在 GitHub 上查看

Karacatica 策略

概述

Karacatica 策略是一种趋势跟随方法,将价格行为与平均趋向指数(ADX)结合使用。当最新收盘价高于或低于 Period 根K线之前的收盘价,并且 +DI 或 -DI 领先时产生交易信号。

指标

  • Average Directional Index (ADX) – 衡量趋势强度,同时提供 +DI 与 -DI 线。
  • 价格比较 – 比较当前收盘价与 Period 根之前的收盘价。

参数

  • Period – 用于ADX计算及价格比较的周期数,默认70。
  • TakeProfitPercent – 以入场价百分比表示的止盈,默认2%。
  • StopLossPercent – 以入场价百分比表示的止损,默认1%。
  • CandleType – 订阅的K线时间框架,默认1小时。

交易逻辑

  • 做多Close > Close[Period]+DI > -DI,并且不存在先前的做多信号时开多仓,平掉空仓。
  • 做空Close < Close[Period]-DI > +DI,并且不存在先前的做空信号时开空仓,平掉多仓。
  • 仓位保护:使用 StartProtection 同时应用止盈和止损百分比。

使用说明

  • 基于 StockSharp 高级 API,订阅K线并绑定 ADX 指标。
  • 当出现反向信号时自动平仓并反向建仓。
  • 当前仅提供 C# 版本,暂不包含 Python 实现。

免责声明

此示例仅用于教育目的,不保证获利。交易具有高风险,请在实盘前充分测试策略。

using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Karacatica strategy uses ADX to determine trend direction and compares
/// current close price with the close price from a specified period ago.
/// It goes long when an uptrend is detected and price is rising, and
/// goes short when a downtrend is detected and price is falling.
/// </summary>
public class KaracaticaStrategy : Strategy
{
	private readonly StrategyParam<int> _period;
	private readonly StrategyParam<DataType> _candleType;

	private AverageDirectionalIndex _adx;
	private readonly Queue<decimal> _closeQueue = new();
	private int _lastSignal;

	/// <summary>
	/// Indicator period used for ADX and price comparison.
	/// </summary>
	public int Period
	{
		get => _period.Value;
		set => _period.Value = value;
	}

	/// <summary>
	/// Candle type parameter.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Constructor.
	/// </summary>
	public KaracaticaStrategy()
	{
		_period = Param(nameof(Period), 30)
			.SetGreaterThanZero()
			.SetDisplay("Period", "ADX period and lookback for close comparison", "Indicators")
			.SetOptimize(20, 50, 10);

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_adx = null;
		_closeQueue.Clear();
		_lastSignal = 0;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_adx = new AverageDirectionalIndex { Length = Period };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(_adx, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _adx);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue adxValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		_closeQueue.Enqueue(candle.ClosePrice);
		if (_closeQueue.Count > Period + 1)
			_closeQueue.Dequeue();

		if (_closeQueue.Count <= Period)
			return;

		if (!adxValue.IsFormed)
			return;

		var pastClose = _closeQueue.Peek();

		var adxTyped = adxValue as IAverageDirectionalIndexValue;
		if (adxTyped?.Dx is not IDirectionalIndexValue dxVal)
			return;

		var plusDi = dxVal.Plus;
		var minusDi = dxVal.Minus;

		if (plusDi is null || minusDi is null)
			return;

		var buySignal = candle.ClosePrice > pastClose && plusDi > minusDi && _lastSignal != 1;
		var sellSignal = candle.ClosePrice < pastClose && minusDi > plusDi && _lastSignal != -1;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (buySignal && Position <= 0)
		{
			BuyMarket();
			_lastSignal = 1;
		}
		else if (sellSignal && Position >= 0)
		{
			SellMarket();
			_lastSignal = -1;
		}
	}
}