GitHub で見る

逆張りトレードMAウィークリー戦略

元の MQL「Contrarian_trade_MA」エキスパートアドバイザーから変換された毎週の逆張りシステム。この戦略は、毎週のローソク足の極端な値と単純な移動平均を分析して、新しい週の初めに伸びた動きを弱めます。

取引ロジック

  • データ ソース: CandleType パラメーターによって提供される週次ローソク足 (デフォルトは 7 日間の時間枠)。
  • 歴史的極値: Highest および Lowest インジケーターは、現在評価されているローソク足を除き、過去の CalcPeriod 完了週の高値と安値を追跡します。
  • 移動平均フィルター: 毎週の終値に適用される長さ MaPeriod の単純な移動平均は、方向性フィルターとして機能します。
  • エントリールール:
    • 購入は、前週の終値が追跡高値 (highest < previousClose) より高い場合、または移動平均が現在の週の始値を上回っている場合に行われます。
    • 売りは、前週の終値が追跡安値 (lowest > previousClose) より低い場合、または移動平均が現在の週次始値を下回っている場合に行われます。
    • いつでもオープンできるポジションは 1 つだけです。反対のシグナルは、既存の取引が終了するまで無視されます。
  • 終了ルール:
    • ポジションは、方向に関係なく 7 日間 (604,800 秒) 保持された後にクローズされます。
    • プロテクティブストップは、完了した毎週のローソク足ごとに評価されます。停止距離は StopLossPoints * PriceStep から計算されます (機器のメタデータでステップが指定されていない場合は、1 に戻ります)。

パラメーター

名前 デフォルト 説明
CalcPeriod 4 最高値と最低値を計算するために使用される完了した週数。
MaPeriod 7 毎週の終値に適用される単純移動平均の期間。
StopLossPoints 300 価格ステップで測定されたエントリー価格からストップロスまでの距離。停止を無効にするには、0 に設定します。
Volume 0.5 BuyMarket/SellMarket によって送信されたロットの注文サイズ。
CandleType 7 days すべての計算を実行するローソク足の時間枠。

追加メモ

  • この戦略は、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;
	}
}