Ver no GitHub

Estratégia RSI Trader V1

Esta estratégia usa o Índice de Força Relativa (RSI) para identificar reversões após extremos de curto prazo. Um sinal de compra ocorre quando o RSI cruza acima do limiar de sobrevenda após permanecer abaixo dele por dois candles consecutivos. Um sinal de venda ocorre quando o RSI cruza abaixo do limiar de sobrecompra após permanecer acima dele por dois candles. A estratégia opcionalmente fecha uma posição oposta existente e opera apenas dentro de uma janela de tempo configurável.

Detalhes

  • Critérios de entrada:
    • Comprado: RSI > BuyPoint e o RSI dos dois candles anteriores < BuyPoint.
    • Vendido: RSI < SellPoint e o RSI dos dois candles anteriores > SellPoint.
  • Critérios de saída: Sinal oposto ou stop/take-profit de proteção.
  • Filtro de tempo: Opera apenas quando a hora de abertura do candle está entre StartHour e EndHour.
  • Stops: Take profit e stop loss fixos expressos em unidades de preço.
  • Parâmetros:
    • RsiPeriod – período de cálculo do RSI.
    • BuyPoint – nível de sobrevenda para entradas compradas.
    • SellPoint – nível de sobrecompra para entradas vendidas.
    • CloseOnOpposite – fechar a posição atual quando aparecer um sinal oposto.
    • StartHour / EndHour – horas de negociação.
    • TakeProfit / StopLoss – níveis de proteção em preço.

Este exemplo demonstra um sistema minimalista de cruzamento RSI construído com a API de alto nível do StockSharp. Pode ser usado como modelo para experimentação adicional.

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-based trading strategy.
/// Buys when RSI crosses above BuyPoint, sells when RSI crosses below SellPoint.
/// </summary>
public class RsiTraderV1Strategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _rsiPeriod;
	private readonly StrategyParam<decimal> _buyPoint;
	private readonly StrategyParam<decimal> _sellPoint;

	private decimal _prevRsi;
	private decimal _prevPrevRsi;
	private bool _hasPrev;
	private bool _hasPrevPrev;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
	public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
	public decimal BuyPoint { get => _buyPoint.Value; set => _buyPoint.Value = value; }
	public decimal SellPoint { get => _sellPoint.Value; set => _sellPoint.Value = value; }

	public RsiTraderV1Strategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");

		_rsiPeriod = Param(nameof(RsiPeriod), 14)
			.SetGreaterThanZero()
			.SetDisplay("RSI Period", "Calculation period", "RSI");

		_buyPoint = Param(nameof(BuyPoint), 30m)
			.SetDisplay("Buy Threshold", "RSI level for long entry", "RSI");

		_sellPoint = Param(nameof(SellPoint), 70m)
			.SetDisplay("Sell Threshold", "RSI level for short entry", "RSI");
	}

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

	protected override void OnReseted()
	{
		base.OnReseted();
		_prevRsi = 0;
		_prevPrevRsi = 0;
		_hasPrev = false;
		_hasPrevPrev = 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 rsiValue)
	{
		if (candle.State != CandleStates.Finished) return;

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

		if (!_hasPrevPrev)
		{
			_prevPrevRsi = _prevRsi;
			_prevRsi = rsiValue;
			_hasPrevPrev = true;
			return;
		}

		var longSignal = rsiValue > BuyPoint && _prevRsi < BuyPoint && _prevPrevRsi < BuyPoint;
		var shortSignal = rsiValue < SellPoint && _prevRsi > SellPoint && _prevPrevRsi > SellPoint;

		if (longSignal && Position <= 0)
		{
			if (Position < 0) BuyMarket();
			BuyMarket();
		}
		else if (shortSignal && Position >= 0)
		{
			if (Position > 0) SellMarket();
			SellMarket();
		}

		_prevPrevRsi = _prevRsi;
		_prevRsi = rsiValue;
	}
}