在 GitHub 上查看

锚定动量突破策略

概述

锚定动量突破策略通过比较指数移动平均线(EMA)与简单移动平均线(SMA)的比率来评估市场动量。当EMA相对SMA上升时,说明上涨动能增强;当比率下降时,表明下跌动能增强。

工作原理

  1. 指标
    • 可配置周期的EMA。
    • 可配置周期的SMA。
  2. 动量计算
    • Momentum = 100 * (EMA / SMA - 1)
    • 动量为正表示EMA高于SMA。
  3. 交易逻辑
    • 如果动量先下降后上升,策略建立多头仓位。
    • 如果动量先上升后下降,策略建立空头仓位。
    • 下单数量包含现有持仓,以便在信号反向时快速反转。
  4. 风险控制
    • 通过StartProtection设置百分比止损和止盈。

参数

名称 说明
SmaPeriod SMA指标周期。
EmaPeriod EMA指标周期。
StopLossPercent 止损百分比。
TakeProfitPercent 止盈百分比。
CandleType 使用的K线周期。

备注

  • 只处理已完成的K线。
  • 所有交易均以市价单执行。
  • 通过高层Bind接口获取指标数值,无需直接访问历史数据。
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;

/// <summary>
/// Strategy based on anchored momentum indicator.
/// Computes momentum as EMA/SMA ratio and trades reversals.
/// </summary>
public class AnchoredMomentumBreakoutStrategy : Strategy
{
	private readonly StrategyParam<int> _smaPeriod;
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _stopLossPercent;
	private readonly StrategyParam<decimal> _takeProfitPercent;

	private decimal _prev;
	private decimal _prevPrev;
	private bool _initialized;

	public int SmaPeriod { get => _smaPeriod.Value; set => _smaPeriod.Value = value; }
	public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
	public decimal TakeProfitPercent { get => _takeProfitPercent.Value; set => _takeProfitPercent.Value = value; }

	public AnchoredMomentumBreakoutStrategy()
	{
		_smaPeriod = Param(nameof(SmaPeriod), 34)
			.SetDisplay("SMA Period", "Period for simple moving average", "Indicators");
		_emaPeriod = Param(nameof(EmaPeriod), 20)
			.SetDisplay("EMA Period", "Period for exponential moving average", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
		_stopLossPercent = Param(nameof(StopLossPercent), 2m)
			.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management");
		_takeProfitPercent = Param(nameof(TakeProfitPercent), 4m)
			.SetDisplay("Take Profit %", "Take profit percentage", "Risk Management");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_prev = 0;
		_prevPrev = 0;
		_initialized = false;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var sma = new ExponentialMovingAverage { Length = SmaPeriod };
		var ema = new ExponentialMovingAverage { Length = EmaPeriod };
		var sub = SubscribeCandles(CandleType);
		sub.Bind(sma, ema, ProcessCandle).Start();

		StartProtection(
			takeProfit: new Unit(TakeProfitPercent, UnitTypes.Percent),
			stopLoss: new Unit(StopLossPercent, UnitTypes.Percent),
			useMarketOrders: true);

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, sub);
			DrawIndicator(area, sma);
			DrawIndicator(area, ema);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, decimal smaVal, decimal emaVal)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (smaVal == 0)
			return;

		var mom = 100m * (emaVal / smaVal - 1m);

		if (!_initialized)
		{
			_prev = mom;
			_prevPrev = mom;
			_initialized = true;
			return;
		}

		if (_prev < _prevPrev && mom >= _prev && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (_prev > _prevPrev && mom <= _prev && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevPrev = _prev;
		_prev = mom;
	}
}