在 GitHub 上查看

Donchain Counter 策略

概述

Donchain Counter 策略是将 MQL5 专家顾问 “Donchain counter”(作者 Michal Rutka)迁移到 StockSharp 的实现。策略关注 Donchian 通道的扩张来捕捉突破行情,并在价格离开通道一定距离后,把止损沿着相反的通道边界进行跟踪。为了与原始脚本保持一致,每 24 小时只能开仓一次。

交易逻辑

多头开仓

  • 只在所选周期(默认 H1)的完整 K 线收盘后评估信号。
  • 如果上一根 K 线 (t-1) 的 Donchian 上轨高于前一根 K 线 (t-2) 的上轨,说明通道向上突破,立即以市价买入。
  • 初始止损设置在当前的 Donchian 下轨。

空头开仓

  • 如果上一根 K 线 (t-1) 的 Donchian 下轨低于前一根 K 线 (t-2) 的下轨,说明通道向下突破,立即以市价卖出。
  • 初始止损设置在当前的 Donchian 上轨。

交易冷却

  • 每次新开仓都会记录时间,在 TradeCooldown(默认 24 小时)过去之前禁止再次开仓,从而复现原策略“一天最多一笔交易”的限制。

跟踪与平仓

  • 只有当价格至少离相反的通道边界 BufferSteps 个最小价格步长时,才激活跟踪止损(MQL 中使用 50 点)。
  • 多头:激活后将止损移动到当前的 Donchian 下轨;若后续某根 K 线的最低价触及该水平,则以市价卖出平仓。
  • 空头:激活后将止损移动到当前的 Donchian 上轨;若某根 K 线的最高价到达该水平,则以市价买入平仓。
  • 被止损平仓后,策略会等待下一次信号并检查冷却时间,再决定是否重新入场。

风险控制

  • 始终只持有一个仓位,仓位大小由 Volume 参数决定。
  • 没有固定的止盈目标,所有离场动作都由 Donchian 通道的跟踪规则触发。

参数

名称 说明 默认值
Volume 每次下单的数量。 1
ChannelPeriod Donchian 通道的回溯周期。 20
BufferSteps 价格在相反通道之外需要移动的最小步长数,达到后才启动跟踪止损。 50
TradeCooldown 连续开仓之间的最短时间。 1 天
CandleType 用于分析的 K 线类型(默认 1 小时)。 1h

指标

  • Donchian Channels —— 上下轨既提供突破信号,也作为跟踪止损的参考水平。

注意事项

  • 请使用具有合理 PriceStep 的品种,保证 BufferSteps 对应的价格距离有效;若未提供价格步长,策略默认使用 0.0001。
  • 策略不会同时持有多头与空头仓位,反向交易前必须平掉原有仓位。
  • 如果环境支持图表渲染,将自动绘制价格 K 线、Donchian 通道以及策略成交点位。
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>
/// Donchain Counter strategy converted from MQL5 Donchain counter expert advisor.
/// Tracks Donchian channel expansions for entries and trails stops along the channel bands.
/// </summary>
public class DonchainCounterStrategy : Strategy
{
	private readonly StrategyParam<int> _channelPeriod;
	private readonly StrategyParam<int> _bufferSteps;
	private readonly StrategyParam<TimeSpan> _tradeCooldown;
	private readonly StrategyParam<DataType> _candleType;

	private DonchianChannels _donchian = null!;
	private decimal _priceStep;
	private decimal _tolerance;
	private decimal _currentUpper;
	private decimal _currentLower;
	private decimal _previousUpper;
	private decimal _previousLower;
	private decimal _earlierUpper;
	private decimal _earlierLower;
	private decimal? _longStopLevel;
	private decimal? _shortStopLevel;
	private DateTimeOffset? _lastTradeTime;

	/// <summary>
	/// Initializes a new instance of <see cref="DonchainCounterStrategy"/>.
	/// </summary>
	public DonchainCounterStrategy()
	{

		_channelPeriod = Param(nameof(ChannelPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Donchian Period", "Lookback period for Donchian Channel", "Indicators")
			
			.SetOptimize(10, 40, 5);

		_bufferSteps = Param(nameof(BufferSteps), 50)
			.SetGreaterThanZero()
			.SetDisplay("Buffer Steps", "Minimum price steps before trailing stop activates", "Risk");

		_tradeCooldown = Param(nameof(TradeCooldown), TimeSpan.FromMinutes(30))
			.SetDisplay("Trade Cooldown", "Minimum waiting time between new entries", "Risk Management");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle Type", "Candle series used for Donchian evaluation", "General");
	}


	/// <summary>
	/// Donchian channel lookback period.
	/// </summary>
	public int ChannelPeriod
	{
		get => _channelPeriod.Value;
		set => _channelPeriod.Value = value;
	}

	/// <summary>
	/// Number of price steps that price must move beyond the opposite band before trailing starts.
	/// </summary>
	public int BufferSteps
	{
		get => _bufferSteps.Value;
		set => _bufferSteps.Value = value;
	}

	/// <summary>
	/// Minimum cooldown between new trades.
	/// </summary>
	public TimeSpan TradeCooldown
	{
		get => _tradeCooldown.Value;
		set => _tradeCooldown.Value = value;
	}

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

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

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

		_donchian = null!;
		_priceStep = 0m;
		_tolerance = 0m;
		_currentUpper = 0m;
		_currentLower = 0m;
		_previousUpper = 0m;
		_previousLower = 0m;
		_earlierUpper = 0m;
		_earlierLower = 0m;
		_longStopLevel = null;
		_shortStopLevel = null;
		_lastTradeTime = null;
	}

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

		_priceStep = Security?.PriceStep ?? 0m;
		if (_priceStep <= 0m)
		{
			_priceStep = 0.0001m;
		}

		_tolerance = _priceStep / 2m;

		_donchian = new DonchianChannels
		{
			Length = ChannelPeriod
		};

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(ProcessDonchianRaw)
			.Start();

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

	private void ProcessDonchianRaw(ICandleMessage candle)
	{
		if (candle.State != CandleStates.Finished)
			return;

		var donchianValue = _donchian.Process(candle);
		if (donchianValue.IsEmpty || !_donchian.IsFormed)
			return;

		var value = (DonchianChannelsValue)donchianValue;

		if (value.UpperBand is not decimal upperBand || value.LowerBand is not decimal lowerBand)
			return;

		_currentUpper = upperBand;
		_currentLower = lowerBand;

		var hadPosition = Position != 0m;
		if (hadPosition)
		{
			ManageExistingPosition(candle);
			UpdateHistory();
			return;
		}

		TryOpenPosition(candle);
		UpdateHistory();
	}

	private void ManageExistingPosition(ICandleMessage candle)
	{
		// Buffer converts the point-based activation threshold into price units.
		var buffer = BufferSteps * _priceStep;

		if (Position > 0m)
		{
			// Activate or advance the trailing stop once price moves far enough from the lower band.
			if (candle.HighPrice > _currentLower + buffer)
			{
				if (!_longStopLevel.HasValue || _longStopLevel.Value < _currentLower - _tolerance)
				{
					_longStopLevel = _currentLower;
					// Log: $"Updated long stop to {_longStopLevel.Value}");
				}
			}

			// Exit the long position when price falls back through the protected band.
			if (_longStopLevel.HasValue && candle.LowPrice <= _longStopLevel.Value + _tolerance)
			{
				SellMarket(Position);
				// Log: $"Long exit triggered at {_longStopLevel.Value}");
				_longStopLevel = null;
			}
		}
		else if (Position < 0m)
		{
			// Activate or advance the trailing stop once price moves far enough from the upper band.
			if (candle.LowPrice < _currentUpper - buffer)
			{
				if (!_shortStopLevel.HasValue || _shortStopLevel.Value > _currentUpper + _tolerance)
				{
					_shortStopLevel = _currentUpper;
					// Log: $"Updated short stop to {_shortStopLevel.Value}");
				}
			}

			// Exit the short position when price rallies back to the protected band.
			if (_shortStopLevel.HasValue && candle.HighPrice >= _shortStopLevel.Value - _tolerance)
			{
				BuyMarket(Math.Abs(Position));
				// Log: $"Short exit triggered at {_shortStopLevel.Value}");
				_shortStopLevel = null;
			}
		}
		else
		{
			_longStopLevel = null;
			_shortStopLevel = null;
		}
	}

	private void TryOpenPosition(ICandleMessage candle)
	{
		// Require at least two completed Donchian samples for breakout comparisons.
		if (_previousUpper == 0m || _earlierUpper == 0m || _previousLower == 0m || _earlierLower == 0m)
		{
			return;
		}

		var now = candle.CloseTime;
		if (_lastTradeTime.HasValue && now - _lastTradeTime.Value < TradeCooldown)
		{
			return;
		}

		// Long entry when the upper Donchian band expanded on the previous bar.
		if (_previousUpper > _earlierUpper && !AreClose(_previousUpper, _earlierUpper))
		{
			BuyMarket(Volume);
			_longStopLevel = _currentLower;
			_lastTradeTime = now;
			// Log: $"Long entry at {candle.ClosePrice} with stop {_currentLower}");
			return;
		}

		// Short entry when the lower Donchian band contracted on the previous bar.
		if (_previousLower < _earlierLower && !AreClose(_previousLower, _earlierLower))
		{
			SellMarket(Volume);
			_shortStopLevel = _currentUpper;
			_lastTradeTime = now;
			// Log: $"Short entry at {candle.ClosePrice} with stop {_currentUpper}");
		}
	}

	private void UpdateHistory()
	{
		_earlierUpper = _previousUpper;
		_earlierLower = _previousLower;
		_previousUpper = _currentUpper;
		_previousLower = _currentLower;
	}

	private bool AreClose(decimal first, decimal second)
	{
		return Math.Abs(first - second) <= _tolerance;
	}

	/// <inheritdoc />
	protected override void OnPositionReceived(Position position)
	{
		base.OnPositionReceived(position);

		if (Position == 0m)
		{
			_longStopLevel = null;
			_shortStopLevel = null;
		}
		else if (Position > 0m)
		{
			_shortStopLevel = null;
		}
		else
		{
			_longStopLevel = null;
		}
	}
}