在 GitHub 上查看

RSI Value

基于相对强弱指数(RSI)中线交叉的交易策略。

当RSI从下向上穿越设定水平(默认50)时开多单;当RSI从上向下穿越该水平时开空单。相反的交叉用于平仓。可选的止损、止盈和追踪止损用于风险控制。

细节

  • 入场条件:RSI上穿水平买入,下穿卖出。
  • 多空方向:双向。
  • 出场条件:反向交叉或触发追踪止损。
  • 止损:可选固定止损、止盈和追踪止损。
  • 默认值
    • RsiPeriod = 14
    • RsiLevel = 50
    • StopLoss = 100
    • TakeProfit = 200
    • TrailingStop = 0
    • CandleType = TimeSpan.FromMinutes(5)
  • 过滤器
    • 分类:振荡器
    • 方向:双向
    • 指标:RSI
    • 止损:有
    • 复杂度:基础
    • 时间框架:日内 (5分钟)
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险级别:中等
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 level crossing strategy.
/// </summary>
public class RsiValueStrategy : Strategy
{
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _rsiLevel;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevRsi;
	private bool _hasPrev;

	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public decimal RsiLevel { get => _rsiLevel.Value; set => _rsiLevel.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public RsiValueStrategy()
	{
		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "RSI period", "Indicators");
		_rsiLevel = Param(nameof(RsiLevel), 50m)
			.SetDisplay("RSI Level", "RSI crossing level", "Indicators");
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Candle type", "General");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevRsi = 0;
		_hasPrev = false;
	}

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

		var rsi = new RelativeStrengthIndex { Length = RsiPeriod };

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

	private void ProcessCandle(ICandleMessage candle, decimal rsiVal)
	{
		if (candle.State != CandleStates.Finished) return;

		if (!_hasPrev)
		{
			_prevRsi = rsiVal;
			_hasPrev = true;
			return;
		}

		var crossUp = _prevRsi <= RsiLevel && rsiVal > RsiLevel;
		var crossDown = _prevRsi >= RsiLevel && rsiVal < RsiLevel;

		if (crossUp && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (crossDown && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevRsi = rsiVal;
	}
}