在 GitHub 上查看

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;
	}
}