GitHub で見る

Hedger Drawdown戦略

MetaTrader 5のエキスパートアドバイザーhedger.mq5(MQL #23511)のStockSharp移植版です。元のシステムは、既存のポジションが指定されたpip数だけドローダウンした場合に、反対方向に保護的なヘッジを開きます。価格がより小さな金額だけ回復すると、ヘッジは損失が出ていても閉じられ、元のトレードが回復できるようになります。この変換はStockSharpの高水準APIを使用して同じ動作を再現し、プラットフォームのネットポジションモデルに合わせて仕組みを適応させています。

トレーディングロジック

  1. 戦略は設定されたタイムフレームの各ローソク足のクローズを監視します。
  2. ヘッジではない各ロングポジションについて、エントリー価格と現在のクローズの距離がDrawdownOpenPips以上かどうかを確認します。アクティブなショートヘッジがない場合、同じボリュームでショートヘッジを開きます。
  3. ヘッジではない各ショートポジションについて、対称的なルールを適用し、損失が開始閾値に達した後にロングヘッジを開きます。
  4. アクティブなヘッジポジションは、その浮動損失がDrawdownClosePipsに達すると閉じられます。これは、部分的な回復後に保護を解除するMetaTraderロジックを反映しています。
  5. 口座がフラットでStartWithLongが有効な場合、アルゴリズムはサイクルを開始するためにシードロングポジションを開きます。

StockSharpはネットポジションを追跡するため、戦略はロングとショートのエントリーの内部台帳(どれがヘッジかを含む)を保持します。各マーケット注文は台帳を更新するため、ブローカーがポジションをまとめても、ヘッジを独立して開閉できます。

パラメーター

パラメーター 説明
DrawdownOpenPips 反対のヘッジ開始をトリガーするpipでのドローダウン。
DrawdownClosePips ヘッジを強制クローズするpipでのドローダウン。
InitialVolume サイクル開始時の初期トレードのボリューム。
StartWithLong 有効にすると、フラット時に初期ロングポジションを開きます。
EnableVerboseLogging デバッグのためにヘッジアクションを戦略ログに書き込みます。
CandleType ドローダウン監視に使用するローソク足シリーズ。

MetaTraderバージョンとの違い

  • エキスパートアドバイザーはヘッジポジションを区別するためにチケットコメント(hedge_buy / hedge_sell)に依存していました。変換ではStockSharpがネッティングを使用するため、このステートはメモリに保存されます。
  • マージンチェックとスリッページ設定は省略されています。注文の配置には高水準ヘルパーBuyMarket / SellMarketを使用します。
  • 戦略はpip閾値とボリュームの最適化範囲を公開しており、StockSharpオプティマイザーで調整できます。

使用上の注意

  1. 戦略を目的のシンボルとポートフォリオに接続します。
  2. pip閾値をインストゥルメントのボラティリティに合わせて調整します。
  3. 変換を検証する際には詳細ログを有効にしてください。ログはpip統計とともに各ヘッジの作成と削除を記録します。
  4. オーバートレードを避けるため、意味のあるローソク足クローズを提供するタイムフレーム(例:M15〜H1)で使用してください。
using System;
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 HedgerDrawdownStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _stopLossPoints;
	private readonly StrategyParam<int> _takeProfitPoints;

	private ExponentialMovingAverage _fast;
	private ExponentialMovingAverage _slow;

	private decimal _prevFast;
	private decimal _prevSlow;
	private decimal _entryPrice;
	private int _cooldown;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
	public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }

	public HedgerDrawdownStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
		_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
		_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
	}

	protected override void OnReseted()
	{
		base.OnReseted();
		_fast = null; _slow = null;
		_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);
		_fast = new ExponentialMovingAverage { Length = FastPeriod };
		_slow = new ExponentialMovingAverage { Length = SlowPeriod };
		var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
		subscription.Bind(_fast, _slow, ProcessCandle);
		subscription.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
		if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }

		var close = candle.ClosePrice;
		var step = Security?.PriceStep ?? 1m;

		if (Position > 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

		if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
		{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
		else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
		{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}