在 GitHub 上查看

RSI 趋势策略

RSI 趋势策略 使用相对强弱指数 (RSI) 判断趋势反转,并通过基于 ATR 的跟踪止损管理风险。当 RSI 向上突破超买阈值时,策略建立多头头寸;当 RSI 向下跌破超卖阈值时,策略建立空头头寸。跟踪止损基于平均真实波幅 (ATR) 的倍数动态调整,以适应市场波动。

此实现展示了如何使用 StockSharp 的高级 API 创建策略,通过绑定指标获取数据,仅处理收盘完成的蜡烛,并避免直接访问历史指标值。

细节

  • 入场条件
    • 多头RSI(t) > BuyLevelRSI(t-1) <= BuyLevel
    • 空头RSI(t) < SellLevelRSI(t-1) >= SellLevel
  • 方向:双向。
  • 出场条件
    • 基于 ATR 倍数的跟踪止损。
  • 止损:是,动态跟踪。
  • 默认参数
    • RSI Period = 14。
    • BuyLevel = 73。
    • SellLevel = 27。
    • ATR Period = 100。
    • ATR Multiple = 3。
  • 过滤器
    • 类别:趋势跟随。
    • 方向:双向。
    • 指标:RSI、ATR。
    • 止损:是。
    • 复杂度:中等。
    • 时间框架:任意(默认 1 分钟蜡烛)。
    • 季节性:否。
    • 神经网络:否。
    • 背离:否。
    • 风险等级:中等。
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>
/// RSI trend strategy with StdDev trailing stop.
/// </summary>
public class RsiTrendStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _rsiBuyLevel;
	private readonly StrategyParam<decimal> _rsiSellLevel;
	private readonly StrategyParam<int> _stdevPeriod;
	private readonly StrategyParam<decimal> _stdevMultiple;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _previousRsi;
	private bool _isRsiInitialized;
	private decimal _stopPrice;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public decimal RsiBuyLevel { get => _rsiBuyLevel.Value; set => _rsiBuyLevel.Value = value; }
	public decimal RsiSellLevel { get => _rsiSellLevel.Value; set => _rsiSellLevel.Value = value; }
	public int StdevPeriod { get => _stdevPeriod.Value; set => _stdevPeriod.Value = value; }
	public decimal StdevMultiple { get => _stdevMultiple.Value; set => _stdevMultiple.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public RsiTrendStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "Period for RSI calculation", "RSI Settings");

		_rsiBuyLevel = Param(nameof(RsiBuyLevel), 60m)
			.SetDisplay("RSI Buy Level", "Upper RSI barrier for long entries", "RSI Settings");

		_rsiSellLevel = Param(nameof(RsiSellLevel), 40m)
			.SetDisplay("RSI Sell Level", "Lower RSI barrier for short entries", "RSI Settings");

		_stdevPeriod = Param(nameof(StdevPeriod), 20)
			.SetGreaterThanZero()
			.SetDisplay("StdDev Period", "StdDev period for trailing stop", "Settings");

		_stdevMultiple = Param(nameof(StdevMultiple), 2m)
			.SetGreaterThanZero()
			.SetDisplay("StdDev Multiple", "StdDev multiplier for trailing stop", "Settings");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles for processing", "General");
	}

	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	protected override void OnReseted()
	{
		base.OnReseted();
		_previousRsi = 0;
		_isRsiInitialized = false;
		_stopPrice = 0;
	}

	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
		var stdev = new StandardDeviation { Length = StdevPeriod };

		SubscribeCandles(CandleType)
			.Bind(rsi, stdev, ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle, decimal rsiValue, decimal stdevValue)
	{
		if (candle.State != CandleStates.Finished) return;
		if (stdevValue <= 0) return;

		if (!_isRsiInitialized)
		{
			_previousRsi = rsiValue;
			_isRsiInitialized = true;
			return;
		}

		var bullish = rsiValue > RsiBuyLevel && _previousRsi <= RsiBuyLevel;
		var bearish = rsiValue < RsiSellLevel && _previousRsi >= RsiSellLevel;

		if (bullish && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
			_stopPrice = candle.ClosePrice - stdevValue * StdevMultiple;
		}
		else if (bearish && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
			_stopPrice = candle.ClosePrice + stdevValue * StdevMultiple;
		}

		if (Position > 0)
		{
			var newStop = candle.ClosePrice - stdevValue * StdevMultiple;
			if (newStop > _stopPrice) _stopPrice = newStop;
			if (candle.ClosePrice <= _stopPrice) SellMarket();
		}
		else if (Position < 0)
		{
			var newStop = candle.ClosePrice + stdevValue * StdevMultiple;
			if (newStop < _stopPrice) _stopPrice = newStop;
			if (candle.ClosePrice >= _stopPrice) BuyMarket();
		}

		_previousRsi = rsiValue;
	}
}