在 GitHub 上查看

MA MACD Position Averaging 策略

该策略忠实移植自 MetaTrader 专家顾问 “MA MACD Position averaging”。它使用加权移动平均线与 MACD 比值过滤信号,并在行情对持仓不利时按设定的点数间隔执行“金字塔式”加仓。所有风险参数均以点(pip)为单位配置,并根据 StockSharp 提供的品种属性自动换算为价格偏移量。

交易逻辑

  1. 指标准备
    • 在每根完成的 K 线上计算可配置的移动平均线(MaPeriod、MaMethod、MaAppliedPrice)。SignalBar 与 MaShift 参数复刻了 MetaTrader 读取历史柱线和水平偏移指标的能力。
    • 同时计算 MACD(MacdFastPeriod、MacdSlowPeriod、MacdSignalPeriod、MacdAppliedPrice),并把主线与信号线值存入循环缓冲,以便随时读取历史值而无需直接访问指标接口。
  2. 入场条件
    • 做多:MACD 主线与信号线均小于零,MACDmain / MACDsignal 比值不低于 MacdRatio,收盘价位于移动平均线上方,并且价格与均线的距离不少于 IndentPips 点。
    • 做空:MACD 两条线均大于零,比值高于 MacdRatio,收盘价低于均线且距离不少于 IndentPips 点。
    • 只有在当前无持仓时才会触发新的方向性入场;一旦进入加仓循环,就只执行平均加仓规则。
  3. 加仓模块
    • 若存在多头腿且价格自最佳(最低)买入价下跌至少 StepLossingPips 点,则按“上一腿成交量 × LotCoefficient”的手数再买入一笔(按照品种的最小交易步长向下取整)。
    • 若存在空头腿且价格自最佳(最高)卖出价上升至少 StepLossingPips 点,则按相同公式追加空头。
    • 如果意外出现多空同时存在的情况,策略会立即平掉所有腿以保持状态一致。
  4. 风控与出场
    • 每条腿拥有独立的止损/止盈水平(StopLossPips、TakeProfitPips)。在每根完成的 K 线上检测蜡烛最高价/最低价是否触及这些水平,若触及则通过市价单平仓。
    • 可选的追踪止损(TrailingStopPips、TrailingStepPips)在浮盈超过 TrailingStopPips + TrailingStepPips 点后启动,并将止损向盈利方向移动 TrailingStopPips 点;只有在价格继续前进至少 TrailingStepPips 点时才会再次移动。
  5. 辅助规则
    • 所有下单量都会按合约的最小成交单位对齐,并限制在允许的最小/最大范围内。策略仅在 CandleStates.Finished 状态下处理数据,避免重复触发。

参数

参数 类型 默认值 说明
CandleType DataType TimeSpan.FromHours(1).TimeFrame() 指标计算所用的时间框架。
OrderVolume decimal 0.1 首次入场的基础手数。
StopLossPips int 50 止损距离(点),0 表示禁用。
TakeProfitPips int 50 止盈距离(点),0 表示禁用。
TrailingStopPips int 5 追踪止损与价格之间的距离(点)。启用追踪时必须大于 0。
TrailingStepPips int 5 追踪止损每次前移所需的额外利润(点)。
StepLossingPips int 30 触发加仓所需的反向波动幅度(点)。
LotCoefficient decimal 2.0 每次加仓的成交量系数。
SignalBar int 0 指标采样向前回看的完成柱数量。
MaPeriod int 15 移动平均线长度。
MaShift int 0 移动平均线的水平偏移(柱数)。
MaMethod MovingAverageMethod Weighted 移动平均的平滑方式(简单、指数、平滑、加权)。
MaAppliedPrice AppliedPriceType Weighted 输入到移动平均线的价格类型。
IndentPips int 4 入场时价格与均线的最小间隔(点)。
MacdFastPeriod int 12 MACD 快速 EMA 周期。
MacdSlowPeriod int 26 MACD 慢速 EMA 周期。
MacdSignalPeriod int 9 MACD 信号线周期。
MacdAppliedPrice AppliedPriceType Weighted MACD 使用的价格类型。
MacdRatio decimal 0.9 MACD 主线/信号线的最低允许比值。

点值换算

StopLossPips、TakeProfitPips、TrailingStopPips、TrailingStepPips、StepLossingPips、IndentPips 等参数会乘以品种的 PriceStep。若报价保留 3 或 5 位小数,则额外乘以 10 以匹配 MetaTrader 对“pip”的定义;若缺少步长信息,则使用 0.0001 作为默认值。

实现细节

  • 由于 StockSharp 使用净持仓模式,策略在内部维护一个腿列表,每条腿都记录入场价、止损和止盈,以复现 MetaTrader 中逐单管理的行为。
  • 止损/止盈通过软件模拟实现:当蜡烛触碰到相应水平时,在同一根蜡烛上用市价单平仓。
  • 当 StepLossingPips 为 0 时自动停用加仓逻辑;否则新腿的手数等于上一腿手数乘以 LotCoefficient,并按交易单位向下取整。
  • 追踪止损以蜡烛收盘价作为当前价格参考,只会向盈利方向移动,且必须等到收益超过 TrailingStopPips + TrailingStepPips 点才会启动。
  • 指标缓冲遵循 SignalBar 与 MaShift 设置,因此决策所使用的数据与原始 MetaTrader 指标缓冲保持一致。
using System;
using System.Collections.Generic;
using System.Linq;

using Ecng.Common;

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

namespace StockSharp.Samples.Strategies;

public enum MaMacdMovingAverageMethod
{
	Simple,
	Exponential,
	Smoothed,
	Weighted,
}

public enum MaMacdAppliedPrice
{
	Close,
	Open,
	High,
	Low,
	Median,
	Typical,
	Weighted,
}

/// <summary>
/// MA + MACD position averaging strategy.
/// </summary>
public class MaMacdPositionAveragingStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<int> _trailingStopPips;
	private readonly StrategyParam<int> _trailingStepPips;
	private readonly StrategyParam<int> _stepLossingPips;
	private readonly StrategyParam<decimal> _lotCoefficient;
	private readonly StrategyParam<int> _signalBar;
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<int> _maShift;
	private readonly StrategyParam<MaMacdMovingAverageMethod> _maMethod;
	private readonly StrategyParam<MaMacdAppliedPrice> _maAppliedPrice;
	private readonly StrategyParam<int> _indentPips;
	private readonly StrategyParam<int> _macdFastPeriod;
	private readonly StrategyParam<int> _macdSlowPeriod;
	private readonly StrategyParam<int> _macdSignalPeriod;
	private readonly StrategyParam<MaMacdAppliedPrice> _macdAppliedPrice;
	private readonly StrategyParam<decimal> _macdRatio;

	private readonly List<decimal> _maInputs = [];
	private readonly List<decimal> _maValues = [];
	private readonly List<(decimal Main, decimal Signal)> _macdValues = [];
	private readonly List<Leg> _legs = [];

	private decimal? _macdFast;
	private decimal? _macdSlow;
	private decimal? _macdSignal;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public decimal OrderVolume { get => _orderVolume.Value; set => _orderVolume.Value = value; }
	public int StopLossPips { get => _stopLossPips.Value; set => _stopLossPips.Value = value; }
	public int TakeProfitPips { get => _takeProfitPips.Value; set => _takeProfitPips.Value = value; }
	public int TrailingStopPips { get => _trailingStopPips.Value; set => _trailingStopPips.Value = value; }
	public int TrailingStepPips { get => _trailingStepPips.Value; set => _trailingStepPips.Value = value; }
	public int StepLossingPips { get => _stepLossingPips.Value; set => _stepLossingPips.Value = value; }
	public decimal LotCoefficient { get => _lotCoefficient.Value; set => _lotCoefficient.Value = value; }
	public int SignalBar { get => _signalBar.Value; set => _signalBar.Value = value; }
	public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
	public int MaShift { get => _maShift.Value; set => _maShift.Value = value; }
	public MaMacdMovingAverageMethod MaMethod { get => _maMethod.Value; set => _maMethod.Value = value; }
	public MaMacdAppliedPrice MaAppliedPrice { get => _maAppliedPrice.Value; set => _maAppliedPrice.Value = value; }
	public int IndentPips { get => _indentPips.Value; set => _indentPips.Value = value; }
	public int MacdFastPeriod { get => _macdFastPeriod.Value; set => _macdFastPeriod.Value = value; }
	public int MacdSlowPeriod { get => _macdSlowPeriod.Value; set => _macdSlowPeriod.Value = value; }
	public int MacdSignalPeriod { get => _macdSignalPeriod.Value; set => _macdSignalPeriod.Value = value; }
	public MaMacdAppliedPrice MacdAppliedPrice { get => _macdAppliedPrice.Value; set => _macdAppliedPrice.Value = value; }
	public decimal MacdRatio { get => _macdRatio.Value; set => _macdRatio.Value = value; }

	public MaMacdPositionAveragingStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame());
		_orderVolume = Param(nameof(OrderVolume), 0.1m).SetGreaterThanZero();
		_stopLossPips = Param(nameof(StopLossPips), 50).SetNotNegative();
		_takeProfitPips = Param(nameof(TakeProfitPips), 50).SetNotNegative();
		_trailingStopPips = Param(nameof(TrailingStopPips), 5).SetNotNegative();
		_trailingStepPips = Param(nameof(TrailingStepPips), 5).SetNotNegative();
		_stepLossingPips = Param(nameof(StepLossingPips), 30).SetNotNegative();
		_lotCoefficient = Param(nameof(LotCoefficient), 2m).SetGreaterThanZero();
		_signalBar = Param(nameof(SignalBar), 0).SetNotNegative();
		_maPeriod = Param(nameof(MaPeriod), 15).SetGreaterThanZero();
		_maShift = Param(nameof(MaShift), 0).SetNotNegative();
		_maMethod = Param(nameof(MaMethod), MaMacdMovingAverageMethod.Weighted);
		_maAppliedPrice = Param(nameof(MaAppliedPrice), MaMacdAppliedPrice.Weighted);
		_indentPips = Param(nameof(IndentPips), 4).SetNotNegative();
		_macdFastPeriod = Param(nameof(MacdFastPeriod), 12).SetGreaterThanZero();
		_macdSlowPeriod = Param(nameof(MacdSlowPeriod), 26).SetGreaterThanZero();
		_macdSignalPeriod = Param(nameof(MacdSignalPeriod), 9).SetGreaterThanZero();
		_macdAppliedPrice = Param(nameof(MacdAppliedPrice), MaMacdAppliedPrice.Weighted);
		_macdRatio = Param(nameof(MacdRatio), 0.9m).SetNotNegative();
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_maInputs.Clear();
		_maValues.Clear();
		_macdValues.Clear();
		_legs.Clear();
		_macdFast = null;
		_macdSlow = null;
		_macdSignal = null;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		SubscribeCandles(CandleType).Bind(ProcessCandle).Start();
	}

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

		UpdateIndicators(candle);

		if (_legs.Select(l => l.Side).Distinct().Count() > 1)
		{
			FlattenAll();
			return;
		}

		ApplyProtection(candle);

		if (_legs.Count > 0)
		{
			TryAverage(candle.ClosePrice, candle.OpenTime);
			return;
		}

		if (Position != 0)
			return;

		var maIndex = _maValues.Count - 1 - SignalBar - MaShift;
		var macdIndex = _macdValues.Count - 1 - SignalBar;

		if (maIndex < 0 || macdIndex < 0)
			return;

		var ma = _maValues[maIndex];
		var (main, signal) = _macdValues[macdIndex];

		if (signal == 0m)
			return;

		var ratio = main / signal;
		var pip = GetPipSize();
		var indent = IndentPips * pip;
		var close = candle.ClosePrice;

		if (main < 0m && signal < 0m && ratio >= MacdRatio && close > ma && close - ma >= indent)
			AddLeg(Sides.Buy, NormalizeVolume(OrderVolume), close, candle.OpenTime);
		else if (main > 0m && signal > 0m && ratio >= MacdRatio && close < ma && ma - close >= indent)
			AddLeg(Sides.Sell, NormalizeVolume(OrderVolume), close, candle.OpenTime);
	}

	private void UpdateIndicators(ICandleMessage candle)
	{
		var maPrice = GetAppliedPrice(candle, MaAppliedPrice);
		_maInputs.Add(maPrice);
		_maValues.Add(CalculateMa(_maInputs, MaPeriod, MaMethod));

		var macdPrice = GetAppliedPrice(candle, MacdAppliedPrice);
		_macdFast = Ema(_macdFast, macdPrice, MacdFastPeriod, 2m);
		_macdSlow = Ema(_macdSlow, macdPrice, MacdSlowPeriod, 2m);
		var main = _macdFast.Value - _macdSlow.Value;
		_macdSignal = Ema(_macdSignal, main, MacdSignalPeriod, 2m);
		_macdValues.Add((main, _macdSignal.Value));

		var keep = Math.Max(MaPeriod + MaShift + SignalBar + 10, MacdSlowPeriod + MacdSignalPeriod + SignalBar + 10);
		if (_maInputs.Count > keep)
		{
			var remove = _maInputs.Count - keep;
			_maInputs.RemoveRange(0, remove);
			_maValues.RemoveRange(0, remove);
			_macdValues.RemoveRange(0, remove);
		}
	}

	private void TryAverage(decimal close, DateTimeOffset candleTime)
	{
		if (StepLossingPips <= 0 || _legs.Count == 0)
			return;

		var side = _legs[0].Side;
		if (_legs.Any(l => l.Side != side))
			return;

		var pip = GetPipSize();
		var distance = StepLossingPips * pip;
		var lastVolume = _legs[^1].Volume;
		var volume = NormalizeVolume(lastVolume * LotCoefficient);

		if (side == Sides.Buy)
		{
			var bestEntry = _legs.Min(l => l.EntryPrice);
			if (close <= bestEntry - distance)
				AddLeg(Sides.Buy, volume, close, candleTime);
		}
		else
		{
			var bestEntry = _legs.Max(l => l.EntryPrice);
			if (close >= bestEntry + distance)
				AddLeg(Sides.Sell, volume, close, candleTime);
		}
	}

	private void ApplyProtection(ICandleMessage candle)
	{
		if (_legs.Count == 0)
			return;

		var pip = GetPipSize();
		var exitBuy = 0m;
		var exitSell = 0m;

		for (var i = _legs.Count - 1; i >= 0; i--)
		{
			var leg = _legs[i];
			if (candle.OpenTime <= leg.EntryTime)
				continue;

			var stopPrice = leg.StopPrice;
			var takePrice = leg.TakePrice;
			var hit = leg.Side == Sides.Buy
				? (stopPrice is decimal stop && candle.LowPrice <= stop) || (takePrice is decimal take && candle.HighPrice >= take)
				: (stopPrice is decimal shortStop && candle.HighPrice >= shortStop) || (takePrice is decimal shortTake && candle.LowPrice <= shortTake);

			if (!hit)
			{
				// A stop moved on this close only guards the candles that follow.
				UpdateTrailing(leg, candle.ClosePrice, pip);
				continue;
			}

			if (leg.Side == Sides.Buy)
				exitSell += leg.Volume;
			else
				exitBuy += leg.Volume;

			_legs.RemoveAt(i);
		}

		if (exitSell > 0m)
			SellMarket(exitSell);
		if (exitBuy > 0m)
			BuyMarket(exitBuy);
	}

	private void UpdateTrailing(Leg leg, decimal close, decimal pip)
	{
		if (TrailingStopPips <= 0 || TrailingStepPips < 0)
			return;

		var trail = TrailingStopPips * pip;
		var step = TrailingStepPips * pip;

		if (leg.Side == Sides.Buy)
		{
			if (close - leg.EntryPrice < trail + step)
				return;

			var candidate = close - trail;
			if (leg.StopPrice is null || candidate >= leg.StopPrice.Value + step)
				leg.StopPrice = candidate;
		}
		else
		{
			if (leg.EntryPrice - close < trail + step)
				return;

			var candidate = close + trail;
			if (leg.StopPrice is null || candidate <= leg.StopPrice.Value - step)
				leg.StopPrice = candidate;
		}
	}

	private void AddLeg(Sides side, decimal volume, decimal price, DateTimeOffset entryTime)
	{
		if (volume <= 0m)
			return;

		if (side == Sides.Buy)
			BuyMarket(volume);
		else
			SellMarket(volume);

		var pip = GetPipSize();
		var stopDistance = StopLossPips * pip;
		var takeDistance = TakeProfitPips * pip;

		_legs.Add(new Leg
		{
			Side = side,
			Volume = volume,
			EntryPrice = price,
			EntryTime = entryTime,
			StopPrice = StopLossPips > 0 ? side == Sides.Buy ? price - stopDistance : price + stopDistance : null,
			TakePrice = TakeProfitPips > 0 ? side == Sides.Buy ? price + takeDistance : price - takeDistance : null,
		});
	}

	private void FlattenAll()
	{
		if (Position > 0)
			SellMarket(Math.Abs(Position));
		else if (Position < 0)
			BuyMarket(Math.Abs(Position));

		_legs.Clear();
	}

	private decimal NormalizeVolume(decimal volume)
	{
		if (Security?.MaxVolume is decimal max && max > 0m)
			volume = Math.Min(volume, max);
		if (Security?.MinVolume is decimal min && min > 0m)
			volume = Math.Max(volume, min);
		if (Security?.VolumeStep is decimal step && step > 0m)
			volume = Math.Floor(volume / step) * step;

		return volume;
	}

	private decimal GetPipSize()
	{
		var step = Security?.PriceStep ?? 0m;
		if (step <= 0m)
			return 0.0001m;

		return step is 0.00001m or 0.001m ? step * 10m : step;
	}

	private static decimal GetAppliedPrice(ICandleMessage candle, MaMacdAppliedPrice type)
		=> type switch
		{
			MaMacdAppliedPrice.Open => candle.OpenPrice,
			MaMacdAppliedPrice.High => candle.HighPrice,
			MaMacdAppliedPrice.Low => candle.LowPrice,
			MaMacdAppliedPrice.Median => (candle.HighPrice + candle.LowPrice) / 2m,
			MaMacdAppliedPrice.Typical => (candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 3m,
			MaMacdAppliedPrice.Weighted => (candle.HighPrice + candle.LowPrice + 2m * candle.ClosePrice) / 4m,
			_ => candle.ClosePrice,
		};

	private static decimal CalculateMa(List<decimal> values, int period, MaMacdMovingAverageMethod method)
	{
		var count = Math.Min(period, values.Count);
		var start = values.Count - count;

		if (method == MaMacdMovingAverageMethod.Weighted)
		{
			var weighted = 0m;
			var weights = 0m;
			for (var i = 0; i < count; i++)
			{
				var weight = i + 1m;
				weighted += values[start + i] * weight;
				weights += weight;
			}
			return weighted / weights;
		}

		if (method == MaMacdMovingAverageMethod.Simple)
			return values.Skip(start).Average();

		var alpha = method == MaMacdMovingAverageMethod.Smoothed ? 1m / period : 2m / (period + 1m);
		var result = values[start];
		for (var i = start + 1; i < values.Count; i++)
			result += alpha * (values[i] - result);
		return result;
	}

	private static decimal Ema(decimal? previous, decimal value, int period, decimal numerator)
	{
		if (previous is null)
			return value;

		var alpha = numerator / (period + 1m);
		return previous.Value + alpha * (value - previous.Value);
	}

	private sealed class Leg
	{
		public Sides Side { get; init; }
		public decimal Volume { get; init; }
		public decimal EntryPrice { get; init; }
		public DateTimeOffset EntryTime { get; init; }
		public decimal? StopPrice { get; set; }
		public decimal? TakePrice { get; init; }
	}
}