GitHub で見る

Demarker Martingale 戦略 (StockSharp)

概要

Demarker Martingale 戦略は、StockSharpの高レベルAPIを使用してMetaTraderのエキスパートアドバイザー「Demarker Martingale」を再現します。このシステムは中期的なDeMarkerオシレーターシグナルと上位タイムフレームのMACDトレンドフィルターを組み合わせます。エントリーはマーティンゲールスタイルのポジションサイジング、固定のストップロスとテイクプロフィットレベル、ブレークイーブン保護、および元のエキスパートのマネーマネジメントツールキットを模倣したトレーリングストップが続きます。

コアトレードロジック

  1. データフィード – 戦略はシグナル生成のためにユーザー定義のトレードタイムフレーム(デフォルト15分足)と、MACDフィルターを計算するための上位タイムフレームシリーズ(デフォルト月足)を購読します。
  2. DeMarkerトリガー – DeMarkerの値が中立のDemarkerThreshold(デフォルト0.5)を超え、最近の価格行動が強気のオーバーラップを形成する(Low[2] < High[1])と、ロングセットアップが検討されます。逆に、DeMarkerが閾値以下の弱気のオーバーラップはショートを準備します。
  3. MACD確認 – 上位タイムフレームのMACDは方向と一致する必要があります。強気シグナルはMACDメインラインがシグナルラインより上にあることを必要とし、弱気シグナルは逆の関係を期待します。これはMQLエキスパートの月次MACDフィルターを再現します。
  4. 注文実行 – 有効なシグナルは現在のマーティンゲール調整済みボリュームでマーケット注文を配置します。一度に1つの方向ポジションのみが維持されます。
  5. ポジション監視 – ポジションが開いている間、戦略はストップロス、テイクプロフィット、ブレークイーブン、またはトレーリングストップのトリガーを検出するために完了した各ローソク足を評価します。違反イベントはマーケット注文でポジション全体を閉じます。

マネーマネジメント

  • 初期サイジング – 注文はVolumeStepに合わせたInitialVolumeで開始し、VolumeMin/VolumeMaxに制限されます。
  • マーティンゲールのエスカレーション – 負けトレードの後、次のボリュームはMartingaleMultiplierで乗算(DoubleLotSize = true)されるか、LotIncrementだけ増加します。利益トレードはラダーをベースボリュームにリセットします。エスカレーションの深さは、無制限の露出を防ぐためにMaxMartingaleStepsで制限されます。
  • ストップロスとテイクプロフィット – 距離はMetaTraderスタイルのピップスで表されます。ピップサイズは3/5桁のForeex相場に自動的に適応し、元のticksizeロジックに合わせます。
  • ブレークイーブン – 未実現利益がBreakEvenTriggerPipsに達すると、ストップロスはエントリーにBreakEvenOffsetPipsを加えた(ロング)またはマイナスのオフセット(ショート)にシフトされます。
  • トレーリングストップTrailingStopPipsを超えた利益は、各ローソク足で締まっていく内部トレーリング閾値を動かし、EAのTrailingStop動作を再現します。

パラメーター

名前 説明
CandleType DeMarkerシグナルに使用するトレードタイムフレーム。
MacdCandleType MACDトレンドフィルターを計算するために使用する上位タイムフレーム。
DemarkerPeriod DeMarkerのルックバック期間。
DemarkerThreshold 強気と弱気セットアップの間の中立境界。
MacdFast / MacdSlow / MacdSignal MACDのEMA長。
InitialVolume マーティンゲール調整前のベース注文サイズ。
MartingaleMultiplier DoubleLotSizeが有効な場合の乗数。
LotIncrement 倍増が無効な場合の加算増分。
DoubleLotSize 乗算と加算のマーティンゲールを切り替える。
MaxMartingaleSteps 連続エスカレーションの最大数。
StopLossPips ピップスでのストップロス距離。
TakeProfitPips ピップスでのテイクプロフィット距離。
TrailingStopPips ピップスでのトレーリングストップ距離。
UseBreakEven ブレークイーブンロジックを有効または無効にする。
BreakEvenTriggerPips ブレークイーブンに切り替える前の利益閾値(ピップス)。
BreakEvenOffsetPips ブレークイーブンストップに適用するバッファ。

変換ノート

  • ピップ変換はMQL EAを反映します(ticksize == 0.00001または0.001は10倍のピップスケールを意味します)。これにより3/5桁の相場で一貫したリスク距離が保たれます。
  • MACDトレンドフィルターは元のEMA長のMovingAverageConvergenceDivergenceSignalを使用し、月次チャートロジックをエミュレートするために別のローソク足シリーズを処理します。
  • マーティンゲールの帳簿は加重平均エントリー価格と実現PnLを追跡し、次のトレードがエスカレートするかリセットするかを決定します。
  • すべての保護アクション(ストップロス、テイクプロフィット、ブレークイーブン、トレーリング)はStartProtectionガード下での直接注文変更を高レベルAPIが推奨しないため、マーケット出口で実行されます。

使用のヒント

  • 割り当てられた証券がピップ計算とボリューム丸めを取引所制約に合わせるためにPriceStepVolumeStepVolumeMinVolumeMaxを公開していることを確認してください。
  • より速い市場のためにトレンドフィルターを微調整するためにMacdCandleType(例:週足)を試してください。
  • 最適化する際は、ドローダウンを抑制するためにDemarkerThresholdTrailingStopPips、およびマーティンゲールパラメーターを共同調整してください。
  • マーティンゲールシーケンスは損失後に露出を本質的に増加させるため、ライブ展開時は戦略をポートフォリオレベルのリスク管理またはトレードセッションフィルターと組み合わせてください。
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 DemarkerMartingaleStrategy : 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 DemarkerMartingaleStrategy()
	{
		_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;
	}
}