Breakeven V3マネージャー
概要
Breakeven V3マネージャーはMetaTrader 5エキスパートアドバイザーBreakeven v3 (barabashkakvn's edition)の変換版です。
元のスクリプトはトレードを開きません。代わりに選択したシンボルのポートフォリオのブレークイーブンレベルを継続的に計算し、
オープンしているすべてのロングおよびショートポジションの保護注文(ストップロスまたはテイクプロフィット)を移動させて、
オプションのバッファを付けてそのブレークイーブン価格付近で全帳簿がクローズされるようにします。
戦略ロジック
- ブレークイーブンの再構築 – トレードが約定するか新しい気配値が届くたびに、戦略はロングとショートのエクスポージャーの
加重平均建値を別々に再構築します。MQL実装を反映するため、StockSharpが
MyTradeオブジェクトで報告するポジションごとの 手数料を含めます。 - 目標価格の計算 – ブレークイーブン価格は
Delta (points)MetaTraderポイントずらされます。ネットエクスポージャーが ロングの場合はずれ幅が加算され、ショートの場合は減算され、元の"Delta"パラメーターを再現します。 - 保護注文の配置 –
- ネットエクスポージャーがロングの場合、ロング総ボリュームのテイクプロフィット売り指値と、同価格でショート 集計ボリュームのストップロス買いストップが配置されます。
- ネットエクスポージャーがショートの場合、ショート全ボリュームのテイクプロフィット買い指値と、ロングヘッジの ストップロス売りストップが配置されます。
- 両サイドがフラットの場合、すべての保護注文はキャンセルされます。
- 気配値モニタリングと診断 – 戦略はLevel1アップデートを購読します。最新のビッド/アスクは目標までの距離統計と
推定フローティング利益の計算に使用されます。
Enable Loggingがtrueの場合、これらの値は戦略ログに書き込まれ、 MQLバージョンのチャート上コメントをエミュレートします。
パラメーター
- Delta (points) – 計算されたブレークイーブン価格に適用されるオフセット。値はMetaTraderポイントで表され、
5桁FXシンボルでは1pipの10分の1です。デフォルト:
100。 - Enable Logging – 現在のブレークイーブンレベル、目標までの距離、フローティングPnLを記述した詳細なログ出力を切り替えます。
デフォルト:
true。
使用上の注意
- この戦略はトレードマネージャーです。既存の戦略や手動ポジションの上で起動する必要があります。 自身では成行注文を開きません。
- 起動時にコードはポートフォリオを検査し、StockSharpが報告する平均価格を使用してポジションの各サイドに 単一の合成ロットを再構築します。最高の精度のため、新しいトレードが開かれるたびに戦略を実行し続けてください。
- スワップチャージはStockSharpから利用できないため、ブレークイーブン価格の再構築時には手数料情報のみが含まれます。 ブローカーが夜間スワップを適用する場合は手動で処理する必要があります。
- スクリプトはアカウントがヘッジ(ロングとショートポジションの同時保有)を許可することを前提としています。 ブローカーがポジションをネットする場合、ロングとショートの集計はMetaTraderと同様に単一のネットエクスポージャーに 縮小されます。
- このポートにはPythonバージョンはありません。C#実装のみが提供されます。
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>
/// Break-even management strategy that enters on EMA crossover and moves
/// the exit level to break-even once price moves a configurable distance in favor.
/// </summary>
public class BreakevenV3Strategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _activationPoints;
private readonly StrategyParam<int> _deltaPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private decimal _breakEvenPrice;
private bool _breakEvenActivated;
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 ActivationPoints { get => _activationPoints.Value; set => _activationPoints.Value = value; }
public int DeltaPoints { get => _deltaPoints.Value; set => _deltaPoints.Value = value; }
public BreakevenV3Strategy()
{
_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");
_activationPoints = Param(nameof(ActivationPoints), 200).SetNotNegative().SetDisplay("Activation", "Distance price must move before break-even activates", "Risk");
_deltaPoints = Param(nameof(DeltaPoints), 100).SetNotNegative().SetDisplay("Delta", "Offset from entry for break-even stop", "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; _breakEvenPrice = 0;
_breakEvenActivated = false; _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;
// Manage break-even for open position
if (Position != 0 && _entryPrice > 0)
{
var activationDistance = ActivationPoints * step;
var deltaOffset = DeltaPoints * step;
if (Position > 0)
{
if (!_breakEvenActivated && activationDistance > 0 && close >= _entryPrice + activationDistance)
{
_breakEvenActivated = true;
_breakEvenPrice = _entryPrice + deltaOffset;
}
if (_breakEvenActivated && close <= _breakEvenPrice)
{
SellMarket();
_entryPrice = 0; _breakEvenPrice = 0; _breakEvenActivated = false;
_cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue;
return;
}
}
else if (Position < 0)
{
if (!_breakEvenActivated && activationDistance > 0 && close <= _entryPrice - activationDistance)
{
_breakEvenActivated = true;
_breakEvenPrice = _entryPrice - deltaOffset;
}
if (_breakEvenActivated && close >= _breakEvenPrice)
{
BuyMarket();
_entryPrice = 0; _breakEvenPrice = 0; _breakEvenActivated = false;
_cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue;
return;
}
}
}
// Entry: EMA crossover
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_entryPrice = close; _breakEvenActivated = false; _cooldown = 100;
}
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
_entryPrice = close; _breakEvenActivated = false; _cooldown = 100;
}
_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 breakeven_v3_strategy(Strategy):
def __init__(self):
super(breakeven_v3_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast EMA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow EMA period", "Indicator")
self._activation_points = self.Param("ActivationPoints", 200) \
.SetDisplay("Activation", "Distance price must move before break-even activates", "Risk")
self._delta_points = self.Param("DeltaPoints", 100) \
.SetDisplay("Delta", "Offset from entry for break-even stop", "Risk")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._break_even_price = 0.0
self._break_even_activated = False
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 activation_points(self):
return self._activation_points.Value
@property
def delta_points(self):
return self._delta_points.Value
def OnReseted(self):
super(breakeven_v3_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._break_even_price = 0.0
self._break_even_activated = False
self._cooldown = 0
def OnStarted2(self, time):
super(breakeven_v3_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self.fast_period
slow = ExponentialMovingAverage()
slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(fast, slow, self.OnProcess).Start()
def OnProcess(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if fast_val == 0 or slow_val == 0:
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.PriceStep is not None else 1.0
if self.Position != 0 and self._entry_price > 0:
activation_distance = float(self.activation_points) * step
delta_offset = float(self.delta_points) * step
if self.Position > 0:
if not self._break_even_activated and activation_distance > 0 and close >= self._entry_price + activation_distance:
self._break_even_activated = True
self._break_even_price = self._entry_price + delta_offset
if self._break_even_activated and close <= self._break_even_price:
self.SellMarket()
self._entry_price = 0.0
self._break_even_price = 0.0
self._break_even_activated = False
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0:
if not self._break_even_activated and activation_distance > 0 and close <= self._entry_price - activation_distance:
self._break_even_activated = True
self._break_even_price = self._entry_price - delta_offset
if self._break_even_activated and close >= self._break_even_price:
self.BuyMarket()
self._entry_price = 0.0
self._break_even_price = 0.0
self._break_even_activated = False
self._cooldown = 100
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._break_even_activated = False
self._cooldown = 100
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._break_even_activated = False
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return breakeven_v3_strategy()