Breakeven v3 管理器
概述
Breakeven v3 管理器移植自 MetaTrader 5 智能交易系统 Breakeven v3 (barabashkakvn's edition)。
它不会主动开仓,而是持续计算所选交易品种的组合盈亏平衡价,并根据该价格(外加可选偏移)
调整所有多头与空头持仓的止损 / 止盈,让整个仓位组合在盈亏平衡附近被动平仓。
策略逻辑
- 盈亏平衡重建 – 每当成交或新的报价到达时,策略都会重新计算多头与空头持仓的加权平均
开仓价。同时累计
MyTrade里可获得的手续费,力求复刻 MQL 版本的算法。 - 目标价位计算 – 在计算出的盈亏平衡价基础上,加上
Delta (points)参数设定的 MetaTrader 点数偏移。 净持仓为多头时向上偏移,净持仓为空头时向下偏移,对应原始 EA 中的 Delta 设置。 - 保护性委托挂单 –
- 净持仓多头:在目标价位放置覆盖全部多头仓位的 卖出限价单,同时为所有空头仓位设置同价位 的 买入止损单 作为止损。
- 净持仓空头:在目标价位放置覆盖全部空头仓位的 买入限价单,同时为所有多头仓位设置同价位 的 卖出止损单。
- 双边仓位为零时,撤销所有保护性挂单。
- 行情监控与诊断 – 订阅 Level1 行情,利用最新买价 / 卖价计算到目标价的距离以及浮动盈亏估算。
当
Enable Logging为真时,这些信息会记录到策略日志,用于模拟原脚本在图表上显示的提示文本。
参数
- Delta (points) – 施加在盈亏平衡价上的偏移量,以 MetaTrader 点表示(对于五位报价的外汇品种
相当于 0.1 点)。默认值:
100。 - Enable Logging – 是否输出详细的日志信息(盈亏平衡价、目标距离与浮动盈亏)。默认值:
true。
使用说明
- 该策略是仓位管理工具,需配合已有策略或人工开仓运行,本身不会发起市价委托。
- 启动时会读取当前投资组合,为每个方向构建一笔合成仓位,价格来源于 StockSharp 提供的平均价。 为获得最准确的结果,请在产生新成交前保持策略运行。
- StockSharp 暂不提供库存费 / 掉期数据,因此盈亏平衡价只考虑手续费。如果券商会收取隔夜库存费, 需要额外手动处理。
- 脚本假设账户支持锁仓(同时持有多空仓位)。若券商采用净额结算模式,多空持仓最终会收敛到 与 MetaTrader 相同的单一净仓。
- 本次移植仅提供 C# 版本,没有 Python 版本。
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()