Zero-Lag TEMA Crosses Strategy
Zero-lag triple EMA crossover system. Positions use recent highs and lows for stops and risk-reward based targets.
Details
- Entry Criteria: Fast TEMA crossing slow TEMA.
- Long/Short: Both directions.
- Exit Criteria: Stop at recent extreme or target by ratio.
- Stops: Yes.
- Default Values:
Lookback= 20FastPeriod= 69SlowPeriod= 130RiskReward= 1.5mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: TEMA
- 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>
/// Strategy based on zero-lag TEMA crossovers with stop and target from recent extremes.
/// </summary>
public class ZeroLagTemaCrossesPakunStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<decimal> _riskReward;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _stopPrice;
private decimal _takeProfitPrice;
private bool _entryPlaced;
public int Lookback { get => _lookback.Value; set => _lookback.Value = value; }
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public decimal RiskReward { get => _riskReward.Value; set => _riskReward.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ZeroLagTemaCrossesPakunStrategy()
{
_lookback = Param(nameof(Lookback), 20).SetDisplay("Lookback", "Lookback period", "Indicators");
_fastPeriod = Param(nameof(FastPeriod), 20).SetDisplay("Fast Period", "Fast TEMA length", "Indicators");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetDisplay("Slow Period", "Slow TEMA length", "Indicators");
_riskReward = Param(nameof(RiskReward), 1.5m).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();
_prevFast = 0;
_prevSlow = 0;
_stopPrice = 0;
_takeProfitPrice = 0;
_entryPlaced = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastTema = new TripleExponentialMovingAverage { Length = FastPeriod };
var slowTema = new TripleExponentialMovingAverage { Length = SlowPeriod };
var highest = new Highest { Length = Lookback };
var lowest = new Lowest { Length = Lookback };
_prevFast = 0;
_prevSlow = 0;
_stopPrice = 0;
_takeProfitPrice = 0;
_entryPlaced = false;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(fastTema, slowTema, highest, lowest, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal highestVal, decimal lowestVal)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevFast == 0)
{
_prevFast = fast;
_prevSlow = slow;
return;
}
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
_prevFast = fast;
_prevSlow = slow;
var price = candle.ClosePrice;
if (!_entryPlaced)
{
if (crossUp && Position <= 0)
{
BuyMarket();
_entryPlaced = true;
_stopPrice = lowestVal;
_takeProfitPrice = price + (price - _stopPrice) * RiskReward;
}
else if (crossDown && Position >= 0)
{
SellMarket();
_entryPlaced = true;
_stopPrice = highestVal;
_takeProfitPrice = price - (_stopPrice - price) * RiskReward;
}
}
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 ExponentialMovingAverage, TripleExponentialMovingAverage, Highest, Lowest
from StockSharp.Algo.Strategies import Strategy
class zero_lag_tema_crosses_pakun_strategy(Strategy):
def __init__(self):
super(zero_lag_tema_crosses_pakun_strategy, self).__init__()
self._lookback = self.Param("Lookback", 20) \
.SetDisplay("Lookback", "Lookback period", "Indicators")
self._fast_period = self.Param("FastPeriod", 20) \
.SetDisplay("Fast Period", "Fast TEMA length", "Indicators")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow TEMA length", "Indicators")
self._risk_reward = self.Param("RiskReward", 1.5) \
.SetDisplay("Risk/Reward", "Take profit ratio", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_placed = False
@property
def lookback(self):
return self._lookback.Value
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def risk_reward(self):
return self._risk_reward.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(zero_lag_tema_crosses_pakun_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._stop_price = 0.0
self._take_profit_price = 0.0
self._entry_placed = False
def OnStarted2(self, time):
super(zero_lag_tema_crosses_pakun_strategy, self).OnStarted2(time)
fast_tema = TripleExponentialMovingAverage()
fast_tema.Length = self.fast_period
slow_tema = TripleExponentialMovingAverage()
slow_tema.Length = self.slow_period
highest = Highest()
highest.Length = self.lookback
lowest = Lowest()
lowest.Length = self.lookback
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_tema, slow_tema, highest, lowest, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow, highest_val, lowest_val):
if candle.State != CandleStates.Finished:
return
if self._prev_fast == 0:
self._prev_fast = fast
self._prev_slow = slow
return
cross_up = self._prev_fast <= self._prev_slow and fast > slow
cross_down = self._prev_fast >= self._prev_slow and fast < slow
self._prev_fast = fast
self._prev_slow = slow
price = float(candle.ClosePrice)
if not self._entry_placed:
if cross_up and self.Position <= 0:
self.BuyMarket()
self._entry_placed = True
self._stop_price = float(lowest_val)
self._take_profit_price = price + (price - self._stop_price) * float(self.risk_reward)
elif cross_down and self.Position >= 0:
self.SellMarket()
self._entry_placed = True
self._stop_price = float(highest_val)
self._take_profit_price = price - (self._stop_price - price) * float(self.risk_reward)
else:
if self.Position > 0:
if float(candle.LowPrice) <= self._stop_price or float(candle.HighPrice) >= self._take_profit_price:
self.SellMarket()
self._entry_placed = False
elif self.Position < 0:
if float(candle.HighPrice) >= self._stop_price or float(candle.LowPrice) <= self._take_profit_price:
self.BuyMarket()
self._entry_placed = False
def CreateClone(self):
return zero_lag_tema_crosses_pakun_strategy()