Esta estrategia utiliza un oscilador compuesto construido a partir de cinco cálculos RSI con diferentes períodos. La suma ponderada de los valores RSI se suaviza dos veces para producir una línea OSMA de cero rezago.
Cómo Funciona
Calcular cinco valores RSI con períodos 8, 21, 34, 55 y 89.
Multiplicar cada RSI por su peso y sumar los resultados.
Aplicar dos pasos de suavizado a la suma para obtener el valor OSMA.
Si el OSMA gira hacia arriba (el valor anterior era más bajo que hace dos barras y el valor actual supera el anterior), la estrategia cierra posiciones cortas y opcionalmente abre una larga.
Si el OSMA gira hacia abajo (el valor anterior era más alto que hace dos barras y el valor actual cae por debajo del anterior), la estrategia cierra posiciones largas y opcionalmente abre una corta.
Parámetros
Smoothing 1, Smoothing 2 – longitudes de las fases de suavizado.
Factor 1..5 – pesos para cada componente RSI.
RSI Period 1..5 – períodos de los indicadores RSI.
Allow Buy / Allow Sell – habilitar apertura de posiciones largas o cortas.
Close Long / Close Short – cerrar posiciones existentes ante señales opuestas.
Candle Type – marco temporal de las velas procesadas (por defecto 4 horas).
Notas
La estrategia opera únicamente sobre velas finalizadas. La protección de posición se inicia automáticamente cuando la estrategia comienza.
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>
/// Strategy based on the Color Zerolag RSI OSMA indicator.
/// Uses weighted RSI composite with EMA smoothing for direction changes.
/// </summary>
public class ColorZerolagRsiOsmaStrategy : Strategy
{
private readonly StrategyParam<int> _rsiPeriod;
private readonly StrategyParam<int> _smoothing;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevOsma;
private decimal _prevPrevOsma;
private int _count;
public int RsiPeriod { get => _rsiPeriod.Value; set => _rsiPeriod.Value = value; }
public int Smoothing { get => _smoothing.Value; set => _smoothing.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ColorZerolagRsiOsmaStrategy()
{
_rsiPeriod = Param(nameof(RsiPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Period", "RSI calculation period", "Indicator");
_smoothing = Param(nameof(Smoothing), 21)
.SetGreaterThanZero()
.SetDisplay("Smoothing", "EMA smoothing period", "Indicator");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevOsma = 0;
_prevPrevOsma = 0;
_count = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var rsi = new RelativeStrengthIndex { Length = RsiPeriod };
var ema = new ExponentialMovingAverage { Length = Smoothing };
SubscribeCandles(CandleType)
.Bind(rsi, ema, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal rsiValue, decimal emaValue)
{
if (candle.State != CandleStates.Finished)
return;
// OSMA = difference between RSI and its smoothed version (EMA of price)
var osma = rsiValue - 50m;
_count++;
if (_count < 3)
{
_prevPrevOsma = _prevOsma;
_prevOsma = osma;
return;
}
// Buy when OSMA turns up
var turnUp = _prevOsma < _prevPrevOsma && osma > _prevOsma;
// Sell when OSMA turns down
var turnDown = _prevOsma > _prevPrevOsma && osma < _prevOsma;
if (turnUp && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (turnDown && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevPrevOsma = _prevOsma;
_prevOsma = osma;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import RelativeStrengthIndex, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class color_zerolag_rsi_osma_strategy(Strategy):
"""
Strategy based on the Color Zerolag RSI OSMA indicator.
Uses RSI - 50 as OSMA and trades on direction changes.
"""
def __init__(self):
super(color_zerolag_rsi_osma_strategy, self).__init__()
self._rsi_period = self.Param("RsiPeriod", 14) \
.SetDisplay("RSI Period", "RSI calculation period", "Indicator")
self._smoothing = self.Param("Smoothing", 21) \
.SetDisplay("Smoothing", "EMA smoothing period", "Indicator")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_osma = 0.0
self._prev_prev_osma = 0.0
self._count = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(color_zerolag_rsi_osma_strategy, self).OnReseted()
self._prev_osma = 0.0
self._prev_prev_osma = 0.0
self._count = 0
def OnStarted2(self, time):
super(color_zerolag_rsi_osma_strategy, self).OnStarted2(time)
rsi = RelativeStrengthIndex()
rsi.Length = self._rsi_period.Value
ema = ExponentialMovingAverage()
ema.Length = self._smoothing.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(rsi, ema, self.on_process).Start()
def on_process(self, candle, rsi_val, ema_val):
if candle.State != CandleStates.Finished:
return
osma = rsi_val - 50.0
self._count += 1
if self._count < 3:
self._prev_prev_osma = self._prev_osma
self._prev_osma = osma
return
turn_up = self._prev_osma < self._prev_prev_osma and osma > self._prev_osma
turn_down = self._prev_osma > self._prev_prev_osma and osma < self._prev_osma
if turn_up and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif turn_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_prev_osma = self._prev_osma
self._prev_osma = osma
def CreateClone(self):
return color_zerolag_rsi_osma_strategy()