在 GitHub 上查看

Trade on Qualified RSI 策略

概述

该策略将 MetaTrader 的 "Trade on qualified RSI" 专家顾问迁移到 StockSharp 高级 API。它是一种逆势策略:当 RSI 长时间停留在极端区域时,算法将其视为动能耗尽的信号,并在获得多根蜡烛确认后,向相反方向开仓。止损按价格最小变动单位(PriceStep)进行跟踪,只在价格向有利方向移动时上调或下调。

信号逻辑

指标

  • 可配置周期的相对强弱指标(RSI),默认长度为 28。
  • 基于所选蜡烛序列计算,默认使用 15 分钟蜡烛。

做空条件

  1. 最近一根已收盘的蜡烛 RSI 大于或等于上限阈值(默认 55)。
  2. 在此之前的 CountBars 根蜡烛 RSI 也全部高于该阈值。策略内部维护一个连续计数器,当计数达到 CountBars + 1 时触发信号。
  3. 当前没有持仓。满足条件后,以设定的交易量市价卖出,并将收盘价记录为入场价。

做多条件

  1. 最近一根已收盘的蜡烛 RSI 小于或等于下限阈值(默认 45)。
  2. 在此之前的 CountBars 根蜡烛 RSI 也全部低于该阈值(同样需要连续 CountBars + 1 根满足条件)。
  3. 当前没有持仓。满足条件后,以设定的交易量市价买入,并记录收盘价。

仓位管理

  • 初始止损: 开仓后立即将止损设置在距离入场价 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 历史值,而是使用连续计数器来验证阈值条件。
  • 止损在策略内部模拟,当价格突破止损时发送市价单平仓,无需额外挂单。
  • 入场和出场都会写入日志,方便监控运行状态,并贴近原始专家顾问的详细输出。

使用建议

  1. 将策略添加到 StockSharp 应用中,选择交易品种和投资组合,并配置所需的蜡烛序列。
  2. 根据标的波动性调整 RSI 阈值、确认蜡烛数量以及止损步长。
  3. 启动策略,观察日志了解信号触发和止损移动情况。
  4. 如需进一步优化,可使用 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;
		}
	}
}