GitHub で見る
LBS 戦略
LBS 戦略 は MetaTrader 5 エキスパートアドバイザー「LBS (barabashkakvn's edition)」の直接変換です。元のシステムは設定可能な取引ウィンドウ中に前のローソク足のブレイクアウトを監視し、両方の極値にストップ注文を配置します。StockSharp ポートは高レベル API(SubscribeCandles、SubscribeLevel1、BuyStop/SellStop)を使用して同じトレード管理ルールを維持します。
取引ロジック
- ストラテジーは選択した時間軸(
CandleType)の完了したローソク足を監視します。
- ローソク足のクローズ時間が有効な取引時間(
Hour1、Hour2、Hour3)のいずれかと一致すると、アルゴリズムはブレイクアウトレベルを計算します:
- バイストップはローソク足の高値と現在のアスクにフリーズバッファを加えた値の大きい方に配置されます。
- セルストップはローソク足の安値と現在のビッドからバッファを差し引いた値の小さい方に配置されます。
- バッファは MetaTrader の
SYMBOL_TRADE_FREEZE_LEVEL フォールバック(スプレッドの3倍、ただし10ピップ未満にはなりません)を再現します。
- ポジションが開かれると、反対の保留注文は即座にキャンセルされます。これは MQL エキスパートの
DeleteAllPendingOrders ルーティンと同様です。
- 初期ストップロス価格は
StopLossPips に従って添付されます。オプションのトレーリングロジック(TrailingStopPips と TrailingStepPips)は、浮動利益が設定された閾値を超えるとストップを移動させます。
- ストラテジーがオンライン状態で、ポジションが開いておらず、有効な Level1 クォートが利用可能な場合のみ注文が送信されます。
資金管理
MoneyMode は元のエキスパートの Lot/Risk スイッチを反映します:
- FixedLot –
VolumeOrRisk パラメーターは絶対的な取引量として解釈されます。
- 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 にフォールバックします。
使用上のヒント
- ストラテジーを楽器に接続し、MetaTrader で使用したのと同じ時間軸を選択します。
- 取引したいセッションに応じて取引時間を設定します(
0 に設定するとそのスロットが無効になります)。
- 自動スケーリングを希望する場合は
RiskPercent モードを選択し、StopLossPips が正であることを確認してください。
- 固定ロット取引の場合は
MoneyMode を FixedLot のままにし、VolumeOrRisk を希望するサイズに設定します。
- ストラテジーを開始します。次の設定された時間に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;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class lbs_strategy(Strategy):
def __init__(self):
super(lbs_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 20) \
.SetDisplay("Fast Period", "Fast EMA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 100) \
.SetDisplay("Slow Period", "Slow EMA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(lbs_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(lbs_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 80
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 80
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return lbs_strategy()