Estrategia RSI
Estrategia simple basada en el Índice de Fuerza Relativa. Compra cuando el RSI cruza por encima del nivel de sobreventa y vende cuando cruza por debajo del nivel de sobrecompra.
Detalles
- Criterios de entrada:
- Largo: RSI cruza por encima de
OverSold - Corto: RSI cruza por debajo de
OverBought
- Largo: RSI cruza por encima de
- Largo/Corto: Ambos
- Criterios de salida:
- Señal opuesta
- Stops: No
- Valores predeterminados:
RsiLength= 14OverSold= 25mOverBought= 75mCandleType= TimeSpan.FromMinutes(5).TimeFrame()
- Filtros:
- Categoría: Oscilador
- Dirección: Ambos
- Indicadores: RSI
- Stops: No
- Complejidad: Básico
- Marco temporal: Intradía
- Estacionalidad: No
- Redes neuronales: No
- Divergencia: No
- Nivel de riesgo: Bajo
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 threshold-cross reversal strategy.
/// </summary>
public class RsiStrategy : Strategy
{
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<decimal> _overSold;
private readonly StrategyParam<decimal> _overBought;
private readonly StrategyParam<DataType> _candleType;
private RelativeStrengthIndex _rsi;
private decimal? _previousRsi;
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public decimal OverSold { get => _overSold.Value; set => _overSold.Value = value; }
public decimal OverBought { get => _overBought.Value; set => _overBought.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public RsiStrategy()
{
_rsiLength = Param(nameof(RsiLength), 14).SetGreaterThanZero();
_overSold = Param(nameof(OverSold), 25m);
_overBought = Param(nameof(OverBought), 75m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame());
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_rsi = null;
_previousRsi = null;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_rsi = new RelativeStrengthIndex { Length = RsiLength };
SubscribeCandles(CandleType)
.Bind(_rsi, (candle, value) =>
{
if (candle.State != CandleStates.Finished || !_rsi.IsFormed)
return;
if (_previousRsi is decimal previous)
ApplySignal(GetSignal(previous, value, OverSold, OverBought));
_previousRsi = value;
})
.Start();
}
private void ApplySignal(int signal)
{
if (signal > 0 && Position <= 0m)
BuyMarket(Volume + Math.Abs(Position));
else if (signal < 0 && Position >= 0m)
SellMarket(Volume + Math.Abs(Position));
}
internal static int GetSignal(decimal previous, decimal current, decimal overSold, decimal overBought)
{
if (previous <= overSold && current > overSold)
return 1;
if (previous >= overBought && current < overBought)
return -1;
return 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
from StockSharp.Algo.Indicators import RelativeStrengthIndex
from StockSharp.Algo.Strategies import Strategy
class rsi_strategy(Strategy):
def __init__(self):
super(rsi_strategy, self).__init__()
self._rsi_length = self.Param("RsiLength", 14).SetGreaterThanZero()
self._over_sold = self.Param("OverSold", 25.0)
self._over_bought = self.Param("OverBought", 75.0)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5)))
self._rsi = None
self._previous_rsi = None
def GetWorkingSecurities(self):
return [(self.Security, self._candle_type.Value)]
def OnReseted(self):
super(rsi_strategy, self).OnReseted()
self._rsi = None
self._previous_rsi = None
def OnStarted2(self, time):
super(rsi_strategy, self).OnStarted2(time)
self._rsi = RelativeStrengthIndex()
self._rsi.Length = int(self._rsi_length.Value)
def on_candle(candle, value):
if candle.State != CandleStates.Finished or not self._rsi.IsFormed:
return
current = float(value)
if self._previous_rsi is not None:
signal = self.get_signal(
self._previous_rsi, current,
float(self._over_sold.Value), float(self._over_bought.Value))
if signal > 0 and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif signal < 0 and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
self._previous_rsi = current
self.SubscribeCandles(self._candle_type.Value).Bind(self._rsi, on_candle).Start()
@staticmethod
def get_signal(previous, current, over_sold, over_bought):
if previous <= over_sold and current > over_sold:
return 1
if previous >= over_bought and current < over_bought:
return -1
return 0
def CreateClone(self):
return rsi_strategy()