Zero-Lag MA Trend Following
Trend following system that waits for a zero-lag MA to cross an EMA and then enters when price breaks out of an ATR-sized box. Positions include risk-reward based targets.
Details
- Entry Criteria: Zero-lag MA cross and box breakout.
- Long/Short: Both directions.
- Exit Criteria: ATR-based stop or take profit.
- Stops: Yes.
- Default Values:
Length= 34AtrPeriod= 14RiskReward= 2mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: ZLEMA, EMA, ATR
- Stops: Yes
- Complexity: Intermediate
- Timeframe: Intraday (5m)
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
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 zero lag moving average and EMA breakout boxes.
/// </summary>
public class ZeroLagMaTrendFollowingStrategy : Strategy
{
private readonly StrategyParam<int> _length;
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _riskReward;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevZlma;
private decimal _prevEma;
private bool _longSetup;
private bool _shortSetup;
private decimal _boxTop;
private decimal _boxBottom;
private decimal _stopPrice;
private decimal _takeProfitPrice;
private bool _entryPlaced;
public int Length { get => _length.Value; set => _length.Value = value; }
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public decimal RiskReward { get => _riskReward.Value; set => _riskReward.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ZeroLagMaTrendFollowingStrategy()
{
_length = Param(nameof(Length), 34).SetDisplay("Length", "MA length", "Indicators");
_atrPeriod = Param(nameof(AtrPeriod), 14).SetDisplay("ATR Period", "ATR length", "Indicators");
_riskReward = Param(nameof(RiskReward), 2m).SetDisplay("Risk/Reward", "Take profit ratio", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame()).SetDisplay("Candle Type", "Candle timeframe", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_prevZlma = 0;
_prevEma = 0;
_longSetup = false;
_shortSetup = false;
_boxTop = 0;
_boxBottom = 0;
_stopPrice = 0;
_takeProfitPrice = 0;
_entryPlaced = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var zlma = new ZeroLagExponentialMovingAverage { Length = Length };
var ema = new ExponentialMovingAverage { Length = Length };
var atr = new AverageTrueRange { Length = AtrPeriod };
_prevZlma = 0;
_prevEma = 0;
_longSetup = false;
_shortSetup = false;
_boxTop = 0;
_boxBottom = 0;
_stopPrice = 0;
_takeProfitPrice = 0;
_entryPlaced = false;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(zlma, ema, atr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal zlmaVal, decimal emaVal, decimal atrValue)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevZlma == 0)
{
_prevZlma = zlmaVal;
_prevEma = emaVal;
return;
}
var crossUp = _prevZlma <= _prevEma && zlmaVal > emaVal;
var crossDown = _prevZlma >= _prevEma && zlmaVal < emaVal;
_prevZlma = zlmaVal;
_prevEma = emaVal;
if (crossUp)
{
_boxTop = zlmaVal;
_boxBottom = zlmaVal - atrValue;
_longSetup = true;
_shortSetup = false;
}
else if (crossDown)
{
_boxTop = zlmaVal + atrValue;
_boxBottom = zlmaVal;
_shortSetup = true;
_longSetup = false;
}
var price = candle.ClosePrice;
if (!_entryPlaced)
{
if (_longSetup && candle.LowPrice > _boxTop && Position <= 0)
{
BuyMarket();
_entryPlaced = true;
_stopPrice = _boxBottom;
_takeProfitPrice = price + (price - _stopPrice) * RiskReward;
_longSetup = false;
}
else if (_shortSetup && candle.HighPrice < _boxBottom && Position >= 0)
{
SellMarket();
_entryPlaced = true;
_stopPrice = _boxTop;
_takeProfitPrice = price - (_stopPrice - price) * RiskReward;
_shortSetup = false;
}
}
else
{
if (Position > 0)
{
if (candle.LowPrice <= _stopPrice || candle.HighPrice >= _takeProfitPrice)
{
SellMarket();
_entryPlaced = false;
}
}
else if (Position < 0)
{
if (candle.HighPrice >= _stopPrice || candle.LowPrice <= _takeProfitPrice)
{
BuyMarket();
_entryPlaced = false;
}
}
}
}
}
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 AverageTrueRange, ExponentialMovingAverage, ZeroLagExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class zero_lag_ma_trend_following_strategy(Strategy):
def __init__(self):
super(zero_lag_ma_trend_following_strategy, self).__init__()
self._length_param = self.Param("Length", 34) \
.SetDisplay("Length", "MA length", "Indicators")
self._atr_period_param = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "ATR length", "Indicators")
self._risk_reward_param = self.Param("RiskReward", 2.0) \
.SetDisplay("Risk/Reward", "Take profit ratio", "Risk")
self._candle_type_param = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_zlma = 0.0
self._prev_ema = 0.0
self._long_setup = False
self._short_setup = False
self._box_top = 0.0
self._box_bottom = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_placed = False
@property
def length(self):
return self._length_param.Value
@property
def atr_period(self):
return self._atr_period_param.Value
@property
def risk_reward(self):
return self._risk_reward_param.Value
@property
def candle_type(self):
return self._candle_type_param.Value
def OnReseted(self):
super(zero_lag_ma_trend_following_strategy, self).OnReseted()
self._prev_zlma = 0.0
self._prev_ema = 0.0
self._long_setup = False
self._short_setup = False
self._box_top = 0.0
self._box_bottom = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_placed = False
def OnStarted2(self, time):
super(zero_lag_ma_trend_following_strategy, self).OnStarted2(time)
zlma = ZeroLagExponentialMovingAverage()
zlma.Length = self.length
ema = ExponentialMovingAverage()
ema.Length = self.length
atr = AverageTrueRange()
atr.Length = self.atr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(zlma, ema, atr, 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, zlma_val, ema_val, atr_value):
if candle.State != CandleStates.Finished:
return
if self._prev_zlma == 0:
self._prev_zlma = zlma_val
self._prev_ema = ema_val
return
cross_up = self._prev_zlma <= self._prev_ema and zlma_val > ema_val
cross_down = self._prev_zlma >= self._prev_ema and zlma_val < ema_val
self._prev_zlma = zlma_val
self._prev_ema = ema_val
if cross_up:
self._box_top = zlma_val
self._box_bottom = zlma_val - atr_value
self._long_setup = True
self._short_setup = False
elif cross_down:
self._box_top = zlma_val + atr_value
self._box_bottom = zlma_val
self._short_setup = True
self._long_setup = False
price = candle.ClosePrice
if not self._entry_placed:
if self._long_setup and candle.LowPrice > self._box_top and self.Position <= 0:
self.BuyMarket()
self._entry_placed = True
self._stop_price = self._box_bottom
self._take_profit_price = price + (price - self._stop_price) * self.risk_reward
self._long_setup = False
elif self._short_setup and candle.HighPrice < self._box_bottom and self.Position >= 0:
self.SellMarket()
self._entry_placed = True
self._stop_price = self._box_top
self._take_profit_price = price - (self._stop_price - price) * self.risk_reward
self._short_setup = False
else:
if self.Position > 0:
if candle.LowPrice <= self._stop_price or candle.HighPrice >= self._take_profit_price:
self.SellMarket()
self._entry_placed = False
elif self.Position < 0:
if candle.HighPrice >= self._stop_price or candle.LowPrice <= self._take_profit_price:
self.BuyMarket()
self._entry_placed = False
def CreateClone(self):
return zero_lag_ma_trend_following_strategy()