在 GitHub 上查看

Candle 策略

概述

Candle Strategy 是 MT5 经典专家顾问 “Candle.mq5” 的完整移植版。策略在选定周期上分析每一根已完成 K 线的颜色,并让持仓方向始终跟随最新收盘价。收盘价高于开盘价时持有多头,收盘价低于开盘价时持有空头,平收的 K 线则保持现有仓位不变。风险控制通过以点数为单位的止盈和追踪止损来实现,并依据品种的最小报价步长换算成绝对价格。

为避免盘中噪声,策略只在蜡烛完全收盘后做出决策。在开始交易之前,它会确认历史中至少存在 MinBars * 2 根已完成 K 线,并在每次交易后等待一个可配置的冷却时间。凭借这些约束,StockSharp 版本可以忠实地复现原始 MetaTrader 逻辑,而无需直接访问底层时间序列。

交易逻辑

准备阶段

  • 仅订阅 CandleType 指定的蜡烛,不需要其他数据源。
  • 在处理完至少 2 * MinBars 根已完成的蜡烛之前不会开仓。
  • 只有在策略处于在线、已形成且允许交易的状态下才执行订单。
  • 任意两次交易之间都会强制等待 TradeCooldown(默认 10 秒)的冷却时间。

入场与反向规则

  1. 空仓状态:
    • 当蜡烛收盘价高于开盘价时,通过 BuyMarket 建立多头。
    • 当蜡烛收盘价低于开盘价时,通过 SellMarket 建立空头。
  2. 已有仓位:
    • 持有多头且出现阴线时,卖出 |Position| + Volume,先平掉当前仓位,再立即建立大小为 Volume 的空头。
    • 持有空头且出现阳线时,买入 |Position| + Volume,先平掉当前仓位,再立即建立大小为 Volume 的多头。
  3. 十字或平收:
    • 收盘价等于开盘价时不进行手动操作,只保留保护性订单的自动退出。

风险管理与退出

  • 通过 StartProtection 设置以点数计的止盈和追踪止损。策略使用 (PriceStep * 10) 计算点值,与原始专家在 3 位或 5 位报价下的 “digits adjust” 逻辑相一致。
  • 仅当 TrailingStopPips 大于零时才启用追踪止损,盈利时自动沿价格移动。
  • 止盈在达到设定距离后自动平仓,保护性订单执行后会撤销相反方向的挂单。
  • 由于反向操作会先平仓后反手,因此不会与保护性订单产生冲突。

参数

  • CandleType – 用于分析的蜡烛周期(默认 15 分钟)。
  • TakeProfitPips – 止盈距离,单位为点(默认 50 点)。
  • TrailingStopPips – 追踪止损距离,单位为点(默认 30 点)。
  • MinBars – 开始交易前所需的最少历史柱数(默认 26,对应等待 52 根已完成蜡烛)。
  • TradeCooldown – 每次交易后的冷却时间(默认 10 秒)。

请在运行前设置策略的 Volume 属性。策略在反向时会自动发送足够的成交量,既能平掉旧仓位,也能同时建立新仓位。

实现细节

  • 只处理状态为 CandleStates.Finished 的蜡烛,这与原始 MQL 专家通过 CopyOpen/CopyClose 读取已收盘数据的行为一致。
  • 代码完全基于 StockSharp 高层 API:SubscribeCandles 订阅数据,Bind 绑定处理方法,BuyMarket/SellMarket 执行订单。
  • 保护性订单由 StartProtection 自动管理,无需手动维护止损或止盈。
  • 点值计算 (PriceStep * 10) 复刻了原策略在三位和五位报价中的调节方式。
  • 由于信号直接来自最新蜡烛的实体颜色,策略通常持续持仓,并在颜色切换时立即反手。

可以根据所交易的品种调整点距、冷却时间和时间框架。默认参数与 MT5 示例保持一致,也可通过 StockSharp 的参数系统进行优化。

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>
/// Candle color reversal strategy with pip-based protection and trade cooldown.
/// </summary>
public class CandleStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _takeProfitPips;
	private readonly StrategyParam<decimal> _trailingStopPips;
	private readonly StrategyParam<int> _minBars;
	private readonly StrategyParam<TimeSpan> _tradeCooldown;

	private decimal _pipSize;
	private int _finishedCandles;
	private DateTimeOffset _nextAllowedTime;

	/// <summary>
	/// Initializes a new instance of the <see cref="CandleStrategy"/>.
	/// </summary>
	public CandleStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe used for candle evaluation", "General");

		_takeProfitPips = Param(nameof(TakeProfitPips), 50m)
			.SetDisplay("Take Profit (pips)", "Distance to take profit in pips", "Risk")
			.SetGreaterThanZero();

		_trailingStopPips = Param(nameof(TrailingStopPips), 30m)
			.SetDisplay("Trailing Stop (pips)", "Trailing stop distance in pips", "Risk")
			.SetGreaterThanZero();

		_minBars = Param(nameof(MinBars), 26)
			.SetDisplay("Minimum Bars", "History length required before trading", "General")
			.SetGreaterThanZero();

		_tradeCooldown = Param(nameof(TradeCooldown), TimeSpan.FromSeconds(10))
			.SetDisplay("Trade Cooldown", "Waiting time after each trade", "Risk");
	}

	/// <summary>
	/// Candle type and timeframe used by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Take profit distance expressed in pips.
	/// </summary>
	public decimal TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Trailing stop distance expressed in pips.
	/// </summary>
	public decimal TrailingStopPips
	{
		get => _trailingStopPips.Value;
		set => _trailingStopPips.Value = value;
	}

	/// <summary>
	/// Minimum number of bars required on the chart.
	/// </summary>
	public int MinBars
	{
		get => _minBars.Value;
		set => _minBars.Value = value;
	}

	/// <summary>
	/// Cooldown between consecutive trading operations.
	/// </summary>
	public TimeSpan TradeCooldown
	{
		get => _tradeCooldown.Value;
		set => _tradeCooldown.Value = value;
	}

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

		_pipSize = 0m;
		_finishedCandles = 0;
		_nextAllowedTime = DateTimeOffset.MinValue;
	}

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

		_pipSize = (Security?.PriceStep ?? 1m) * 10m;

		Unit takeProfit = TakeProfitPips > 0m && _pipSize > 0m
			? new Unit(TakeProfitPips * _pipSize, UnitTypes.Absolute)
			: null;

		Unit trailingStop = TrailingStopPips > 0m && _pipSize > 0m
			? new Unit(TrailingStopPips * _pipSize, UnitTypes.Absolute)
			: null;

		// Enable automatic protective orders and trailing stop handling.
		if (trailingStop != null || takeProfit != null)
			StartProtection(takeProfit, trailingStop);

		// Subscribe to candle data for the configured timeframe.
		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(ProcessCandle)
			.Start();

		// Draw candles and executions on the chart if visualization is available.
		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle)
	{
		// Skip unfinished candles to work only with final prices.
		if (candle.State != CandleStates.Finished)
			return;

		_finishedCandles++;

		// Wait until the chart has enough historical data.
		if (_finishedCandles < MinBars * 2)
			return;

		var time = candle.CloseTime;

		// Enforce cooldown between trading operations.
		if (time < _nextAllowedTime)
			return;

		var isBullish = candle.ClosePrice > candle.OpenPrice;
		var isBearish = candle.ClosePrice < candle.OpenPrice;

		var tradeExecuted = false;

		if (Position > 0 && isBearish)
		{
			// Reverse from long to short when a bearish candle appears.
			var volume = Math.Abs(Position) + Volume;
			if (volume > 0m)
			{
				SellMarket();
				tradeExecuted = true;
			}
		}
		else if (Position < 0 && isBullish)
		{
			// Reverse from short to long when a bullish candle appears.
			var volume = Math.Abs(Position) + Volume;
			if (volume > 0m)
			{
				BuyMarket();
				tradeExecuted = true;
			}
		}
		else if (Position == 0)
		{
			if (isBullish)
			{
				// Enter long on bullish close.
				if (Volume > 0m)
				{
					BuyMarket();
					tradeExecuted = true;
				}
			}
			else if (isBearish)
			{
				// Enter short on bearish close.
				if (Volume > 0m)
				{
					SellMarket();
					tradeExecuted = true;
				}
			}
		}

		if (tradeExecuted)
		{
			_nextAllowedTime = time + TradeCooldown;
		}
	}
}