Laguerre Filter
The strategy trades the crossover between a Laguerre filter and a short FIR filter built as a weighted moving average of recent median prices.
- The Laguerre filter smooths price using the Gamma parameter to reduce noise.
- The FIR line is a 4-period weighted moving average with symmetrical weights.
- When the FIR line was above the Laguerre line and crosses below it, the strategy opens a long position.
- When the FIR line was below and crosses above the Laguerre line, a short position is opened.
- Opposite positions are closed when the relation between the lines reverses.
- A stop-loss in percent of entry price protects every trade.
This mean-reversion approach attempts to capture pullbacks when price deviates from the smoothed Laguerre curve.
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>
/// Strategy based on Laguerre filter and WMA (FIR) crossover.
/// </summary>
public class LaguerreFilterStrategy : Strategy
{
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevFir;
private decimal? _prevLaguerre;
public decimal StopLossPct
{
get => _stopLossPct.Value;
set => _stopLossPct.Value = value;
}
public decimal TakeProfitPct
{
get => _takeProfitPct.Value;
set => _takeProfitPct.Value = value;
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public LaguerreFilterStrategy()
{
_stopLossPct = Param(nameof(StopLossPct), 2m)
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");
_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
.SetDisplay("Take Profit %", "Take profit percentage", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFir = _prevLaguerre = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var laguerre = new ExponentialMovingAverage { Length = 10 };
var fir = new WeightedMovingAverage { Length = 4 };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(laguerre, fir, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
useMarketOrders: true);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, laguerre);
DrawIndicator(area, fir);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal laguerreValue, decimal firValue)
{
if (candle.State != CandleStates.Finished)
return;
if (_prevFir is null || _prevLaguerre is null)
{
_prevFir = firValue;
_prevLaguerre = laguerreValue;
return;
}
var firWasAbove = _prevFir > _prevLaguerre;
var firIsAbove = firValue > laguerreValue;
if (!firWasAbove && firIsAbove && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (firWasAbove && !firIsAbove && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevFir = firValue;
_prevLaguerre = laguerreValue;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import ExponentialMovingAverage, WeightedMovingAverage
from StockSharp.Algo.Strategies import Strategy
class laguerre_filter_strategy(Strategy):
def __init__(self):
super(laguerre_filter_strategy, self).__init__()
self._stop_loss_pct = self.Param("StopLossPct", 2.0) \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk")
self._take_profit_pct = self.Param("TakeProfitPct", 3.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_fir = None
self._prev_laguerre = None
@property
def stop_loss_pct(self):
return self._stop_loss_pct.Value
@property
def take_profit_pct(self):
return self._take_profit_pct.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(laguerre_filter_strategy, self).OnReseted()
self._prev_fir = None
self._prev_laguerre = None
def OnStarted2(self, time):
super(laguerre_filter_strategy, self).OnStarted2(time)
laguerre = ExponentialMovingAverage()
laguerre.Length = 10
fir = WeightedMovingAverage()
fir.Length = 4
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(laguerre, fir, self.process_candle).Start()
self.StartProtection(
takeProfit=Unit(self.take_profit_pct, UnitTypes.Percent),
stopLoss=Unit(self.stop_loss_pct, UnitTypes.Percent),
useMarketOrders=True)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, laguerre)
self.DrawIndicator(area, fir)
self.DrawOwnTrades(area)
def process_candle(self, candle, laguerre_value, fir_value):
if candle.State != CandleStates.Finished:
return
laguerre_value = float(laguerre_value)
fir_value = float(fir_value)
if self._prev_fir is None or self._prev_laguerre is None:
self._prev_fir = fir_value
self._prev_laguerre = laguerre_value
return
fir_was_above = self._prev_fir > self._prev_laguerre
fir_is_above = fir_value > laguerre_value
if not fir_was_above and fir_is_above and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif fir_was_above and not fir_is_above and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_fir = fir_value
self._prev_laguerre = laguerre_value
def CreateClone(self):
return laguerre_filter_strategy()