在 GitHub 上查看

三根典型价格蜡烛策略

概述

三根典型价格蜡烛策略 在 StockSharp 高级 API 中重现了 MetaTrader 的 "Three Typical Candles" 专家顾问。策略对每根已完成蜡烛的典型价格(高、低、收盘价的平均值)进行跟踪,只要最近三根蜡烛的典型价格呈现严格单调的上升或下降序列,就会入场交易。

此移植版本最大限度地保持了原始 MQL5 代码的特征:

  • 信号只在蜡烛收盘时评估一次,避免了盘中噪声。
  • 可配置的交易时段过滤器能够限制策略仅在指定的小时段内运行,并在禁止交易时强制平仓。
  • 开仓前始终平掉相反方向的持仓,保证账户在任何时刻仅持有一个方向。
  • 订单体量沿用固定手数模式,同时遵循交易所的最小手数、最大手数以及成交量步长要求。

交易规则

  1. 信号识别
    • 对每根已完成的蜡烛计算典型价格 Tp = (High + Low + Close) / 3
    • 保存前两根蜡烛的典型价格。当拥有三个数值时,检查是否形成严格的上升或下降序列。
  2. 做多条件
    • Tp[-2] < Tp[-1] < Tp[0](连续三根典型价格上升)且当前没有多头持仓,则先平掉空头,再市价买入。
  3. 做空条件
    • Tp[-2] > Tp[-1] > Tp[0](连续三根典型价格下降)且当前没有空头持仓,则先平掉多头,再市价卖出。
  4. 时间过滤
    • 当启用 UseTimeControl 时,仅当蜡烛开盘时间落在 StartHour(含)和 EndHour(不含)之间才会评估信号。若时间超出窗口,策略会立即平仓并停止下单。若起止时间跨越午夜(StartHour > EndHour),交易窗口将覆盖晚间与次日清晨。
  5. 仓位管理
    • 策略没有内置止盈或止损。风险控制需要通过外部保护策略或人工监控来实现。

参数说明

名称 类型 默认值 说明
Volume decimal 1 固定下单手数。策略会自动按照交易品种的成交量步长四舍五入,并且不会突破最小/最大允许手数。
UseTimeControl bool true 是否启用日内交易时间过滤。关闭后策略全天候评估信号。
StartHour int 11 启用时间过滤时的开始小时(含,0-23)。
EndHour int 17 启用时间过滤时的结束小时(不含,0-23)。若小于开始小时,则交易时段跨越午夜。
CandleType DataType TimeFrame(1h) 用于分析的蜡烛类型,可根据数据源选择不同周期。

实现细节

  • 策略通过 SubscribeCandles 订阅蜡烛,并在 ProcessCandle 中处理已完成的蜡烛数据。
  • 发生反向信号时,会先调用 BuyMarketSellMarket 平掉现有仓位,然后再根据新信号开仓。
  • OnStarted 中调用 StartProtection(),方便后续接入 StockSharp 的保护性组件(如全局止损/止盈)。
  • GetTradeVolume 方法负责模拟 MetaTrader 的手数规范化逻辑,使所下手数与交易所约束保持一致。
  • 仅保存最近两根典型价格即可完成判断,无需维护额外的数据集合,执行效率高。

使用建议

  • 适用于具有足够流动性的市场。原始 EA 面向外汇品种,但任何提供 OHLC 数据的市场都可尝试。
  • 可以通过优化参数调整蜡烛周期,以匹配不同的交易节奏。默认的一小时蜡烛与原策略一致。
  • 建议配合账户级别的风控方案,例如最大回撤限制或组合止损,以弥补策略缺少硬性止损的缺陷。
  • 在正式部署前,应在多品种和多时间段上进行历史回测,验证三连单调典型价格是否具有统计优势。
using System;
using System.Collections.Generic;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

public class ThreeTypicalCandlesStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public ThreeTypicalCandlesStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 15).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 60).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}