在 GitHub 上查看

Mean Reversion Pro 策略

Mean Reversion Pro 是一套针对主要指数的均值回归策略。它使用两条移动平均线和蜡烛区间水平来寻找回撤。由于指数通常向上偏移,因此更推荐做多。

详情

  • 入场条件
    • 多头:收盘价低于快速 SMA,低于区间 20% 水平,高于慢速 SMA,并且当前无仓位。
    • 空头:收盘价高于快速 SMA,高于区间 80% 水平,低于慢速 SMA,并且当前无仓位。
  • 多/空:双向(推荐多头)。
  • 出场条件
    • 多头:收盘价上穿快速 SMA。
    • 空头:收盘价下穿快速 SMA。
  • 止损:无。
  • 默认值
    • 快速 SMA = 5
    • 慢速 SMA = 100
    • 方向 = 仅做多
  • 过滤器
    • 类别:均值回归
    • 方向:可配置
    • 指标:SMA
    • 止损:无
    • 复杂度:简单
    • 时间框架:日线
using System;
using System.Linq;
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;

public class MeanReversionProStrategy : Strategy
{
	private readonly StrategyParam<int> _fastLength;
	private readonly StrategyParam<int> _slowLength;
	private readonly StrategyParam<DataType> _candleType;

	private SimpleMovingAverage _fastSma;
	private SimpleMovingAverage _slowSma;

	public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
	public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public MeanReversionProStrategy()
	{
		_fastLength = Param(nameof(FastLength), 5);
		_slowLength = Param(nameof(SlowLength), 50);
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
	}

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

		_fastSma = new SimpleMovingAverage { Length = FastLength };
		_slowSma = new SimpleMovingAverage { Length = SlowLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_fastSma, _slowSma, ProcessCandle)
			.Start();
	}

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

		if (!_fastSma.IsFormed || !_slowSma.IsFormed)
			return;

		var range = candle.HighPrice - candle.LowPrice;
		var longThreshold = candle.LowPrice + 0.2m * range;
		var shortThreshold = candle.HighPrice - 0.2m * range;

		var longSignal = candle.ClosePrice < fast &&
			candle.ClosePrice < longThreshold &&
			candle.ClosePrice > slow;

		var shortSignal = candle.ClosePrice > fast &&
			candle.ClosePrice > shortThreshold &&
			candle.ClosePrice < slow;

		var exitLong = candle.ClosePrice > fast && Position > 0;
		var exitShort = candle.ClosePrice < fast && Position < 0;

		if (longSignal && Position <= 0)
			BuyMarket();
		else if (shortSignal && Position >= 0)
			SellMarket();
		else if (exitLong)
			SellMarket();
		else if (exitShort)
			BuyMarket();
	}
}