GitHub で見る

EMA クロストレーリング戦略

概要

この戦略は、MQL/8606/EMA_CROSS_2.mq4 にある MetaTrader 4 エキスパート アドバイザーの StockSharp の変換です。これは、遅い指数移動平均と速い指数移動平均の間の関係を追跡し、クロスオーバーが発生したときに単一の市場ポジションを開くという元のアイデアを保持しています。保護的出口(利益確定、ストップロス、トレーリングストップ)は高レベルの StartProtection ヘルパーを通じて処理されるため、動作は StockSharp のベストプラクティスを使用しながら MetaTrader の実装を反映しています。

取引ロジック

  • 構成可能な CandleType (デフォルトでは 15 分足) を使用してローソク足を構築し、2 つの EMA インジケーターをフィードします。遅い EMA は SlowEmaLength を使用し、速い EMA は FastEmaLength を使用します。
  • 高速な EMA に対して低速な EMA の最新の方向を維持します。両方のインジケーターが形成された後、最初に完了したローソク足は、元のアドバイザーの first_time ガードと同様に、この方向を初期化するためにのみ使用されます。
  • 遅い EMA が速い EMA を上回って (新しい方向は 1 になります)、戦略がフラットになったら、成行買い注文を送信します。遅い EMA が速い EMA を下回って (新しい方向は 2 になります)、戦略がフラットになったら、成行売り注文を送信します。これにより、MQL 関数 Crossed(LEma, SEma) の正確な上下マッピングが再現されます。
  • 一度にアクティブにできるポジションは 1 つだけです。取引が開いている間 (またはエントリー注文がまだ保留中)、追加のクロスオーバーは無視されます。

貿易とリスク管理

  • StartProtection は、商品 PriceStep から計算された価格単位でテイクプロフィット、ストップロス、トレーリングストップの距離を設定します。トレーリングストップはオプションです。無効にするには、TrailingStopPips をゼロに設定します。
  • 注文は、BuyMarket/SellMarket で発注され、元のアドバイザーからの OrderSend およびトレーリング ロジックとまったく同様に、保護レベルがトリガーされると市場によって閉じられます。
  • 基本ロットサイズは OrderVolume によって制御されます。各エントリの前に、拒否を避けるために、楽器の音量ステップ、最小値と最大値に合わせて調整されます。

パラメーター

パラメータ 説明
TakeProfitPips 保護的なテイクプロフィットに使用されるピップ単位の距離 (価格ステップ)。デフォルト: 20。
StopLossPips 保護ストップロスに使用されるピップ単位の距離。デフォルト: 30。
TrailingStopPips ピップ単位のトレーリング距離。末尾を無効にするには、0 に設定します。デフォルト: 50。
OrderVolume 調整前の市場エントリーのロットサイズ。デフォルト: 2。
FastEmaLength 終値に適用される高速 EMA の期間。デフォルト: 5。
SlowEmaLength 遅い EMA の期間が終値に適用されます。デフォルト: 60。
CandleType キャンドル構築の時間枠。デフォルト: 15 分。

注意事項

  • この戦略は、クロスオーバーに反応する前に両方の EMA が完全に形成されるまで待機し、同じ安定性を実現しながら、MQL スクリプトから Bars < 100 チェックを削除します。
  • 成行注文のみが使用されるため、個別の OrderModify 呼び出しはありません。組み込みの保護モジュールは、MetaTrader ループが更新された OrderStopLoss と同じ方法でトレーリング ストップの位置を自動的に変更します。
  • Python ポートは (リクエストごとに) 提供されません。 C# 実装のみが含まれます。
using System;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// EMA crossover strategy with trailing stop.
/// Buys when fast EMA crosses above slow EMA, sells on the opposite crossover.
/// </summary>
public class EmaCrossTrailingStrategy : Strategy
{
	private readonly StrategyParam<int> _fastEmaLength;
	private readonly StrategyParam<int> _slowEmaLength;
	private readonly StrategyParam<DataType> _candleType;

	private int _currentDirection;
	private bool _hasInitialDirection;

	public EmaCrossTrailingStrategy()
	{
		_fastEmaLength = Param(nameof(FastEmaLength), 5)
			.SetDisplay("Fast EMA", "Length of the fast exponential moving average.", "Indicator");

		_slowEmaLength = Param(nameof(SlowEmaLength), 60)
			.SetDisplay("Slow EMA", "Length of the slow exponential moving average.", "Indicator");

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
			.SetDisplay("Candle Type", "Time frame used to build candles and EMAs.", "General");
	}

	public int FastEmaLength
	{
		get => _fastEmaLength.Value;
		set => _fastEmaLength.Value = value;
	}

	public int SlowEmaLength
	{
		get => _slowEmaLength.Value;
		set => _slowEmaLength.Value = value;
	}

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_currentDirection = 0;
		_hasInitialDirection = false;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var fastEma = new ExponentialMovingAverage { Length = FastEmaLength };
		var slowEma = new ExponentialMovingAverage { Length = SlowEmaLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastEma, slowEma, 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 fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		// Determine direction: 1 = fast above slow (bullish), -1 = fast below slow (bearish)
		var newDirection = fastValue > slowValue ? 1 : fastValue < slowValue ? -1 : 0;

		if (newDirection == 0)
			return;

		if (!_hasInitialDirection)
		{
			_currentDirection = newDirection;
			_hasInitialDirection = true;
			return;
		}

		if (newDirection == _currentDirection)
			return;

		var prevDirection = _currentDirection;
		_currentDirection = newDirection;

		// Crossover detected
		if (newDirection == 1 && prevDirection == -1)
		{
			// Bullish crossover
			if (Position < 0)
				BuyMarket(); // Close short
			if (Position <= 0)
				BuyMarket(); // Open long
		}
		else if (newDirection == -1 && prevDirection == 1)
		{
			// Bearish crossover
			if (Position > 0)
				SellMarket(); // Close long
			if (Position >= 0)
				SellMarket(); // Open short
		}
	}
}