Ver en GitHub

Estrategia de Cuatro Pantallas

La estrategia de Cuatro Pantallas opera usando velas Heikin-Ashi en cuatro marcos temporales: 5, 15, 30 y 60 minutos. Entra en largo cuando todos los marcos temporales muestran velas alcistas y entra en corto cuando todos muestran velas bajistas. Los niveles de stop-loss y take-profit se establecen en puntos con un trailing stop opcional.

Cómo funciona

  1. Se suscribe a flujos de velas de 5, 15, 30 y 60 minutos.
  2. Calcula la apertura y cierre Heikin-Ashi para cada vela.
  3. Marca cada marco temporal como alcista o bajista.
  4. Entra en largo cuando todos son alcistas, entra en corto cuando todos son bajistas.
  5. Usa StartProtection para aplicar stop-loss, take-profit y trailing opcional.

Parámetros

  • CandleType – marco temporal base para velas de 5 minutos.
  • StopLossPoints – distancia del stop-loss en puntos.
  • TakeProfitPoints – distancia del take-profit en puntos.
  • UseTrailing – habilitar trailing stop (true/false).

El volumen de operaciones lo define la propiedad Volume de la estrategia.

Notas

  • Funciona con la API de alto nivel usando SubscribeCandles y Bind.
  • Solo procesa velas finalizadas.
  • Los comentarios en el código están en inglés.
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 using Heikin-Ashi color with EMA filter.
/// Buys when HA turns bullish and price above EMA.
/// Sells when HA turns bearish and price below EMA.
/// </summary>
public class FourScreensStrategy : Strategy
{
	private readonly StrategyParam<int> _emaPeriod;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevHaOpen;
	private decimal _prevHaClose;
	private bool _prevIsBull;
	private bool _hasPrev;

	public int EmaPeriod { get => _emaPeriod.Value; set => _emaPeriod.Value = value; }
	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public FourScreensStrategy()
	{
		_emaPeriod = Param(nameof(EmaPeriod), 50)
			.SetGreaterThanZero()
			.SetDisplay("EMA Period", "EMA trend filter period", "Indicator");

		_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 OnReseted()
	{
		base.OnReseted();
		_prevHaOpen = 0;
		_prevHaClose = 0;
		_prevIsBull = false;
		_hasPrev = false;
	}

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

		var ema = new ExponentialMovingAverage { Length = EmaPeriod };

		SubscribeCandles(CandleType)
			.Bind(ema, ProcessCandle)
			.Start();
	}

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

		// Calculate Heikin-Ashi
		decimal haOpen;
		decimal haClose;

		if (_prevHaOpen == 0 && _prevHaClose == 0)
		{
			haOpen = (candle.OpenPrice + candle.ClosePrice) / 2m;
			haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
		}
		else
		{
			haOpen = (_prevHaOpen + _prevHaClose) / 2m;
			haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
		}

		var isBull = haClose > haOpen;
		var close = candle.ClosePrice;

		if (_hasPrev)
		{
			// Buy: HA turns bullish + price above EMA
			if (isBull && !_prevIsBull && close > emaValue && Position <= 0)
			{
				if (Position < 0) BuyMarket();
				BuyMarket();
			}
			// Sell: HA turns bearish + price below EMA
			else if (!isBull && _prevIsBull && close < emaValue && Position >= 0)
			{
				if (Position > 0) SellMarket();
				SellMarket();
			}
		}

		_prevHaOpen = haOpen;
		_prevHaClose = haClose;
		_prevIsBull = isBull;
		_hasPrev = true;
	}
}