在 GitHub 上查看

Gann Line 策略

该策略将 MetaTrader 4 中的 “Gann Line” 专家顾问(源文件 24877)迁移到 StockSharp 高级 API。核心的趋势、动量以及慢速 MACD 过滤器全部保留,同时把所有风控参数统一为价格步长,从而避免经纪商差异造成的影响。

交易逻辑

  1. 趋势过滤(主周期)
    • 对典型价格 (High + Low + Close) / 3 计算快慢两条线性加权移动平均线(LWMA)。
    • 做多要求快线收在慢线上方,做空则相反。
  2. 动量确认(高一级周期)
    • 在可配置的高阶周期上计算动量指标,衡量其相对 100 的偏离程度。
    • 最近三根已完成动量值中至少有一个需要超过设定阈值,否则禁止开仓。
  3. 慢速 MACD 过滤(超长周期)
    • 在非常缓慢的周期(默认 30 天)上运行 MACD,主线高于信号线时允许做多,反之允许做空。
  4. 仓位管理
    • 开仓时把止损和止盈的步长转换为实际价格。
    • 可选的保本逻辑在达到指定盈利步长后把止损移动到开仓价并加上偏移。
    • 可选的跟踪止损在价格走出指定利润后,沿最高高点(多头)或最低低点(空头)拖动止损。

风险控制

  • 所有距离(止损、止盈、保本、跟踪)都以价格步长表示,并根据合约的 PriceStep 自动换算为价格。
  • 策略使用基础类的 Volume 属性;若为 0,则默认下单 1 手。
  • 仅维护单一净头寸,反向信号会先平掉当前仓位再反向开仓。

与 MQL4 版本的区别

  • 原脚本依赖手工绘制的 Gann 线。由于 StockSharp 暂无图形对象接口,此处改为 LWMA 趋势过滤器。
  • 资金量化的跟踪止损、分批减仓以及账户权益检查被简化为按步长计算的确定性逻辑。
  • 未实现提醒、邮件、推送等通知,建议通过平台日志监控策略行为。

参数

名称 说明
Fast LWMA 快速 LWMA 的周期。
Slow LWMA 慢速 LWMA 的周期。
Momentum Period 动量指标在高阶周期上的回溯长度。
Momentum Threshold 最近三次动量值相对 100 的最小偏离。
MACD Fast / Slow / Signal 慢速 MACD 的 EMA 周期设置。
Take Profit (steps) 止盈距离(步长)。
Stop Loss (steps) 止损距离(步长)。
Use Trailing, Trail Activation, Trail Distance 是否启用跟踪止损、触发所需利润步长、跟踪距离。
Use BreakEven, BreakEven Activation, BreakEven Offset 是否启用保本、触发利润步长、附加锁定利润。
Primary Timeframe 主逻辑使用的蜡烛类型。
Momentum Timeframe 动量指标使用的蜡烛类型。
MACD Timeframe 慢速 MACD 使用的蜡烛类型。

使用建议

  1. 选择交易品种并设置 Primary Timeframe。默认情况下动量采用 1 小时、MACD 采用 30 天,可根据需要调整以匹配原策略的倍数关系。
  2. 根据合约规格设置 Volume 以及所有基于步长的风险参数。
  3. 在 Designer 或代码中运行策略,并通过日志确认各类过滤条件、保本移动、跟踪止损是否按预期触发。
  4. 针对不同市场或周期,可通过优化调整动量阈值与 MACD 周期。

后续改进思路

  • 增加账户权益风控,与原脚本保持一致。
  • 当 StockSharp 提供图形对象接口时,恢复对手动画线的检测。
  • 引入分批止盈或减仓,进一步贴近 MT4 版本的多目标结构。
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 GannLineStrategy : 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 GannLineStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).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;
	}
}