Trade on Qualified RSI 策略
概述
该策略将 MetaTrader 的 "Trade on qualified RSI" 专家顾问迁移到 StockSharp 高级 API。它是一种逆势策略:当 RSI 长时间停留在极端区域时,算法将其视为动能耗尽的信号,并在获得多根蜡烛确认后,向相反方向开仓。止损按价格最小变动单位(PriceStep)进行跟踪,只在价格向有利方向移动时上调或下调。
信号逻辑
指标
- 可配置周期的相对强弱指标(RSI),默认长度为 28。
- 基于所选蜡烛序列计算,默认使用 15 分钟蜡烛。
做空条件
- 最近一根已收盘的蜡烛 RSI 大于或等于上限阈值(默认 55)。
- 在此之前的
CountBars根蜡烛 RSI 也全部高于该阈值。策略内部维护一个连续计数器,当计数达到CountBars + 1时触发信号。 - 当前没有持仓。满足条件后,以设定的交易量市价卖出,并将收盘价记录为入场价。
做多条件
- 最近一根已收盘的蜡烛 RSI 小于或等于下限阈值(默认 45)。
- 在此之前的
CountBars根蜡烛 RSI 也全部低于该阈值(同样需要连续CountBars + 1根满足条件)。 - 当前没有持仓。满足条件后,以设定的交易量市价买入,并记录收盘价。
仓位管理
- 初始止损: 开仓后立即将止损设置在距离入场价
StopLossPoints个价格步长的位置(多头在入场价下方,空头在上方)。价格步长来自Security.PriceStep,若未定义则回退为1。 - 跟踪止损: 每根收盘蜡烛都会尝试收紧止损。多头仓位的新止损为
收盘价 - StopLossPoints * PriceStep(前提是该值高于当前止损);空头仓位的新止损为收盘价 + StopLossPoints * PriceStep(前提是该值低于当前止损)。 - 离场: 当多头蜡烛最低价跌破止损,或空头蜡烛最高价突破止损时,策略以市价平掉全部仓位。没有额外的止盈目标或反向信号,只有在前一笔仓位关闭后才会出现新的入场。
参数
| 参数 | 说明 | 默认值 |
|---|---|---|
RsiPeriod |
RSI 指标的计算周期。 | 28 |
UpperThreshold |
触发做空信号的 RSI 阈值。 | 55 |
LowerThreshold |
触发做多信号的 RSI 阈值。 | 45 |
CountBars |
需要连续保持在阈值外侧的历史蜡烛数量(总计 CountBars + 1 根)。 |
5 |
StopLossPoints |
止损距离(以价格步长计),实际价格偏移量为 StopLossPoints * PriceStep。 |
21 |
TradeVolume |
每次入场使用的交易量。 | 1 |
CandleType |
用于计算的蜡烛类型。 | 15 分钟蜡烛 |
所有参数均支持优化。阈值采用十进制,可以精细调整 RSI 边界以适应不同市场。
实现细节
- 通过
SubscribeCandles(...).Bind(...)订阅蜡烛数据并驱动 RSI,只在蜡烛完全收盘后触发逻辑。 - 不通过索引读取 RSI 历史值,而是使用连续计数器来验证阈值条件。
- 止损在策略内部模拟,当价格突破止损时发送市价单平仓,无需额外挂单。
- 入场和出场都会写入日志,方便监控运行状态,并贴近原始专家顾问的详细输出。
使用建议
- 将策略添加到 StockSharp 应用中,选择交易品种和投资组合,并配置所需的蜡烛序列。
- 根据标的波动性调整 RSI 阈值、确认蜡烛数量以及止损步长。
- 启动策略,观察日志了解信号触发和止损移动情况。
- 如需进一步优化,可使用 StockSharp 优化器搜索不同参数组合。
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>
/// Contrarian RSI strategy converted from the "Trade on qualified RSI" expert advisor.
/// </summary>
public class TradeOnQualifiedRSIStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<decimal> _upperThreshold;
private readonly StrategyParam<decimal> _lowerThreshold;
private readonly StrategyParam<int> _countBars;
private readonly StrategyParam<int> _stopLossPoints;
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<DataType> _candleType;
private RelativeStrengthIndex _rsi;
private decimal? _stopPrice;
private decimal _entryPrice;
private int _aboveCounter;
private int _belowCounter;
/// <summary>
/// RSI lookback period.
/// </summary>
public int RsiPeriod
{
get => _rsiPeriod.Value;
set => _rsiPeriod.Value = value;
}
/// <summary>
/// Upper RSI threshold used to qualify short entries.
/// </summary>
public decimal UpperThreshold
{
get => _upperThreshold.Value;
set => _upperThreshold.Value = value;
}
/// <summary>
/// Lower RSI threshold used to qualify long entries.
/// </summary>
public decimal LowerThreshold
{
get => _lowerThreshold.Value;
set => _lowerThreshold.Value = value;
}
/// <summary>
/// Number of previous RSI bars that must stay beyond the threshold.
/// </summary>
public int CountBars
{
get => _countBars.Value;
set => _countBars.Value = value;
}
/// <summary>
/// Stop-loss distance in price steps.
/// </summary>
public int StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Order volume used for entries.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set => _tradeVolume.Value = value;
}
/// <summary>
/// Candle type used as the RSI data source.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize <see cref="TradeOnQualifiedRSIStrategy"/>.
/// </summary>
public TradeOnQualifiedRSIStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 28)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "Lookback period for RSI calculation.", "RSI")
.SetOptimize(10, 50, 2);
_upperThreshold = Param(nameof(UpperThreshold), 65m)
.SetDisplay("Upper Threshold", "RSI level used to qualify short signals.", "RSI")
.SetOptimize(50m, 70m, 1m);
_lowerThreshold = Param(nameof(LowerThreshold), 35m)
.SetDisplay("Lower Threshold", "RSI level used to qualify long signals.", "RSI")
.SetOptimize(30m, 50m, 1m);
_countBars = Param(nameof(CountBars), 8)
.SetGreaterThanZero()
.SetDisplay("Qualification Bars", "How many previous RSI bars must stay beyond the threshold.", "Signals")
.SetOptimize(1, 10, 1);
_stopLossPoints = Param(nameof(StopLossPoints), 1000)
.SetGreaterThanZero()
.SetDisplay("Stop Loss Points", "Stop loss distance expressed in price steps.", "Risk")
.SetOptimize(5, 50, 5);
_tradeVolume = Param(nameof(TradeVolume), 1m)
.SetGreaterThanZero()
.SetDisplay("Trade Volume", "Order volume used for entries.", "Trading");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Source timeframe for RSI calculation.", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
Volume = TradeVolume;
_stopPrice = null;
_entryPrice = 0m;
_aboveCounter = 0;
_belowCounter = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
Volume = TradeVolume;
_rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_rsi, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _rsi);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue)
{
if (candle.State != CandleStates.Finished)
return;
if (_rsi == null || !_rsi.IsFormed)
{
_aboveCounter = 0;
_belowCounter = 0;
return;
}
if (Volume <= 0)
return;
var distance = CalculateStopDistance();
if (distance <= 0)
return;
UpdateCounters(rsiValue);
var requiredBars = CountBars + 1;
if (Position == 0)
{
_stopPrice = null;
_entryPrice = 0m;
var shortSignal = rsiValue >= UpperThreshold && _aboveCounter >= requiredBars;
var longSignal = rsiValue <= LowerThreshold && _belowCounter >= requiredBars;
if (shortSignal)
{
this.LogInfo($"Open short: RSI={rsiValue:F2}, counter={_aboveCounter}");
SellMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = candle.ClosePrice + distance;
return;
}
if (longSignal)
{
this.LogInfo($"Open long: RSI={rsiValue:F2}, counter={_belowCounter}");
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopPrice = candle.ClosePrice - distance;
}
return;
}
if (Position > 0)
{
if (_stopPrice == null)
_stopPrice = _entryPrice - distance;
var newStop = candle.ClosePrice - distance;
if (_stopPrice == null || newStop > _stopPrice)
_stopPrice = newStop;
if (_stopPrice != null && candle.LowPrice <= _stopPrice)
{
this.LogInfo($"Exit long via stop at {_stopPrice:F5}");
SellMarket();
_stopPrice = null;
_entryPrice = 0m;
}
return;
}
if (Position < 0)
{
if (_stopPrice == null)
_stopPrice = _entryPrice + distance;
var newStop = candle.ClosePrice + distance;
if (_stopPrice == null || newStop < _stopPrice)
_stopPrice = newStop;
if (_stopPrice != null && candle.HighPrice >= _stopPrice)
{
this.LogInfo($"Exit short via stop at {_stopPrice:F5}");
BuyMarket();
_stopPrice = null;
_entryPrice = 0m;
}
}
}
private decimal CalculateStopDistance()
{
var step = Security?.PriceStep ?? 1m;
if (step <= 0)
step = 1m;
return StopLossPoints * step;
}
private void UpdateCounters(decimal rsiValue)
{
// Track consecutive closes above and below the thresholds.
if (rsiValue >= UpperThreshold)
{
_aboveCounter++;
}
else
{
_aboveCounter = 0;
}
if (rsiValue <= LowerThreshold)
{
_belowCounter++;
}
else
{
_belowCounter = 0;
}
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class trade_on_qualified_rsi_strategy(Strategy):
def __init__(self):
super(trade_on_qualified_rsi_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 28)
self._upper_threshold = self.Param("UpperThreshold", 65.0)
self._lower_threshold = self.Param("LowerThreshold", 35.0)
self._count_bars = self.Param("CountBars", 8)
self._stop_loss_points = self.Param("StopLossPoints", 1000)
self._trade_volume = self.Param("TradeVolume", 1.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4)))
self._stop_price = None
self._entry_price = 0.0
self._above_counter = 0
self._below_counter = 0
@property
def RsiPeriod(self):
return self._rsi_period.Value
@RsiPeriod.setter
def RsiPeriod(self, value):
self._rsi_period.Value = value
@property
def UpperThreshold(self):
return self._upper_threshold.Value
@UpperThreshold.setter
def UpperThreshold(self, value):
self._upper_threshold.Value = value
@property
def LowerThreshold(self):
return self._lower_threshold.Value
@LowerThreshold.setter
def LowerThreshold(self, value):
self._lower_threshold.Value = value
@property
def CountBars(self):
return self._count_bars.Value
@CountBars.setter
def CountBars(self, value):
self._count_bars.Value = value
@property
def StopLossPoints(self):
return self._stop_loss_points.Value
@StopLossPoints.setter
def StopLossPoints(self, value):
self._stop_loss_points.Value = value
@property
def TradeVolume(self):
return self._trade_volume.Value
@TradeVolume.setter
def TradeVolume(self, value):
self._trade_volume.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def _calculate_stop_distance(self):
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
if step <= 0.0:
step = 1.0
return int(self.StopLossPoints) * step
def OnStarted2(self, time):
super(trade_on_qualified_rsi_strategy, self).OnStarted2(time)
self._rsi = RelativeStrengthIndex()
self._rsi.Length = self.RsiPeriod
self._stop_price = None
self._entry_price = 0.0
self._above_counter = 0
self._below_counter = 0
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._rsi, self.ProcessCandle).Start()
def ProcessCandle(self, candle, rsi_value):
if candle.State != CandleStates.Finished:
return
rsi_val = float(rsi_value)
if not self._rsi.IsFormed:
self._above_counter = 0
self._below_counter = 0
return
distance = self._calculate_stop_distance()
if distance <= 0.0:
return
self._update_counters(rsi_val)
required_bars = int(self.CountBars) + 1
upper = float(self.UpperThreshold)
lower = float(self.LowerThreshold)
close = float(candle.ClosePrice)
if self.Position == 0:
self._stop_price = None
self._entry_price = 0.0
short_signal = rsi_val >= upper and self._above_counter >= required_bars
long_signal = rsi_val <= lower and self._below_counter >= required_bars
if short_signal:
self.SellMarket()
self._entry_price = close
self._stop_price = close + distance
return
if long_signal:
self.BuyMarket()
self._entry_price = close
self._stop_price = close - distance
return
if self.Position > 0:
if self._stop_price is None:
self._stop_price = self._entry_price - distance
new_stop = close - distance
if self._stop_price is None or new_stop > self._stop_price:
self._stop_price = new_stop
if self._stop_price is not None and float(candle.LowPrice) <= self._stop_price:
self.SellMarket()
self._stop_price = None
self._entry_price = 0.0
return
if self.Position < 0:
if self._stop_price is None:
self._stop_price = self._entry_price + distance
new_stop = close + distance
if self._stop_price is None or new_stop < self._stop_price:
self._stop_price = new_stop
if self._stop_price is not None and float(candle.HighPrice) >= self._stop_price:
self.BuyMarket()
self._stop_price = None
self._entry_price = 0.0
def _update_counters(self, rsi_val):
upper = float(self.UpperThreshold)
lower = float(self.LowerThreshold)
if rsi_val >= upper:
self._above_counter += 1
else:
self._above_counter = 0
if rsi_val <= lower:
self._below_counter += 1
else:
self._below_counter = 0
def OnReseted(self):
super(trade_on_qualified_rsi_strategy, self).OnReseted()
self._stop_price = None
self._entry_price = 0.0
self._above_counter = 0
self._below_counter = 0
def CreateClone(self):
return trade_on_qualified_rsi_strategy()