在 GitHub 上查看

MovingUp 策略

该策略实现移动平均线交叉,并提供可选的风险控制模块。 当快速均线向上穿越慢速均线时开多仓,反向穿越时开空仓。

参数

  • Fast MA (FastLength): 快速简单移动平均线周期。
  • Slow MA (SlowLength): 慢速简单移动平均线周期。
  • Use TP (UseTakeProfit): 是否启用止盈规则。
  • TP (TakeProfit): 止盈的价格距离。
  • Use SL (UseStopLoss): 是否启用止损规则。
  • SL (StopLoss): 止损的价格距离。
  • Use TS (UseTrailingStop): 是否启用移动止损。
  • TS (TrailingStop): 移动止损的价格距离。
  • Candle (CandleType): 用于计算的K线类型。

交易逻辑

  1. 订阅K线并计算两条SMA指标。
  2. 检测快速与慢速均线的交叉。
  3. 当快速均线向上穿越慢速均线且无多头仓位时买入。
  4. 当快速均线向下穿越慢速均线且无空头仓位时卖出。
  5. 在每根新K线上执行风险控制:
    • 价格达到设定距离后止盈。
    • 价格向不利方向移动到设定距离后止损。
    • 当价格向有利方向移动时,移动止损保护利润。

原始 MQL 策略

原始的 MQL4 脚本 ma_v_1_3_3.mq4 包含更多功能,如分步加仓和复杂仓位管理。本 C# 版本专注于核心的均线交叉逻辑与基础风险控制。

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>
/// Moving average crossover strategy with risk management via StartProtection.
/// </summary>
public class MovingUpStrategy : Strategy
{
	private readonly StrategyParam<int> _fastLength;
	private readonly StrategyParam<int> _slowLength;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<decimal> _takeProfit;
	private readonly StrategyParam<DataType> _candleType;

	private bool _isInitialized;
	private bool _wasFastBelowSlow;

	public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
	public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
	public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
	public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MovingUpStrategy()
	{
		_fastLength = Param(nameof(FastLength), 13)
			.SetGreaterThanZero()
			.SetDisplay("Fast MA", "Fast MA period", "MA");

		_slowLength = Param(nameof(SlowLength), 21)
			.SetGreaterThanZero()
			.SetDisplay("Slow MA", "Slow MA period", "MA");

		_stopLoss = Param(nameof(StopLoss), 250m)
			.SetGreaterThanZero()
			.SetDisplay("SL", "Stop loss distance", "Risk");

		_takeProfit = Param(nameof(TakeProfit), 500m)
			.SetGreaterThanZero()
			.SetDisplay("TP", "Take profit distance", "Risk");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
			.SetDisplay("Candle", "Candle type", "General");
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_isInitialized = default;
		_wasFastBelowSlow = default;
	}

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

		var fastMa = new ExponentialMovingAverage { Length = FastLength };
		var slowMa = new ExponentialMovingAverage { Length = SlowLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastMa, slowMa, ProcessCandle)
			.Start();

		StartProtection(
			new Unit(StopLoss, UnitTypes.Absolute),
			new Unit(TakeProfit, UnitTypes.Absolute));
	}

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (!_isInitialized)
		{
			_wasFastBelowSlow = fast < slow;
			_isInitialized = true;
			return;
		}

		var isFastBelowSlow = fast < slow;

		if (_wasFastBelowSlow != isFastBelowSlow)
		{
			if (!isFastBelowSlow && Position <= 0)
			{
				if (Position < 0)
					BuyMarket();
				BuyMarket();
			}
			else if (isFastBelowSlow && Position >= 0)
			{
				if (Position > 0)
					SellMarket();
				SellMarket();
			}

			_wasFastBelowSlow = isFastBelowSlow;
		}
	}
}