在 GitHub 上查看

移动平均资金策略

概览

该策略是 MetaTrader 专家顾问“Moving Average Money”的 StockSharp 版本。策略只在蜡烛完全收盘后进行评估,当上一根蜡烛与带有可视化位移的简单移动平均线发生交叉时发出信号。系统同时支持多头与空头交易,并且全部逻辑都通过高级蜡烛订阅 API 执行。

交易逻辑

  • 基于收盘价计算具有可配置周期和位移的简单移动平均线。
  • 仅在蜡烛收盘后处理数据,从而避免同一根蜡烛重复下单。
  • 做空条件: 上一根蜡烛开盘价位于移动平均线之上,而收盘价位于其下方。
  • 做多条件: 上一根蜡烛开盘价位于移动平均线之下,而收盘价位于其上方。
  • 策略不会在已有仓位上加码,若存在反向持仓会先行平仓再入场。

风险控制

  • 通过 MaximumRiskPercent 将组合当前价值转换为价格步进单位,从而确定止损距离。
  • 若可获得买一卖一报价,会在风险距离中扣除价差的影响。
  • 止盈价格等于止损距离乘以 ProfitLossFactor
  • 止损与止盈均在蜡烛收盘时监控,任一触发都会使用市价单平仓。

参数

  • CandleType – 生成信号的时间框架。
  • MovingPeriod – 简单移动平均线的周期。
  • MovingShift – 将移动平均线向右位移的已完成蜡烛数量。
  • MaximumRiskPercent – 每笔交易允许承担的账户价值百分比。
  • ProfitLossFactor – 将止损距离转换为止盈距离的倍数。
  • TradeVolume – 新建仓位时使用的基础下单量(会自动符合成交量步长要求)。

实现说明

  • 策略通过 OnOwnTradeReceived 事件跟踪持仓状态,并在成交后重新初始化止损和止盈。
  • 如果缺少行情报价或投资组合估值信息,会跳过新入场,以保证风险控制有效。
  • 移动平均线的位移通过内部缓冲队列模拟,以保持与 MetaTrader 版本一致的行为。
using System;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Moving Average Money: EMA crossover with ATR stops.
/// </summary>
public class MovingAverageMoneyStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _fastEmaLength;
	private readonly StrategyParam<int> _slowEmaLength;
	private readonly StrategyParam<int> _atrLength;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;

	public MovingAverageMoneyStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe.", "General");
		_fastEmaLength = Param(nameof(FastEmaLength), 12)
			.SetDisplay("Fast EMA", "Fast EMA period.", "Indicators");
		_slowEmaLength = Param(nameof(SlowEmaLength), 26)
			.SetDisplay("Slow EMA", "Slow EMA period.", "Indicators");
		_atrLength = Param(nameof(AtrLength), 14)
			.SetDisplay("ATR Length", "ATR period.", "Indicators");
	}

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int FastEmaLength { get => _fastEmaLength.Value; set => _fastEmaLength.Value = value; }
	public int SlowEmaLength { get => _slowEmaLength.Value; set => _slowEmaLength.Value = value; }
	public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }

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

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
		var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };
		var atr = new AverageTrueRange { Length = AtrLength };
		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(fastEma, slowEma, atr, ProcessCandle).Start();
		var area = CreateChartArea();
		if (area != null) { DrawCandles(area, subscription); DrawIndicator(area, fastEma); DrawIndicator(area, slowEma); DrawOwnTrades(area); }
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastVal, decimal slowVal, decimal atrVal)
	{
		if (candle.State != CandleStates.Finished) return;
		if (_prevFast == 0 || _prevSlow == 0 || atrVal <= 0) { _prevFast = fastVal; _prevSlow = slowVal; return; }
		var close = candle.ClosePrice;

		if (Position > 0)
		{
			if ((fastVal < slowVal && _prevFast >= _prevSlow) || close <= _entryPrice - atrVal * 2m) { SellMarket(); _entryPrice = 0; }
		}
		else if (Position < 0)
		{
			if ((fastVal > slowVal && _prevFast <= _prevSlow) || close >= _entryPrice + atrVal * 2m) { BuyMarket(); _entryPrice = 0; }
		}

		if (Position == 0)
		{
			if (fastVal > slowVal && _prevFast <= _prevSlow) { _entryPrice = close; BuyMarket(); }
			else if (fastVal < slowVal && _prevFast >= _prevSlow) { _entryPrice = close; SellMarket(); }
		}
		_prevFast = fastVal; _prevSlow = slowVal;
	}
}