GitHub で見る

LBS 戦略

LBS 戦略 は MetaTrader 5 エキスパートアドバイザー「LBS (barabashkakvn's edition)」の直接変換です。元のシステムは設定可能な取引ウィンドウ中に前のローソク足のブレイクアウトを監視し、両方の極値にストップ注文を配置します。StockSharp ポートは高レベル API(SubscribeCandlesSubscribeLevel1BuyStop/SellStop)を使用して同じトレード管理ルールを維持します。

取引ロジック

  1. ストラテジーは選択した時間軸(CandleType)の完了したローソク足を監視します。
  2. ローソク足のクローズ時間が有効な取引時間(Hour1Hour2Hour3)のいずれかと一致すると、アルゴリズムはブレイクアウトレベルを計算します:
    • バイストップはローソク足の高値と現在のアスクにフリーズバッファを加えた値の大きい方に配置されます。
    • セルストップはローソク足の安値と現在のビッドからバッファを差し引いた値の小さい方に配置されます。
    • バッファは MetaTrader の SYMBOL_TRADE_FREEZE_LEVEL フォールバック(スプレッドの3倍、ただし10ピップ未満にはなりません)を再現します。
  3. ポジションが開かれると、反対の保留注文は即座にキャンセルされます。これは MQL エキスパートの DeleteAllPendingOrders ルーティンと同様です。
  4. 初期ストップロス価格は StopLossPips に従って添付されます。オプションのトレーリングロジック(TrailingStopPipsTrailingStepPips)は、浮動利益が設定された閾値を超えるとストップを移動させます。
  5. ストラテジーがオンライン状態で、ポジションが開いておらず、有効な Level1 クォートが利用可能な場合のみ注文が送信されます。

資金管理

MoneyMode は元のエキスパートの Lot/Risk スイッチを反映します:

  • FixedLotVolumeOrRisk パラメーターは絶対的な取引量として解釈されます。
  • RiskPercent – ストラテジーは VolumeOrRisk をポートフォリオ価値の割合に変換します。リスク額をエントリー価格と保護ストップ間の距離(価格ステップ単位)で割って注文量を算出します。このモードを使用する場合、ストップロスを有効にする必要があります。そうでなければ注文はスキップされます。

すべてのボリュームはブローカーの拒否を避けるために、楽器の最小、最大、ステップ制約に正規化されます。

パラメーター

名前 デフォルト 説明
StopLossPips 50 ピップ単位の固定ストップまでの距離。ゼロは初期ストップとトレーリングモジュールの両方を無効にします。
TrailingStopPips 5 ピップ単位のトレーリングストップ距離。ゼロはトレーリングを無効にします。
TrailingStepPips 15 トレーリングストップが移動する前に必要な追加利益(ピップ単位)。トレーリングが有効な場合は正の値が必要です。
MoneyMode FixedLot 固定ボリュームとリスクパーセントのサイジングを選択します。
VolumeOrRisk 1.0 FixedLot モードでのロットサイズ、または RiskPercent モードでのリスク割合。
Hour1 10 最初の取引時間。無効にするには 0 に設定します。
Hour2 11 2番目の取引時間。無効にするには 0 に設定します。
Hour3 12 3番目の取引時間。無効にするには 0 に設定します。
CandleType 1時間の時間軸 ブレイクアウト検出に使用されるローソク足シリーズ。MetaTrader のチャート時間軸を反映するように調整します。

注意事項

  • 時間の比較にはローソク足のクローズ時間が使用されます。これは MetaTrader の TimeCurrent() が次のバーの始まりと等しくなる瞬間に対応します。
  • フリーズ/ストップレベルの近似により、ストップ注文が現在の bid/ask から10ピップ未満にならないことが保証され、最も一般的な MetaTrader エラーを防ぎます。
  • トレーリングストップはすべての Level1 ティックで更新されるため、元のエキスパートのティック駆動 OnTick ハンドラーに近い動作が確保されます。
  • リスクベースのサイジングは Portfolio.CurrentValue が利用可能な場合に使用し、そうでない場合は Portfolio.BeginValue にフォールバックします。

使用上のヒント

  1. ストラテジーを楽器に接続し、MetaTrader で使用したのと同じ時間軸を選択します。
  2. 取引したいセッションに応じて取引時間を設定します(0 に設定するとそのスロットが無効になります)。
  3. 自動スケーリングを希望する場合は RiskPercent モードを選択し、StopLossPips が正であることを確認してください。
  4. 固定ロット取引の場合は MoneyModeFixedLot のままにし、VolumeOrRisk を希望するサイズに設定します。
  5. ストラテジーを開始します。次の設定された時間に2つの保留注文を配置し、保護ストップを自動的に維持します。
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>
/// London Breakout Strategy using EMA crossover as breakout direction filter.
/// Buys when fast EMA crosses above slow EMA, sells on reverse.
/// </summary>
public class LbsStrategy : 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;

	/// <summary>
	/// Fast EMA period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Stop-loss distance in price steps.
	/// </summary>
	public int StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take-profit distance in price steps.
	/// </summary>
	public int TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="LbsStrategy"/> class.
	/// </summary>
	public LbsStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast EMA period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 100)
			.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");
	}

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

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

		_fast = null;
		_slow = null;
		_prevFast = 0;
		_prevSlow = 0;
		_entryPrice = 0;
		_cooldown = 0;
	}

	/// <inheritdoc />
	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;

		// Check SL/TP
		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;
			}
		}

		// EMA crossover
		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;
	}
}