Two-Pole Ideal MA Strategy
Crossover system approximating the "2pb Ideal MA" expert by comparing a fast EMA with a slow TEMA.
Details
- Entry Criteria: Fast EMA crossing slow TEMA.
- Long/Short: Both directions.
- Exit Criteria: Reverse on opposite crossover.
- Stops: No.
- Default Values:
FastPeriod= 10SlowPeriod= 30CandleType= TimeSpan.FromHours(4)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: EMA, TEMA
- Stops: No
- Complexity: Beginner
- Timeframe: Swing (H4)
- 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>
/// Crosses a fast EMA and a slow TEMA to approximate the original 2pb Ideal MA logic.
/// </summary>
public class TwoPoleIdealMaStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _minSpreadPercent;
private readonly StrategyParam<int> _cooldownBars;
private ExponentialMovingAverage _fastMa = null!;
private TripleExponentialMovingAverage _slowMa = null!;
private decimal _prevFast;
private decimal _prevSlow;
private int _cooldownRemaining;
/// <summary>
/// Fast EMA length.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow TEMA length.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Candle timeframe used by the strategy.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Minimum normalized spread between the fast and slow averages.
/// </summary>
public decimal MinSpreadPercent
{
get => _minSpreadPercent.Value;
set => _minSpreadPercent.Value = value;
}
/// <summary>
/// Number of completed candles to wait after a position change.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="TwoPoleIdealMaStrategy"/>.
/// </summary>
public TwoPoleIdealMaStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 10).SetDisplay("Fast Period", "Fast MA length", "Indicators");
_slowPeriod = Param(nameof(SlowPeriod), 30).SetDisplay("Slow Period", "Slow MA length", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame()).SetDisplay("Candle Type", "Candle timeframe", "General");
_minSpreadPercent = Param(nameof(MinSpreadPercent), 0.001m).SetDisplay("Minimum Spread %", "Minimum normalized spread between fast and slow averages", "Filters");
_cooldownBars = Param(nameof(CooldownBars), 4).SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_fastMa = null!;
_slowMa = null!;
_prevFast = 0m;
_prevSlow = 0m;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Initialize indicators.
_fastMa = new ExponentialMovingAverage { Length = FastPeriod };
_slowMa = new TripleExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_fastMa, _slowMa, ProcessCandle)
.Start();
// Enable default protective behavior.
StartProtection(null, null);
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
// Process only finished candles.
if (candle.State != CandleStates.Finished)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
var crossUp = _prevFast <= _prevSlow && fast > slow;
var crossDown = _prevFast >= _prevSlow && fast < slow;
var spreadPercent = candle.ClosePrice != 0m ? Math.Abs(fast - slow) / candle.ClosePrice : 0m;
_prevFast = fast;
_prevSlow = slow;
if (crossUp && Position <= 0 && spreadPercent >= MinSpreadPercent && _cooldownRemaining == 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
_cooldownRemaining = CooldownBars;
}
else if (crossDown && Position >= 0 && spreadPercent >= MinSpreadPercent && _cooldownRemaining == 0)
{
if (Position > 0) SellMarket();
SellMarket();
_cooldownRemaining = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import ExponentialMovingAverage, TripleExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class two_pole_ideal_ma_strategy(Strategy):
def __init__(self):
super(two_pole_ideal_ma_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 10) \
.SetDisplay("Fast Period", "Fast MA length", "Indicators")
self._slow_period = self.Param("SlowPeriod", 30) \
.SetDisplay("Slow Period", "Slow MA length", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle Type", "Candle timeframe", "General")
self._min_spread_percent = self.Param("MinSpreadPercent", 0.001) \
.SetDisplay("Minimum Spread %", "Minimum normalized spread between fast and slow averages", "Filters")
self._cooldown_bars = self.Param("CooldownBars", 4) \
.SetDisplay("Cooldown Bars", "Completed candles to wait after a position change", "Trading")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._cooldown_remaining = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def candle_type(self):
return self._candle_type.Value
@property
def min_spread_percent(self):
return self._min_spread_percent.Value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
def OnReseted(self):
super(two_pole_ideal_ma_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(two_pole_ideal_ma_strategy, self).OnStarted2(time)
fast_ma = ExponentialMovingAverage()
fast_ma.Length = self.fast_period
slow_ma = TripleExponentialMovingAverage()
slow_ma.Length = self.slow_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ma, slow_ma, self.process_candle).Start()
def process_candle(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
fast = float(fast)
slow = float(slow)
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
cross_up = self._prev_fast <= self._prev_slow and fast > slow
cross_down = self._prev_fast >= self._prev_slow and fast < slow
close = float(candle.ClosePrice)
spread_percent = abs(fast - slow) / close if close != 0 else 0.0
self._prev_fast = fast
self._prev_slow = slow
min_sp = float(self.min_spread_percent)
if cross_up and self.Position <= 0 and spread_percent >= min_sp and self._cooldown_remaining == 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._cooldown_remaining = self.cooldown_bars
elif cross_down and self.Position >= 0 and spread_percent >= min_sp and self._cooldown_remaining == 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._cooldown_remaining = self.cooldown_bars
def CreateClone(self):
return two_pole_ideal_ma_strategy()