在 GitHub 上查看

趋势延续策略

该策略利用两条指数移动平均线来识别趋势的延续。当快 EMA 上穿慢 EMA 时开多单;当快 EMA 下穿慢 EMA 时开空单。

参数

  • Fast EMA Length:快线 EMA 的周期(默认 20)。
  • Candle Type:使用的K线周期(默认 4 小时)。
  • Stop Loss:保护性止损,在启动时通过 StartProtection 启用(默认 1000)。
  • Take Profit:盈利目标,通过 StartProtection 启用(默认 2000)。

工作原理

  1. 启动时订阅指定的K线并创建两条 EMA 指标。
  2. 每当收到完成的K线,就检测快慢 EMA 的交叉。
  3. 快线从下向上穿越慢线时开多并关闭空单;相反的交叉则开空并关闭多单。
  4. 通过止损和止盈参数控制风险。

该示例是对原始 MQL Exp_TrendContinuation 专家的简化转换。

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>
/// Trend continuation strategy based on fast and slow EMA cross.
/// Opens long when fast EMA crosses above slow EMA, short on opposite.
/// </summary>
public class TrendContinuationStrategy : Strategy
{
	private readonly StrategyParam<int> _length;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevFast;
	private decimal? _prevSlow;

	public int Length
	{
		get => _length.Value;
		set => _length.Value = value;
	}

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public TrendContinuationStrategy()
	{
		_length = Param(nameof(Length), 20)
			.SetGreaterThanZero()
			.SetDisplay("Fast EMA Length", "Period for the fast EMA", "Indicators");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles to use", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = null;
		_prevSlow = null;
	}

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

		_prevFast = _prevSlow = null;

		var fast = new ExponentialMovingAverage { Length = Length };
		var slow = new ExponentialMovingAverage { Length = Length * 2 };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fast, slow, ProcessCandle)
			.Start();

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (_prevFast.HasValue && _prevSlow.HasValue)
		{
			if (_prevFast < _prevSlow && fast >= slow && Position <= 0)
				BuyMarket();

			if (_prevFast > _prevSlow && fast <= slow && Position >= 0)
				SellMarket();
		}

		_prevFast = fast;
		_prevSlow = slow;
	}
}