Anomaly Counter-Trend Strategy
The algorithm detects sharp percentage moves over a short window and trades against them. When price jumps above the threshold it sells; when price drops below the threshold it buys. Stop-loss and take-profit are set in ticks.
Details
- Entry Criteria: Percentage change over lookback window exceeds threshold.
- Long/Short: Both directions.
- Exit Criteria: Stop-loss or take-profit.
- Stops: Yes.
- Default Values:
PercentageThreshold= 1LookbackMinutes= 30StopLossTicks= 100TakeProfitTicks= 200CandleType= TimeSpan.FromMinutes(1)
- Filters:
- Category: Counter-trend
- Direction: Both
- Indicators: Price
- Stops: Yes
- Complexity: Basic
- Timeframe: Intraday (1m)
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
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 that trades against sharp price moves using ROC indicator.
/// Short when ROC rises above threshold, long when ROC falls below negative threshold.
/// </summary>
public class AnomalyCounterTrendStrategy : Strategy
{
private readonly StrategyParam<decimal> _percentageThreshold;
private readonly StrategyParam<int> _rocLength;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private int _barIndex;
private int _lastTradeBar;
/// <summary>
/// Minimum ROC percentage to detect anomaly.
/// </summary>
public decimal PercentageThreshold
{
get => _percentageThreshold.Value;
set => _percentageThreshold.Value = value;
}
/// <summary>
/// ROC lookback period.
/// </summary>
public int RocLength
{
get => _rocLength.Value;
set => _rocLength.Value = value;
}
/// <summary>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Candle type to process.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="AnomalyCounterTrendStrategy"/>.
/// </summary>
public AnomalyCounterTrendStrategy()
{
_percentageThreshold = Param(nameof(PercentageThreshold), 1m)
.SetDisplay("Percentage Threshold", "Minimum ROC to trigger counter trade", "Anomaly Detection");
_rocLength = Param(nameof(RocLength), 60)
.SetDisplay("ROC Length", "Rate of change lookback period", "Anomaly Detection");
_cooldownBars = Param(nameof(CooldownBars), 200)
.SetDisplay("Cooldown Bars", "Bars between trades", "Trading");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_barIndex = 0;
_lastTradeBar = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var roc = new RateOfChange { Length = RocLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(roc, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal rocValue)
{
if (candle.State != CandleStates.Finished)
return;
_barIndex++;
var cooldownOk = _barIndex - _lastTradeBar > CooldownBars;
// Counter-trend: sell when sharp rise, buy when sharp fall
if (rocValue >= PercentageThreshold && Position >= 0 && cooldownOk)
{
SellMarket();
_lastTradeBar = _barIndex;
}
else if (rocValue <= -PercentageThreshold && Position <= 0 && cooldownOk)
{
BuyMarket();
_lastTradeBar = _barIndex;
}
}
}
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 RateOfChange
from StockSharp.Algo.Strategies import Strategy
class anomaly_counter_trend_strategy(Strategy):
def __init__(self):
super(anomaly_counter_trend_strategy, self).__init__()
self._percentage_threshold = self.Param("PercentageThreshold", 1.0) \
.SetDisplay("Percentage Threshold", "Minimum ROC to trigger counter trade", "Anomaly Detection")
self._roc_length = self.Param("RocLength", 60) \
.SetDisplay("ROC Length", "Rate of change lookback period", "Anomaly Detection")
self._cooldown_bars = self.Param("CooldownBars", 200) \
.SetDisplay("Cooldown Bars", "Bars between trades", "Trading")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._bar_index = 0
self._last_trade_bar = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
@property
def cooldown_bars(self):
return self._cooldown_bars.Value
@cooldown_bars.setter
def cooldown_bars(self, value):
self._cooldown_bars.Value = value
def OnReseted(self):
super(anomaly_counter_trend_strategy, self).OnReseted()
self._bar_index = 0
self._last_trade_bar = 0
def OnStarted2(self, time):
super(anomaly_counter_trend_strategy, self).OnStarted2(time)
roc = RateOfChange()
roc.Length = self._roc_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(roc, self.OnProcess).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
def OnProcess(self, candle, roc_val):
if candle.State != CandleStates.Finished:
return
self._bar_index += 1
roc_v = float(roc_val)
threshold = float(self._percentage_threshold.Value)
cooldown_ok = self._bar_index - self._last_trade_bar > self.cooldown_bars
if roc_v >= threshold and self.Position >= 0 and cooldown_ok:
self.SellMarket()
self._last_trade_bar = self._bar_index
elif roc_v <= -threshold and self.Position <= 0 and cooldown_ok:
self.BuyMarket()
self._last_trade_bar = self._bar_index
def CreateClone(self):
return anomaly_counter_trend_strategy()