Ver no GitHub

Estratégia Ema612CrossoverStrategy

Resumo

  • Port do consultor especializado do MetaTrader 5 "EMA 6.12 (edição de barabashkakvn)" para a API de alto nível do StockSharp.
  • Negocia o cruzamento entre uma média móvel simples rápida e uma lenta (o script original também usava MODE_SMA apesar de seu nome EMA).
  • Adiciona gerenciamento opcional de take profit e trailing stop expressos em unidades de preço absolutas para que o comportamento possa ser ajustado por instrumento.

Lógica de trading

Preparação de dados

  • A estratégia subscreve velas do tipo definido por CandleType (período de 15 minutos por padrão).
  • Duas médias móveis simples são calculadas: comprimento FastPeriod para a curva rápida e comprimento SlowPeriod para a curva lenta. O período lento deve ser maior que o período rápido.

Regras de entrada

  • Os sinais são avaliados no fechamento de cada vela terminada.
  • Um cruzamento altista ocorre quando a SMA lenta estava acima da SMA rápida na vela anterior e cai abaixo dela na vela atual. Qualquer posição vendida aberta é fechada e uma posição comprada é aberta com o Volume configurado.
  • Um cruzamento baixista ocorre quando a SMA lenta estava abaixo da SMA rápida na vela anterior e sobe acima dela na vela atual. Qualquer posição comprada aberta é fechada e uma posição vendida é aberta com o Volume configurado.

Regras de saída

  • As posições abertas são fechadas no cruzamento oposto conforme descrito acima.
  • Take profit opcional: se TakeProfitOffset for maior que zero, a estratégia calcula um alvo de preço fixo a partir do preço de entrada. Trades comprados saem quando o preço atinge entrada + TakeProfitOffset; trades vendidos saem quando o preço atinge entrada - TakeProfitOffset.
  • Trailing stop opcional: quando TrailingStopOffset for maior que zero, a estratégia aguarda até que o lucro não realizado ultrapasse TrailingStopOffset + TrailingStepOffset. Uma vez que esse limiar é cruzado, o preço de stop é ajustado para ficar TrailingStopOffset afastado do último fechamento, mas somente se o novo nível estiver pelo menos TrailingStepOffset mais próximo do preço do que o stop anterior. Trades comprados usam mínimas para acionar o stop, vendidos usam máximas.

Parâmetros

Parâmetro Padrão Descrição
CandleType Período de 15 minutos Resolução de vela usada para cálculos SMA e avaliação de sinais.
FastPeriod 6 Período para a média móvel simples rápida. Deve ser > 0 e menor que SlowPeriod.
SlowPeriod 54 Período para a média móvel simples lenta. Deve ser > 0 e maior que FastPeriod.
Volume 1 Volume de ordem usado para novas entradas.
TakeProfitOffset 0.001 Distância de preço absoluta opcional para o alvo de take profit. Definir como 0 para desabilitar.
TrailingStopOffset 0.005 Distância absoluta entre o preço e o trailing stop. Definir como 0 para desabilitar o trailing.
TrailingStepOffset 0.0005 Movimento favorável adicional necessário antes de o trailing stop ser movido.

Importante: os offsets são especificados em unidades de preço absolutas. Ajuste-os para corresponder ao tamanho do tick do instrumento (por exemplo, no EURUSD com um passo de 0.0001, os valores padrão correspondem a 10, 50 e 5 pips respectivamente).

Notas de implementação

  • Usa o fluxo de trabalho de alto nível SubscribeCandles().Bind() conforme exigido pelas diretrizes do projeto.
  • A saída do gráfico plota ambas as SMAs e marcadores de operações quando os gráficos estão disponíveis no ambiente.
  • As variáveis de estado rastreiam o preço de entrada, o nível de trailing stop e o alvo de take profit exatamente como a versão MQL.
  • A implementação em C# impõe SlowPeriod > FastPeriod na inicialização para evitar uma configuração de indicador inválida.

Dicas de uso

  • Otimize o período das velas e os períodos SMA para corresponder ao mercado sendo negociado (p.ex., períodos mais curtos para futuros intradiários, mais longos para swing trading).
  • Converta os offsets de pips ou ticks em unidades de preço absolutas antes de executar a estratégia.
  • O trailing pode ser desativado definindo TrailingStopOffset como zero; a estratégia então dependerá exclusivamente do cruzamento oposto ou do take profit opcional para as saídas.
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// EMA 6/12 crossover strategy with trailing stop management.
/// </summary>
public class Ema612CrossoverStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<decimal> _takeProfitOffset;
	private readonly StrategyParam<decimal> _trailingStopOffset;
	private readonly StrategyParam<decimal> _trailingStepOffset;

	private ExponentialMovingAverage _fastSma;
	private ExponentialMovingAverage _slowSma;

	private decimal? _prevFast;
	private decimal? _prevSlow;

	private decimal? _entryPrice;
	private decimal? _stopPrice;
	private decimal? _takeProfitPrice;

	/// <summary>
	/// Candle type for calculations.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Fast moving average period.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow moving average period.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}


	/// <summary>
	/// Take profit distance in absolute price units.
	/// </summary>
	public decimal TakeProfitOffset
	{
		get => _takeProfitOffset.Value;
		set => _takeProfitOffset.Value = value;
	}

	/// <summary>
	/// Trailing stop distance in absolute price units.
	/// </summary>
	public decimal TrailingStopOffset
	{
		get => _trailingStopOffset.Value;
		set => _trailingStopOffset.Value = value;
	}

	/// <summary>
	/// Additional distance required to move the trailing stop.
	/// </summary>
	public decimal TrailingStepOffset
	{
		get => _trailingStepOffset.Value;
		set => _trailingStepOffset.Value = value;
	}

	/// <summary>
	/// Initializes <see cref="Ema612CrossoverStrategy"/>.
	/// </summary>
	public Ema612CrossoverStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
			.SetDisplay("Candle Type", "Candle resolution", "General");
		_fastPeriod = Param(nameof(FastPeriod), 6)
			.SetGreaterThanZero()
			.SetDisplay("Fast Period", "Fast SMA length", "Moving Averages");
		_slowPeriod = Param(nameof(SlowPeriod), 54)
			.SetGreaterThanZero()
			.SetDisplay("Slow Period", "Slow SMA length", "Moving Averages");
		_takeProfitOffset = Param(nameof(TakeProfitOffset), 0.001m)
			.SetNotNegative()
			.SetDisplay("Take Profit", "Target distance in price units", "Risk");
		_trailingStopOffset = Param(nameof(TrailingStopOffset), 0.005m)
			.SetNotNegative()
			.SetDisplay("Trailing Stop", "Trailing stop distance", "Risk");
		_trailingStepOffset = Param(nameof(TrailingStepOffset), 0.0005m)
			.SetNotNegative()
			.SetDisplay("Trailing Step", "Additional profit required to tighten stop", "Risk");
	}

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

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

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

		if (SlowPeriod <= FastPeriod)
			throw new InvalidOperationException("Slow period must be greater than fast period.");

		_fastSma = new ExponentialMovingAverage { Length = FastPeriod };
		_slowSma = new ExponentialMovingAverage { Length = SlowPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_fastSma, _slowSma, ProcessCandle)
			.Start();

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

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

		if (!_fastSma.IsFormed || !_slowSma.IsFormed)
			return;

		var bullishCross = false;
		var bearishCross = false;

		if (_prevFast.HasValue && _prevSlow.HasValue)
		{
			// Detect crossovers using previous candle values.
			bullishCross = _prevSlow > _prevFast && slow < fast;
			bearishCross = _prevSlow < _prevFast && slow > fast;
		}

		HandleExistingPosition(candle, bullishCross, bearishCross);

		if (Position == 0)
		{
			if (bullishCross)
			{
				// Slow MA crossed below the fast MA - go long.
				EnterLong(candle);
			}
			else if (bearishCross)
			{
				// Slow MA crossed above the fast MA - go short.
				EnterShort(candle);
			}
		}

		_prevFast = fast;
		_prevSlow = slow;
	}

	private void HandleExistingPosition(ICandleMessage candle, bool bullishCross, bool bearishCross)
	{
		if (Position > 0)
		{
			// Update trailing stop for the long position before evaluating exits.
			UpdateLongTrailing(candle);

			var exit = bearishCross;
			if (!exit && _takeProfitPrice.HasValue && candle.HighPrice >= _takeProfitPrice.Value)
			{
				// Price reached the take profit objective.
				exit = true;
			}

			if (!exit && _stopPrice.HasValue && candle.LowPrice <= _stopPrice.Value)
			{
				// Price retraced to the trailing stop.
				exit = true;
			}

			if (exit)
			{
				SellMarket(Position);
				ResetPositionState();
			}
		}
		else if (Position < 0)
		{
			// Update trailing stop for the short position before evaluating exits.
			UpdateShortTrailing(candle);

			var exit = bullishCross;
			if (!exit && _takeProfitPrice.HasValue && candle.LowPrice <= _takeProfitPrice.Value)
			{
				// Price reached the take profit objective for the short trade.
				exit = true;
			}

			if (!exit && _stopPrice.HasValue && candle.HighPrice >= _stopPrice.Value)
			{
				// Price rallied back to the trailing stop level.
				exit = true;
			}

			if (exit)
			{
				BuyMarket(Math.Abs(Position));
				ResetPositionState();
			}
		}
	}

	private void EnterLong(ICandleMessage candle)
	{
		BuyMarket(Volume);
		_entryPrice = candle.ClosePrice;
		_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice + TakeProfitOffset : null;
		_stopPrice = null;
	}

	private void EnterShort(ICandleMessage candle)
	{
		SellMarket(Volume);
		_entryPrice = candle.ClosePrice;
		_takeProfitPrice = TakeProfitOffset > 0m ? candle.ClosePrice - TakeProfitOffset : null;
		_stopPrice = null;
	}

	private void UpdateLongTrailing(ICandleMessage candle)
	{
		if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
			return;

		var gain = candle.ClosePrice - _entryPrice.Value;
		var triggerDistance = TrailingStopOffset + TrailingStepOffset;

		if (gain <= triggerDistance)
			return;

		var candidate = candle.ClosePrice - TrailingStopOffset;
		var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;

		if (!_stopPrice.HasValue || candidate - _stopPrice.Value > minAdvance)
		{
			// Move stop loss closer only when price progressed enough.
			_stopPrice = candidate;
		}
	}

	private void UpdateShortTrailing(ICandleMessage candle)
	{
		if (TrailingStopOffset <= 0m || !_entryPrice.HasValue)
			return;

		var gain = _entryPrice.Value - candle.ClosePrice;
		var triggerDistance = TrailingStopOffset + TrailingStepOffset;

		if (gain <= triggerDistance)
			return;

		var candidate = candle.ClosePrice + TrailingStopOffset;
		var minAdvance = TrailingStepOffset <= 0m ? 0m : TrailingStepOffset;

		if (!_stopPrice.HasValue || _stopPrice.Value - candidate > minAdvance)
		{
			// Move stop loss for the short only after sufficient favorable movement.
			_stopPrice = candidate;
		}
	}

	private void ResetPositionState()
	{
		_entryPrice = null;
		_stopPrice = null;
		_takeProfitPrice = null;
	}
}