Ver no GitHub

Parabolic SAR Multitemporal

Parabolic SAR Multitemporal usa quatro indicadores Parabolic SAR diferentes de períodos superiores para confirmar uma tendência antes de entrar em uma operação. A estratégia processa velas de 15 minutos e verifica o estado do SAR em gráficos de 30 minutos, 1 hora e 4 horas. Uma posição comprada só é aberta quando o preço está acima de todos os valores SAR; uma posição vendida é aberta quando o preço está abaixo de todos os SARs.

O método tenta filtrar o ruído exigindo alinhamento em múltiplos períodos. A posição é fechada quando a condição oposta aparece.

Detalhes

  • Critérios de entrada: Preço relativo ao Parabolic SAR nos períodos 15m/30m/1h/4h.
  • Comprado/Vendido: Ambas as direções.
  • Critérios de saída: Sinal oposto de todos os indicadores SAR.
  • Stops: Usa StartProtection para proteção básica, sem valores de stop explícitos.
  • Valores padrão:
    • Step15 = 0.062
    • Step30 = 0.058
    • Step60 = 0.058
    • Step240 = 0.058
    • MaxStep = 0.1
  • Filtros:
    • Categoria: Tendência
    • Direção: Ambos
    • Indicadores: Parabolic SAR
    • Stops: Não
    • Complexidade: Intermediário
    • Período: Intradiário (base 15m com confirmações superiores)
    • Sazonalidade: Não
    • Redes neurais: Não
    • Divergência: Não
    • Nível de risco: Médio

Uso

  1. Anexe a estratégia a um instrumento.
  2. Ajuste os parâmetros de passo do SAR se necessário.
  3. Inicie a estratégia; ela se inscreverá automaticamente em velas de 15m, 30m, 1h e 4h.
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>
/// Parabolic SAR trend-following strategy with EMA confirmation.
/// </summary>
public class ParabolicSarMultiTimeframeStrategy : Strategy
{
	private readonly StrategyParam<decimal> _sarAcceleration;
	private readonly StrategyParam<decimal> _sarMaxAcceleration;
	private readonly StrategyParam<int> _emaLength;
	private readonly StrategyParam<DataType> _candleType;

	public decimal SarAcceleration { get => _sarAcceleration.Value; set => _sarAcceleration.Value = value; }
	public decimal SarMaxAcceleration { get => _sarMaxAcceleration.Value; set => _sarMaxAcceleration.Value = value; }
	public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public ParabolicSarMultiTimeframeStrategy()
	{
		_sarAcceleration = Param(nameof(SarAcceleration), 0.02m)
			.SetDisplay("SAR Accel", "SAR acceleration factor", "Indicators");

		_sarMaxAcceleration = Param(nameof(SarMaxAcceleration), 0.2m)
			.SetDisplay("SAR Max", "SAR max acceleration", "Indicators");

		_emaLength = Param(nameof(EmaLength), 50)
			.SetGreaterThanZero()
			.SetDisplay("EMA Length", "EMA trend filter period", "Indicators");

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

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

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

		var sar = new ParabolicSar { Acceleration = SarAcceleration, AccelerationMax = SarMaxAcceleration };
		var ema = new ExponentialMovingAverage { Length = EmaLength };

		var subscription = SubscribeCandles(CandleType);
		subscription.Bind(sar, ema, ProcessCandle).Start();

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

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

		var price = candle.ClosePrice;

		// Buy when price is above both SAR and EMA
		if (price > sarValue && price > emaValue && Position <= 0)
			BuyMarket();
		// Sell when price is below both SAR and EMA
		else if (price < sarValue && price < emaValue && Position >= 0)
			SellMarket();

		// Exit on SAR flip
		if (Position > 0 && price < sarValue)
			SellMarket();
		else if (Position < 0 && price > sarValue)
			BuyMarket();
	}
}