This strategy is a StockSharp high-level translation of the MQL expert advisor "The Predator". The original system mixes trend direction filters with momentum, Bollinger Bands, and stochastic oscillators. Two independent entry templates (Strategy 1 and Strategy 2) are available, replicating the selectable modes inside the MQL implementation.
The conversion focuses on candle-based processing, using StockSharp subscriptions and indicator bindings. All calculations are performed on a single configurable candle series.
Core Indicators
Linear Weighted Moving Averages (LWMA) – fast/slow structure to confirm the short-term trend.
Directional Movement Index + Average Directional Index (DMI/ADX) – directional strength and trend confirmation.
Momentum (period 14 by default) – measures the distance from the neutral 100 level for both breakout and pullback logic.
Bollinger Bands – two envelopes (narrow and wide) to detect context and prior candle location, especially for Strategy 2.
Stochastic Oscillator – additional filter for Strategy 2 to require momentum exhaustion zones.
MACD – trend momentum confirmation by comparing the MACD line with its signal.
Trading Logic
Common filters
Process only completed candles.
Require the selected indicators to be formed before trading (IsFormedAndOnlineAndAllowTrading).
ADX must be greater than the configured threshold.
Momentum deviation history is maintained for the last three values to match the MQL checks without calling GetValue on indicators.
Strategy 1
Long entries when:
ADX above threshold and +DI exceeds −DI.
Fast LWMA above slow LWMA.
Momentum deviation above the buy threshold on any of the last three values.
MACD line above its signal line.
Short entries mirror the above with the signs reversed.
Strategy 2
Long entries additionally require:
Previous candle close at or above the previous narrow-band lower Bollinger boundary.
Stochastic signal and main lines both above the upper threshold.
Momentum deviation below the buy threshold on any of the last three values (looking for pullbacks inside trends).
Short entries require:
Previous candle close at or below the previous narrow-band upper Bollinger boundary.
Stochastic signal line above the upper threshold while the main line is below the lower threshold.
Momentum deviation below the sell threshold on any of the last three values.
Position handling
The strategy cancels any pending active orders before opening a new trade.
When a reversal signal occurs, the strategy closes the current exposure and opens a new position in the opposite direction using a combined market order.
Risk Management
StartProtection configures:
Initial stop-loss distance in pips.
Initial take-profit distance in pips.
Optional trailing stop that trails by a fixed pip amount once armed.
Risk distances are converted into absolute price units using the security price step.
The money-based break-even and trailing modules from the original EA are replaced with these pip-based protections (documented difference below).
Parameters
Parameter
Description
Mode
Chooses Strategy 1 (trend breakout) or Strategy 2 (pullback with stochastic filters).
FastMaLength, SlowMaLength
LWMA lengths used to determine trend direction.
DmiPeriod, AdxSmoothing
Directional Movement Index parameters.
MomentumPeriod
Lookback used by the momentum indicator.
MomentumBuyThreshold, MomentumSellThreshold
Minimum deviation from 100 required to accept signals.
Parameters for the stochastic oscillator used in Strategy 2.
TradeVolume
Volume submitted with market orders.
StopLossPips, TakeProfitPips, TrailingStopPips
Risk distances (converted to price units with the instrument step).
CandleType
Data series used by the strategy.
Differences from the MQL Version
Money-based take-profit, stop-loss, and trailing values are translated into pip distances handled by StartProtection.
Break-even adjustments and notification emails/push messages are not ported (not available in high-level API).
The MQL expert called MACD and Momentum on higher timeframes. In StockSharp the logic runs on the configured candle series only; multi-timeframe data can be added through additional subscriptions if required.
Order volume optimization and martingale-style sizing are not implemented; the StockSharp version uses a fixed TradeVolume parameter.
Usage
Create a connector and portfolio as in other StockSharp samples.
Instantiate ThePredatorStrategy, assign Security, Portfolio, and desired parameters.
Start the strategy. Visualisation is optional but available when a chart area is provided.
The translation keeps the decision tree faithful to the original while embracing StockSharp best practices such as indicator binding and StartProtection for risk. Adjust thresholds to fit the chosen instrument and timeframe.
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;
public class ThePredatorStrategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<int> _takeProfitPoints;
private ExponentialMovingAverage _fast;
private ExponentialMovingAverage _slow;
private decimal _prevFast;
private decimal _prevSlow;
private decimal _entryPrice;
private int _cooldown;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public int StopLossPoints { get => _stopLossPoints.Value; set => _stopLossPoints.Value = value; }
public int TakeProfitPoints { get => _takeProfitPoints.Value; set => _takeProfitPoints.Value = value; }
public ThePredatorStrategy()
{
_fastPeriod = Param(nameof(FastPeriod), 14).SetGreaterThanZero().SetDisplay("Fast Period", "Fast EMA period", "Indicator");
_slowPeriod = Param(nameof(SlowPeriod), 50).SetGreaterThanZero().SetDisplay("Slow Period", "Slow EMA period", "Indicator");
_stopLossPoints = Param(nameof(StopLossPoints), 200).SetNotNegative().SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk");
_takeProfitPoints = Param(nameof(TakeProfitPoints), 400).SetNotNegative().SetDisplay("Take Profit", "Take-profit in price steps", "Risk");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
yield return (Security, TimeSpan.FromMinutes(5).TimeFrame());
}
protected override void OnReseted()
{
base.OnReseted();
_fast = null; _slow = null;
_prevFast = 0; _prevSlow = 0; _entryPrice = 0; _cooldown = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_fast = new ExponentialMovingAverage { Length = FastPeriod };
_slow = new ExponentialMovingAverage { Length = SlowPeriod };
var subscription = SubscribeCandles(TimeSpan.FromMinutes(5).TimeFrame());
subscription.Bind(_fast, _slow, ProcessCandle);
subscription.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fastValue, decimal slowValue)
{
if (candle.State != CandleStates.Finished) return;
if (!_fast.IsFormed || !_slow.IsFormed) { _prevFast = fastValue; _prevSlow = slowValue; return; }
if (_cooldown > 0) { _cooldown--; _prevFast = fastValue; _prevSlow = slowValue; return; }
var close = candle.ClosePrice;
var step = Security?.PriceStep ?? 1m;
if (Position > 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close <= _entryPrice - StopLossPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close >= _entryPrice + TakeProfitPoints * step) { SellMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
else if (Position < 0 && _entryPrice > 0)
{
if (StopLossPoints > 0 && close >= _entryPrice + StopLossPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
if (TakeProfitPoints > 0 && close <= _entryPrice - TakeProfitPoints * step) { BuyMarket(); _entryPrice = 0; _cooldown = 100; _prevFast = fastValue; _prevSlow = slowValue; return; }
}
if (_prevFast <= _prevSlow && fastValue > slowValue && Position <= 0)
{ if (Position < 0) BuyMarket(); BuyMarket(); _entryPrice = close; _cooldown = 100; }
else if (_prevFast >= _prevSlow && fastValue < slowValue && Position >= 0)
{ if (Position > 0) SellMarket(); SellMarket(); _entryPrice = close; _cooldown = 100; }
_prevFast = fastValue; _prevSlow = slowValue;
}
}
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
from StockSharp.Algo.Strategies import Strategy
class the_predator_strategy(Strategy):
def __init__(self):
super(the_predator_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 14) \
.SetDisplay("Fast Period", "Fast MA period", "Indicator")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow MA period", "Indicator")
self._stop_loss_points = self.Param("StopLossPoints", 200) \
.SetDisplay("Stop Loss", "Stop-loss in price steps", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 400) \
.SetDisplay("Take Profit", "Take-profit in price steps", "Risk")
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
@property
def fast_period(self):
return self._fast_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def stop_loss_points(self):
return self._stop_loss_points.Value
@property
def take_profit_points(self):
return self._take_profit_points.Value
def OnReseted(self):
super(the_predator_strategy, self).OnReseted()
self._fast = None
self._slow = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._entry_price = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(the_predator_strategy, self).OnStarted2(time)
self._fast = ExponentialMovingAverage()
self._fast.Length = self.fast_period
self._slow = ExponentialMovingAverage()
self._slow.Length = self.slow_period
subscription = self.SubscribeCandles(DataType.TimeFrame(TimeSpan.FromMinutes(5)))
subscription.Bind(self._fast, self._slow, self._process_candle)
subscription.Start()
def _process_candle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_value)
slow_val = float(slow_value)
if not self._fast.IsFormed or not self._slow.IsFormed:
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_fast = fast_val
self._prev_slow = slow_val
return
close = float(candle.ClosePrice)
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if self.Position > 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close <= self._entry_price - self.stop_loss_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close >= self._entry_price + self.take_profit_points * step:
self.SellMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
elif self.Position < 0 and self._entry_price > 0:
if self.stop_loss_points > 0 and close >= self._entry_price + self.stop_loss_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self.take_profit_points > 0 and close <= self._entry_price - self.take_profit_points * step:
self.BuyMarket()
self._entry_price = 0.0
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
return
if self._prev_fast <= self._prev_slow and fast_val > slow_val and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
self._entry_price = close
self._cooldown = 100
elif self._prev_fast >= self._prev_slow and fast_val < slow_val and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._entry_price = close
self._cooldown = 100
self._prev_fast = fast_val
self._prev_slow = slow_val
def CreateClone(self):
return the_predator_strategy()