在 GitHub 上查看

Contrarian Trade MA Weekly 策略

本策略来源于 MQL 专家顾问 "Contrarian_trade_MA",在 StockSharp 平台上以周线数据运行。系统结合周线极值和简单移动平均,在每个新交易周开始时逆势入场。

交易逻辑

  • 数据来源:通过 CandleType 参数订阅周线(默认 7 天时间框架)。
  • 极值监控HighestLowest 指标跟踪最近 CalcPeriod 个已完成周线的最高价与最低价,不包含当前正在评估的K线。
  • 移动平均过滤:长度为 MaPeriod 的简单移动平均,用于确认方向偏差。
  • 入场条件
    • 做多:上一周的收盘价高于历史最高值 (highest < previousClose),或移动平均高于当前周开盘价。
    • 做空:上一周的收盘价低于历史最低值 (lowest > previousClose),或移动平均低于当前周开盘价。
    • 策略同一时间只允许一笔仓位,在仓位关闭前忽略相反信号。
  • 离场条件
    • 仓位持有七天(604 800 秒)后无条件平仓。
    • 每根完成的周线都会检查止损,距离按 StopLossPoints * PriceStep 计算;若品种未提供 PriceStep,则使用 1 作为缺省值。

参数

名称 默认值 说明
CalcPeriod 4 计算历史最高/最低时参考的已完成周线数量。
MaPeriod 7 周线收盘价的简单移动平均周期。
StopLossPoints 300 止损距离,单位为价格最小变动。设为 0 可关闭止损。
Volume 0.5 BuyMarket/SellMarket 下单时使用的手数。
CandleType 7 天 执行全部逻辑所使用的K线周期。

其他说明

  • 策略会自动从 Security.PriceStep 读取最小价格步长,请在合约资料中填写该信息以确保止损距离正确。
  • 已启用 StartProtection(),用于监控策略之外的持仓变化。
  • 由于逻辑基于已完成的周线,在回测中默认按信号周线的收盘价模拟成交。
using System;
using System.Collections.Generic;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Contrarian MA strategy - mean reversion around SMA.
/// Buys when price crosses below SMA (contrarian dip buy).
/// Sells when price crosses above SMA (contrarian top sell).
/// Uses Highest/Lowest as extreme confirmation.
/// </summary>
public class ContrarianTradeMaWeeklyStrategy : Strategy
{
	private readonly StrategyParam<int> _maPeriod;
	private readonly StrategyParam<int> _channelPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevClose;
	private decimal _prevSma;
	private bool _hasPrev;

	public int MaPeriod { get => _maPeriod.Value; set => _maPeriod.Value = value; }
	public int ChannelPeriod { get => _channelPeriod.Value; set => _channelPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ContrarianTradeMaWeeklyStrategy()
	{
		_maPeriod = Param(nameof(MaPeriod), 14)
			.SetDisplay("SMA Period", "SMA period", "Indicators");

		_channelPeriod = Param(nameof(ChannelPeriod), 10)
			.SetDisplay("Channel Period", "Highest/Lowest lookback", "Indicators");

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

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities() => [(Security, CandleType)];
	protected override void OnReseted() { base.OnReseted(); _prevClose = 0m; _prevSma = 0m; _hasPrev = false; }

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

		_hasPrev = false;

		var sma = new SimpleMovingAverage { Length = MaPeriod };
		var highest = new Highest { Length = ChannelPeriod };
		var lowest = new Lowest { Length = ChannelPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(sma, highest, lowest, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal sma, decimal highest, decimal lowest)
	{
		if (candle.State != CandleStates.Finished)
			return;

		var close = candle.ClosePrice;

		if (!_hasPrev)
		{
			_prevClose = close;
			_prevSma = sma;
			_hasPrev = true;
			return;
		}

		var mid = (highest + lowest) / 2;

		// Contrarian buy: price crosses below SMA and is near the low
		if (_prevClose >= _prevSma && close < sma && close < mid && Position <= 0)
		{
			if (Position < 0)
				BuyMarket();
			BuyMarket();
		}
		// Contrarian sell: price crosses above SMA and is near the high
		else if (_prevClose <= _prevSma && close > sma && close > mid && Position >= 0)
		{
			if (Position > 0)
				SellMarket();
			SellMarket();
		}

		_prevClose = close;
		_prevSma = sma;
	}
}