异常逆势策略
该算法检测短时间内的剧烈百分比变动并逆向交易。价格大幅上升超过阈值时做空,跌破阈值时做多。止损和止盈以跳数设置。
详情
- 入场条件: 价格在回溯窗口内的百分比变动超过阈值。
- 多空方向: 双向。
- 出场条件: 止损或止盈。
- 止损: 有。
- 默认值:
PercentageThreshold= 1LookbackMinutes= 30StopLossTicks= 100TakeProfitTicks= 200CandleType= TimeSpan.FromMinutes(1)
- 筛选:
- 类别: 逆势
- 方向: 双向
- 指标: 价格
- 止损: 有
- 复杂度: 基础
- 时间框架: 日内 (1m)
- 季节性: 无
- 神经网络: 无
- 背离: 无
- 风险等级: 中
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()