在 GitHub 上查看

Brandy v1.2 策略(C# 版本)

概览

Brandy v1.2 策略 是对 MetaTrader 4 专家顾问 "Brandy_v1_2.mq4" 的完整移植,基于 StockSharp 高级策略 API 实现。系统同时计算两条基于收盘价的简单移动平均线(SMA),并对它们施加与原始脚本相同的位移。只有当长周期与短周期 SMA 的斜率同时指向同一方向时才允许开仓;持仓阶段则通过趋势反转、固定止损以及可选的跟踪止损进行管理。

原始 EA 只在每根新 K 线生成时执行一次逻辑。本移植版本同样仅在 CandleStates.Finished 状态下处理蜡烛数据,确保所有信号都基于已收盘的价格信息。

交易逻辑

  1. 指标准备
    • 构建两条简单移动平均线:LongPeriod 代表长周期均线,ShortPeriod 代表短周期均线。
    • 每条均线都会读取两个数值:上一根 K 线的值(位移 1)以及距今 LongShift/ShortShift 根 K 线的值,以完全复刻 iMA(..., shift) 的计算方式。
  2. 开仓条件
    • 做多:当上一根 K 线的长短两条 SMA 均高于各自的位移值(均线斜率向上)且当前没有持仓时开多。
    • 做空:当上一根 K 线的长短两条 SMA 均低于各自的位移值(均线斜率向下)且当前没有持仓时开空。
    • 任何时刻最多只保留一笔头寸,对应原脚本中的 k == 0 限制。
  3. 平仓条件
    • 斜率反转:持有多单时若长周期 SMA 转为向下(longPrev < longShifted),立即平仓;持有空单时若长周期 SMA 转为向上(longPrev > longShifted),立即回补。
    • 固定止损:开仓后记录入场价,并按照 StopLossPoints × PriceStep 计算绝对止损价位;每根完成的 K 线都会检查该止损是否被突破。
    • 跟踪止损:当 TrailingStopPoints ≥ 100 时启用。只有在浮动盈利超过跟踪距离且当前止损离价格的距离仍大于该值时,才会将止损上移/下移到 currentPrice ± trailingDistance,完全模拟原 EA 的 OrderModify 行为。

参数说明

参数 默认值 说明
LongPeriod 70 长周期 SMA 的长度(对应 MQL 中的 p1)。必须为正数。
LongShift 5 长周期 SMA 的位移量(对应 s1)。允许为 0。
ShortPeriod 20 短周期 SMA 的长度(对应 p2)。必须为正数。
ShortShift 5 短周期 SMA 的位移量(对应 s2)。允许为 0。
StopLossPoints 50 固定止损距离(以最小价格跳动为单位,对应 sl)。设为 0 可关闭硬止损。
TrailingStopPoints 150 跟踪止损距离(以最小价格跳动为单位,对应 ts)。只有当值 ≥ 100 时才会启动跟踪。
Volume 0.1 下单手数(对应 lots)。
CandleType 15 分钟 使用的蜡烛类型,可在 UI 中修改。

价格步长依赖

止损与跟踪止损都以“点”为单位。策略会读取 Security.PriceStep 将其转换为绝对价格距离;若行情源未提供 PriceStep,则回退到 0.0001 作为估算值。实际交易前请确认交易品种的价格步长配置正确。

风险管理

  • 硬止损:每根完成的蜡烛都会检查是否触及止损价位,一旦突破立即通过 SellMarketBuyMarket 平掉全部仓位。
  • 跟踪止损:复制原 EA 的触发条件,仅在收益充足且现有止损仍然过远时才向价格方向移动。
  • 单一仓位:策略不会加仓或对冲,始终保持“多 / 空 / 空仓”三种状态之一。

实现细节

  • OnReseted() 会清空所有内部状态(入场价、止损、SMA 历史值),方便重复回测或重启。
  • 为了模拟 shift 功能,使用短队列维护 SMA 历史值,而不是调用被禁止的 GetValue() 方法。
  • 代码中的注释全部采用英文,符合仓库规范。
  • 按需求仅提供 C# 版本(CS/BrandyV12Strategy.cs),未创建 Python 目录或脚本。

使用步骤

  1. 在 StockSharp 终端中加载策略,选择目标品种,并确保蜡烛数据与 CandleType 参数一致。
  2. 根据需求调整参数,默认值完全复刻 MT4 原始设置。
  3. 启动策略后,它会自动订阅蜡烛数据、绘制两条 SMA,并根据上述规则管理仓位。

免责声明: 本策略仅用于教育与测试。正式上实盘前请先在历史数据和模拟账户中充分验证。

using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Trend-following strategy using displaced simple moving averages.
/// </summary>
public class BrandyV12Strategy : Strategy
{
	private readonly StrategyParam<int> _longPeriod;
	private readonly StrategyParam<int> _longShift;
	private readonly StrategyParam<int> _shortPeriod;
	private readonly StrategyParam<int> _shortShift;
	private readonly StrategyParam<decimal> _stopLossPoints;
	private readonly StrategyParam<decimal> _trailingStopPoints;
	private readonly StrategyParam<DataType> _candleType;

	private SimpleMovingAverage _longSma;
	private SimpleMovingAverage _shortSma;
	private readonly List<decimal> _longHistory = new();
	private readonly List<decimal> _shortHistory = new();
	private decimal? _entryPrice;
	private decimal? _stopPrice;

	/// <summary>
	/// Initializes a new instance of <see cref="BrandyV12Strategy"/>.
	/// </summary>
	public BrandyV12Strategy()
	{
		_longPeriod = Param(nameof(LongPeriod), 70)
			.SetGreaterThanZero()
			.SetDisplay("Long SMA Period", "Period for the longer moving average.", "Indicators")
			;

		_longShift = Param(nameof(LongShift), 5)
			.SetNotNegative()
			.SetDisplay("Long SMA Shift", "Backward shift applied to the longer SMA.", "Indicators")
			;

		_shortPeriod = Param(nameof(ShortPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("Short SMA Period", "Period for the shorter moving average.", "Indicators")
			;

		_shortShift = Param(nameof(ShortShift), 5)
			.SetNotNegative()
			.SetDisplay("Short SMA Shift", "Backward shift applied to the shorter SMA.", "Indicators")
			;

		_stopLossPoints = Param(nameof(StopLossPoints), 50m)
			.SetNotNegative()
			.SetDisplay("Stop Loss (points)", "Initial stop-loss distance expressed in price steps.", "Risk")
			;

		_trailingStopPoints = Param(nameof(TrailingStopPoints), 150m)
			.SetNotNegative()
			.SetDisplay("Trailing Stop (points)", "Trailing stop distance in price steps. Activates when >= 100.", "Risk")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(2).TimeFrame())
			.SetDisplay("Candle Type", "Candle series processed by the strategy.", "General");
	}

	/// <summary>
	/// Period for the longer simple moving average.
	/// </summary>
	public int LongPeriod
	{
		get => _longPeriod.Value;
		set => _longPeriod.Value = value;
	}

	/// <summary>
	/// Backward shift used when evaluating the longer SMA.
	/// </summary>
	public int LongShift
	{
		get => _longShift.Value;
		set => _longShift.Value = value;
	}

	/// <summary>
	/// Period for the shorter simple moving average.
	/// </summary>
	public int ShortPeriod
	{
		get => _shortPeriod.Value;
		set => _shortPeriod.Value = value;
	}

	/// <summary>
	/// Backward shift used when evaluating the shorter SMA.
	/// </summary>
	public int ShortShift
	{
		get => _shortShift.Value;
		set => _shortShift.Value = value;
	}

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

	/// <summary>
	/// Trailing stop distance in points (price steps).
	/// Trailing activates only when the configured value is at least 100.
	/// </summary>
	public decimal TrailingStopPoints
	{
		get => _trailingStopPoints.Value;
		set => _trailingStopPoints.Value = value;
	}

	/// <summary>
	/// Candle type processed by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

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

		_longSma = null;
		_shortSma = null;
		_longHistory.Clear();
		_shortHistory.Clear();
		_entryPrice = null;
		_stopPrice = null;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		_longSma = new SMA { Length = LongPeriod };
		_shortSma = new SMA { Length = ShortPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_longSma, _shortSma, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, _longSma);
			DrawIndicator(area, _shortSma);
			DrawOwnTrades(area);
		}
	}

	private void ProcessCandle(ICandleMessage candle, decimal longValue, decimal shortValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (_longSma?.IsFormed != true || _shortSma?.IsFormed != true)
			return;

		var longCapacity = Math.Max(LongShift, 1) + 2;
		var shortCapacity = Math.Max(ShortShift, 1) + 2;
		UpdateHistory(_longHistory, longValue, longCapacity);
		UpdateHistory(_shortHistory, shortValue, shortCapacity);

		if (!TryGetShiftedValue(_longHistory, 1, out var longPrev) ||
			!TryGetShiftedValue(_longHistory, LongShift, out var longShifted) ||
			!TryGetShiftedValue(_shortHistory, 1, out var shortPrev) ||
			!TryGetShiftedValue(_shortHistory, ShortShift, out var shortShifted))
		{
			return;
		}

		if (ManageExistingPosition(candle, longPrev, longShifted))
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		if (Position == 0)
		{
			var bullish = longPrev > longShifted && shortPrev > shortShifted;
			var bearish = longPrev < longShifted && shortPrev < shortShifted;

			if (bullish)
			{
				EnterLong(candle);
			}
			else if (bearish)
			{
				EnterShort(candle);
			}
		}
	}

	private bool ManageExistingPosition(ICandleMessage candle, decimal longPrev, decimal longShifted)
	{
		if (Position > 0)
		{
			if (longPrev < longShifted)
			{
				SellMarket(Position);
				ResetPositionState();
				return true;
			}

			if (UpdateLongStops(candle))
			{
				SellMarket(Position);
				ResetPositionState();
				return true;
			}
		}
		else if (Position < 0)
		{
			if (longPrev > longShifted)
			{
				BuyMarket(Math.Abs(Position));
				ResetPositionState();
				return true;
			}

			if (UpdateShortStops(candle))
			{
				BuyMarket(Math.Abs(Position));
				ResetPositionState();
				return true;
			}
		}

		return false;
	}

	private void EnterLong(ICandleMessage candle)
	{
		var volume = Volume;
		if (volume <= 0m)
			return;

		BuyMarket(volume);

		var step = GetPoint();
		var price = candle.ClosePrice;
		_entryPrice = price;

		_stopPrice = StopLossPoints > 0m ? price - StopLossPoints * step : null;
	}

	private void EnterShort(ICandleMessage candle)
	{
		var volume = Volume;
		if (volume <= 0m)
			return;

		SellMarket(volume);

		var step = GetPoint();
		var price = candle.ClosePrice;
		_entryPrice = price;

		_stopPrice = StopLossPoints > 0m ? price + StopLossPoints * step : null;
	}

	private bool UpdateLongStops(ICandleMessage candle)
	{
		if (_entryPrice is not decimal entry)
			return false;

		var step = GetPoint();
		if (step <= 0m)
			return false;

		if (_stopPrice is null && StopLossPoints > 0m)
		{
			_stopPrice = entry - StopLossPoints * step;
		}

		if (TrailingStopPoints >= 100m)
		{
			var trailingDistance = TrailingStopPoints * step;
			if (trailingDistance > 0m)
			{
				var currentPrice = candle.ClosePrice;
				if (currentPrice - entry > trailingDistance)
				{
					var newStop = currentPrice - trailingDistance;
					if (_stopPrice is not decimal existing || currentPrice - existing > trailingDistance)
					{
						_stopPrice = newStop;
					}
				}
			}
		}

		if (_stopPrice is not decimal stop)
			return false;

		return candle.LowPrice <= stop;
	}

	private bool UpdateShortStops(ICandleMessage candle)
	{
		if (_entryPrice is not decimal entry)
			return false;

		var step = GetPoint();
		if (step <= 0m)
			return false;

		if (_stopPrice is null && StopLossPoints > 0m)
		{
			_stopPrice = entry + StopLossPoints * step;
		}

		if (TrailingStopPoints >= 100m)
		{
			var trailingDistance = TrailingStopPoints * step;
			if (trailingDistance > 0m)
			{
				var currentPrice = candle.ClosePrice;
				if (entry - currentPrice > trailingDistance)
				{
					var newStop = currentPrice + trailingDistance;
					if (_stopPrice is not decimal existing || existing - currentPrice > trailingDistance)
					{
						_stopPrice = newStop;
					}
				}
			}
		}

		if (_stopPrice is not decimal stop)
			return false;

		return candle.HighPrice >= stop;
	}

	private void ResetPositionState()
	{
		_entryPrice = null;
		_stopPrice = null;
	}

	private static void UpdateHistory(List<decimal> history, decimal value, int capacity)
	{
		history.Add(value);
		if (history.Count > capacity)
		{
			history.RemoveAt(0);
		}
	}

	private static bool TryGetShiftedValue(List<decimal> history, int shift, out decimal value)
	{
		value = 0m;

		if (shift < 0)
			return false;

		var index = history.Count - 1 - shift;
		if (index < 0 || index >= history.Count)
			return false;

		value = history[index];
		return true;
	}

	private decimal GetPoint()
	{
		var step = Security?.PriceStep;
		if (step is decimal priceStep && priceStep > 0m)
			return priceStep;

		return 0.0001m;
	}
}