Auf GitHub ansehen

BrainTrend2 V2 Duplex Strategy

Overview

The BrainTrend2 V2 Duplex strategy is a high-level StockSharp port of the original MetaTrader 5 expert Exp_BrainTrend2_V2_Duplex. It runs two independent instances of the BrainTrend2 V2 indicator: one dedicated to long opportunities and another tuned for short opportunities. Each side can operate on its own candle series, ATR length, and signal shift, allowing the strategy to mix multi-timeframe confirmations or asymmetric risk settings.

BrainTrend2 V2 is a trend-following engine that builds a dynamic "river" channel by comparing the most recent true range against a weighted ATR average. The indicator paints candles with five distinct colors:

  • 0 – Bullish candle within an uptrend river.
  • 1 – Bearish candle within an uptrend river.
  • 2 – Neutral placeholder while the river is switching direction.
  • 3 – Bullish candle within a downtrend river.
  • 4 – Bearish candle within a downtrend river.

The duplex strategy interprets those color transitions to trigger entries and exits, closely mirroring the rules hard-coded in the MQL5 expert.

Trading Logic

Long side

  • Evaluate the indicator on the candle located Long Signal Bar steps back (default 1 = the previous finished bar).
  • Open a long position when:
    • The color on bar SignalBar + 1 (two bars back) was less than 2 (green tones of an uptrend river), and
    • The color on bar SignalBar is greater than 1 (transition away from the pure bullish state).
  • Close an existing long position when the color on bar SignalBar + 1 is greater than 2 (magenta tones produced by the downtrend river).

Short side

  • Evaluate the indicator on the candle located Short Signal Bar steps back (default 1).
  • Open a short position when:
    • The color on bar SignalBar + 1 was greater than 2 (magenta tones), and
    • The color on bar SignalBar is greater than 0 (anything except a pure bullish candle).
  • Close an existing short position when the color on bar SignalBar + 1 is less than 2 (return to the uptrend river).

When a new order is issued the strategy automatically offsets any opposite exposure. For example, a short entry request will first buy back the current long position (if any) and then send the sell order for the configured short volume.

Risk Management

  • Both sides can specify independent stop-loss and take-profit distances in points. A value of 0 disables the respective bracket.
  • Stops and targets are computed in absolute prices using the security price step. Longs monitor the candle low/high, shorts monitor the candle high/low to emulate intrabar execution.
  • Position size is expressed directly in trading units and can differ between long and short streams.
  • The strategy also enables StartProtection() to integrate with any portfolio-level safeguards configured inside StockSharp.

Parameters

Parameter Description Default
Long Candle Type Candle data type used for the long indicator (time frame). H4 time frame
Long ATR Period ATR lookback used in the BrainTrend2 V2 calculation for the long stream. 7
Long Signal Bar Historical shift (in bars) evaluated for long decisions. 1
Enable Long Entries Allows or blocks new long orders. true
Enable Long Exits Allows or blocks long exits generated by the indicator. true
Long Volume Base order size for long entries. 1
Long Stop Loss Stop-loss distance in points for long trades (0 = disabled). 1000
Long Take Profit Take-profit distance in points for long trades (0 = disabled). 2000
Short Candle Type Candle data type used for the short indicator. H4 time frame
Short ATR Period ATR lookback used in the BrainTrend2 V2 calculation for the short stream. 7
Short Signal Bar Historical shift (in bars) evaluated for short decisions. 1
Enable Short Entries Allows or blocks new short orders. true
Enable Short Exits Allows or blocks short exits generated by the indicator. true
Short Volume Base order size for short entries. 1
Short Stop Loss Stop-loss distance in points for short trades (0 = disabled). 1000
Short Take Profit Take-profit distance in points for short trades (0 = disabled). 2000

Usage Notes

  • Use larger signal shifts to wait for additional candle confirmation or combine different time frames by assigning distinct candle types to long and short streams.
  • Because the strategy uses a custom BrainTrend2 implementation, it does not rely on any external indicator files; everything is self-contained inside the C# class.
  • Stops and targets are managed on every finished candle. When running on live data, consider using a sufficiently small candle interval if you require tighter risk control.
  • Setting both stop and take-profit distances to zero keeps positions open until an opposite color trigger appears.
  • The indicator buffer is initialized once enough candles equal to the ATR period have been processed. Until that moment no trading decisions are taken.
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>
/// BrainTrend2 V2 Duplex strategy (simplified).
/// Uses ATR-based channel breakout for trend detection.
/// </summary>
public class BrainTrend2V2DuplexStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _atrPeriod;
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<decimal> _channelMult;

	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	public int AtrPeriod
	{
		get => _atrPeriod.Value;
		set => _atrPeriod.Value = value;
	}

	public int EmaPeriod
	{
		get => _emaPeriod.Value;
		set => _emaPeriod.Value = value;
	}

	public decimal ChannelMult
	{
		get => _channelMult.Value;
		set => _channelMult.Value = value;
	}

	public BrainTrend2V2DuplexStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candles", "General");

		_atrPeriod = Param(nameof(AtrPeriod), 7)
			.SetGreaterThanZero()
			.SetDisplay("ATR Period", "ATR length", "Indicators");

		_emaPeriod = Param(nameof(EmaPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA length for trend", "Indicators");

		_channelMult = Param(nameof(ChannelMult), 2.5m)
			.SetGreaterThanZero()
			.SetDisplay("Channel Mult", "ATR multiplier for channel width", "Indicators");
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var atr = new AverageTrueRange { Length = AtrPeriod };
		var ema = new ExponentialMovingAverage { Length = EmaPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(atr, ema, (ICandleMessage candle, decimal atrValue, decimal emaValue) =>
			{
				if (candle.State != CandleStates.Finished)
					return;

				if (!IsFormedAndOnlineAndAllowTrading())
					return;

				var close = candle.ClosePrice;
				var upper = emaValue + ChannelMult * atrValue;
				var lower = emaValue - ChannelMult * atrValue;

				// Buy when close breaks above upper channel
				if (close > upper && Position <= 0)
				{
					BuyMarket();
				}
				// Sell when close breaks below lower channel
				else if (close < lower && Position >= 0)
				{
					SellMarket();
				}
			})
			.Start();

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