GitHub で見る

Pendulum戦略

2つの価格しきい値の間で振動するグリッドベースのマーチンゲールシステムです。戦略はグリッドの上限に価格が到達するとロングポジションを開き、下限に価格が移動すると増加したボリュームでショートポジションに転換します。元のPendulumエキスパートアドバイザーに従って、目標を拡大し保護距離を縮小しながら(設定可能な最大レイヤー数まで)方向を交互に切り替え続けます。利益確定後、エンジンはグリッドをリセットし、振り子運動を継続するために同じレベルで新たなエントリーをスケジュールします。

詳細

  • エントリーロジック
    • 設定されたStepSizeを使ってローソク足の終値にグリッドを整列させます。
    • 上限トリガー到達 → ベースボリュームでロングポジションを開きます。
    • 下限トリガー到達 → ベースボリュームでショートポジションを開きます。
    • アクティブなポジションが反対のトリガーに移動すると、戦略は方向を反転し、絶対ボリュームをMultiplierで乗算し、MQLバージョンと同様にテイクプロフィット/ストップロス距離を更新します。
    • 利益確定後に再エントリーがスケジュールされるため、クローズ取引が処理されると次のローソク足が同じグリッドレベルで直ちに再開できます。
  • エグジットロジック
    • 各レイヤーは専用のテイクプロフィットを定義します: 最初のレイヤーには1ステップ、後続の各レイヤーにはMultiplierステップ。
    • 保護ストップはMQLロジックを反映します: 最初のレイヤーはワイドストップ(StepSize * Multiplier)を使用し、後続レイヤーは新しい方向に対する1ステップストップを使用します。
    • 最大レイヤー数に達すると、戦略はリセット前にテイクプロフィットまたはストップロスを待ちます。
  • ポジション管理
    • ネッティングを使用します: StockSharpポートはヘッジされたロングとショートを保持する代わりに、集合ポジションをクローズして反転させます。これにより元のエキスパートのエクスポージャーを維持しつつStockSharpポートフォリオとの互換性を保ちます。
    • ボリュームは利用可能な場合、商品のボリュームステップに丸められます。
  • データ
    • 任意のシンボルと時間軸で動作します。デフォルトのサブスクリプションは1分足ローソク足を使用し、グリッドチェックにローソク足の終値を使用します。
  • 組み込み保護
    • StartProtection()は切断後や手動介入後に残った予期しないポジションを保護するために有効化されています。

パラメーター

パラメーター デフォルト 説明
StepSize 0.001 グリッドレベル間の距離。グリッドは常にこの値の倍数にスナップします。
Multiplier 2 方向が新しいレイヤーに反転したときにトレードボリュームと拡張目標の両方を乗算します。1より大きい必要があります。
MaxLayers 3 戦略が新しい反転の追加を停止するまでのマーチンゲールレイヤーの最大数。
BaseVolume 1 最初のレイヤーに使用するベーストレードサイズ。後のレイヤーはMultiplierでスケールします。
CandleType 1 Minute TimeFrame サブスクリプションに使用するローソク足タイプ。データソースがサポートする他の時間軸に変更できます。

メモ

  • 戦略はヘッジポジションに依存せずにPendulum.mq5の動作を再現します。StockSharpはエクスポージャーを統合するため、MQLグリッドをエミュレートするためにネットポジションが反転されます。
  • テイクプロフィット完了後、クローズ取引が処理されると次のローソク足が同じ価格レベルで即座に再開できるように、延期注文が発動されます。
  • グリッドレベルの過度な丸めを避けるため、設定されたステップサイズを商品の価格ステップと合わせてください。
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;

/// <summary>
/// Pendulum strategy using SMA crossover with mean reversion.
/// Buys when fast SMA crosses above slow SMA, sells on reverse.
/// </summary>
public class PendulumStrategy : 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 PendulumStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 20).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
		_slowPeriod = Param(nameof(SlowPeriod), 80).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 = 80; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 80; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}
		else if (Position < 0 && _entryPrice > 0)
		{
			if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 80; _prevFast = fastValue; _prevSlow = slowValue; return; }
			if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 80; _prevFast = fastValue; _prevSlow = slowValue; return; }
		}

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

		_prevFast = fastValue; _prevSlow = slowValue;
	}
}