Ver no GitHub

Estratégia Color Zerolag JJRSX

Esta estratégia replica a lógica do especialista ColorZerolagJJRSX do MetaTrader. Utiliza dois osciladores RSI suavizados para aproximar o indicador ColorZerolagJJRSX original. O cruzamento das linhas rápida e lenta gera sinais de negociação.

Como funciona

  • Quando o oscilador rápido cruza abaixo do oscilador lento, a estratégia fecha qualquer posição vendida e opcionalmente abre uma nova posição comprada.
  • Quando o oscilador rápido cruza acima do oscilador lento, a estratégia fecha qualquer posição comprada e opcionalmente abre uma nova posição vendida.
  • Níveis de stop-loss e take-profit de proteção são aplicados usando o mecanismo integrado StartProtection.

Parâmetros

Nome Descrição
FastPeriod Período da linha JJRSX rápida.
SlowPeriod Período da linha JJRSX lenta.
BuyOpen Permitir abertura de posições compradas.
SellOpen Permitir abertura de posições vendidas.
BuyClose Fechar posições compradas existentes no sinal oposto.
SellClose Fechar posições vendidas existentes no sinal oposto.
StopLoss Nível de stop-loss em unidades de preço.
TakeProfit Nível de take-profit em unidades de preço.
CandleType Período utilizado para os cálculos.

Notas

  • A implementação usa indicadores integrados e a API Bind de alto nível.
  • O volume é obtido da propriedade Volume da estratégia.
  • Não há versão em Python para esta estratégia.

Referências

O código-fonte MQL original está localizado em MQL/13854 neste repositório.

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 crossing of two RSI lines (fast and slow).
/// </summary>
public class ColorZerolagJjrsxStrategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<decimal> _stopLossPct;
	private readonly StrategyParam<decimal> _takeProfitPct;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevFast;
	private decimal? _prevSlow;

	public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
	public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
	public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
	public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ColorZerolagJjrsxStrategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 8)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast RSI period", "Indicator");

		_slowPeriod = Param(nameof(SlowPeriod), 21)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow RSI period", "Indicator");

		_stopLossPct = Param(nameof(StopLossPct), 2m)
			.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk");

		_takeProfitPct = Param(nameof(TakeProfitPct), 3m)
			.SetDisplay("Take Profit %", "Take profit percentage", "Risk");

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Time frame for indicator", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
	{
		return [(Security, CandleType)];
	}

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevFast = null;
		_prevSlow = null;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		var fastRsi = new RelativeStrengthIndex { Length = FastPeriod };
		var slowRsi = new RelativeStrengthIndex { Length = SlowPeriod };

		StartProtection(
			takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent),
			stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
			useMarketOrders: true);

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(fastRsi, slowRsi, ProcessCandle)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawIndicator(area, fastRsi);
			DrawIndicator(area, slowRsi);
			DrawOwnTrades(area);
		}
	}

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

		if (_prevFast is null || _prevSlow is null)
		{
			_prevFast = fast;
			_prevSlow = slow;
			return;
		}

		var crossDown = _prevFast > _prevSlow && fast < slow;
		var crossUp = _prevFast < _prevSlow && fast > slow;

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

		_prevFast = fast;
		_prevSlow = slow;
	}
}