This strategy re-creates the MetaTrader expert Exp_BrainTrend2_AbsolutelyNoLagLwma_MMRec by combining two independent signal blocks: the BrainTrend2 trend-following engine and the AbsolutelyNoLagLWMA adaptive filter. Each block can open and close trades according to its own permissions, mimicking the money-management switches of the original MMRec template. Orders are executed with the StockSharp high-level API using market executions and the configurable default volume.
Trading Logic
BrainTrend2 Block
Builds a dynamic trailing level based on an ATR-like weighted true range.
The direction (river) toggles when the candle pierces the trailing buffer by more than 0.7 * ATR.
Up candles inside an up river trigger long entries (if enabled) and close short positions.
Down candles inside a down river trigger short entries (if enabled) and close long positions.
Signals can be delayed by the Brain Signal Shift parameter to work with older bars.
AbsolutelyNoLagLWMA Block
Applies a two-stage linear weighted moving average to the selected price source.
Colours become up (2) when the double LWMA rises, down (0) when it falls and neutral (1) otherwise.
A transition to colour 2 opens longs and optionally exits shorts; a switch to colour 0 opens shorts and optionally exits longs.
Signals may also be shifted back by a user-defined number of bars.
Position Management
The strategy operates a single net position. When both blocks request trades on the same bar, close signals execute before any new entries.
If a block wants to open a trade but the opposite position is open and the corresponding close permission is disabled, the entry is skipped (mirrors the inability to hold hedged positions with a single net portfolio).
Parameters
Group
Name
Description
BrainTrend2
Brain Candle
Candle type used for the BrainTrend2 indicator.
BrainTrend2
Brain ATR
ATR period for the internal BrainTrend2 calculations.
BrainTrend2
Brain Signal Shift
Number of bars to delay BrainTrend2 signals.
BrainTrend2
Brain Buy / Sell
Allow BrainTrend2 to open long/short trades.
BrainTrend2
Brain Close Buys / Close Sells
Allow BrainTrend2 signals to close existing positions.
AbsolutelyNoLag
Abs Candle
Candle type used for the LWMA indicator.
AbsolutelyNoLag
Abs Length
LWMA period.
AbsolutelyNoLag
Abs Price
Applied price used for the LWMA. Matches the MQL Applied_price_ enum.
AbsolutelyNoLag
Abs Signal Shift
Number of bars to delay LWMA signals.
AbsolutelyNoLag
Abs Buy / Sell
Allow LWMA block to open long/short trades.
AbsolutelyNoLag
Abs Close Buys / Close Sells
Allow LWMA block to close positions.
AbsolutelyNoLag
Abs Shift
Adds a constant price offset to the LWMA output.
General
Order Volume
Default market order volume.
Notes
The ATR and LWMA computations follow the original MQL implementations, including the triangular ATR weighting and the extensive applied price list.
Spread information is unavailable in StockSharp candles, so the true range uses candle prices only. This mirrors the indicator behaviour when spread equals zero.
Multiple simultaneous positions with different magic numbers are consolidated into a single net position, which is standard in StockSharp strategies.
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 AbsolutelyNoLag LWMA MMRec strategy (simplified).
/// Uses RSI + EMA for trend detection with position recovery logic.
/// </summary>
public class BrainTrend2AbsolutelyNoLagLwmaMmrecStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<int> _emaLength;
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int RsiLength
{
get => _rsiLength.Value;
set => _rsiLength.Value = value;
}
public int EmaLength
{
get => _emaLength.Value;
set => _emaLength.Value = value;
}
public BrainTrend2AbsolutelyNoLagLwmaMmrecStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "Indicators");
_emaLength = Param(nameof(EmaLength), 20)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period", "Indicators");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var ema = new ExponentialMovingAverage { Length = EmaLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(rsi, ema, (ICandleMessage candle, decimal rsiVal, decimal emaVal) =>
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var close = candle.ClosePrice;
// Bullish: RSI above 55 and close above EMA
if (rsiVal > 55 && close > emaVal && Position <= 0)
BuyMarket();
// Bearish: RSI below 45 and close below EMA
else if (rsiVal < 45 && close < emaVal && Position >= 0)
SellMarket();
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
}
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 RelativeStrengthIndex, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class brain_trend2_absolutely_no_lag_lwma_mmrec_strategy(Strategy):
def __init__(self):
super(brain_trend2_absolutely_no_lag_lwma_mmrec_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candles", "General")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period", "Indicators")
self._ema_length = self.Param("EmaLength", 20) \
.SetDisplay("EMA Length", "EMA period", "Indicators")
@property
def CandleType(self):
return self._candle_type.Value
@property
def RsiLength(self):
return self._rsi_length.Value
@property
def EmaLength(self):
return self._ema_length.Value
def OnStarted2(self, time):
super(brain_trend2_absolutely_no_lag_lwma_mmrec_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self.RsiLength
ema = ExponentialMovingAverage()
ema.Length = self.EmaLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(rsi, ema, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, rsi_value, ema_value):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
rv = float(rsi_value)
ev = float(ema_value)
if rv > 55 and close > ev and self.Position <= 0:
self.BuyMarket()
elif rv < 45 and close < ev and self.Position >= 0:
self.SellMarket()
def CreateClone(self):
return brain_trend2_absolutely_no_lag_lwma_mmrec_strategy()