Ver no GitHub

Estratégia OsMaSter V0

Visão geral

  • Convertida do especialista de MetaTrader 5 "OsMaSter v0" (arquivo MQL OsMaSter v0.mq5).
  • Usa um padrão de histograma MACD (OsMA) para identificar reversões de momentum após uma breve consolidação.
  • Projetada para operar em um único instrumento e período selecionado pelo usuário através do parâmetro CandleType.
  • Converte automaticamente as configurações de risco baseadas em pips (stop-loss e take-profit) para offsets de preço absolutos usando o passo de preço do instrumento e a precisão decimal.

Parâmetros

Nome Padrão Descrição
FastPeriod 9 Comprimento da EMA rápida para o histograma MACD.
SlowPeriod 26 Comprimento da EMA lenta para o histograma MACD.
SignalPeriod 5 Comprimento da EMA de sinal usada para suavizar o histograma.
StopLossPips 30 Distância ao stop de proteção em pips. Definir como 0 para desabilitar.
TakeProfitPips 50 Distância ao alvo de lucro em pips. Definir como 0 para desabilitar.
TradeVolume 1 Volume de ordem (lotes) usado para entradas de mercado.
CandleType Candles de 15 minutos Período usado para os cálculos do indicador.

Lógica de sinais

  1. A estratégia mantém os últimos quatro valores do histograma MACD (hist0 = atual, hist1 = anterior, ..., hist3 = três candles atrás).
  2. Entrada comprada quando hist3 > hist2, hist2 < hist1, e hist1 < hist0 — uma sequência ascendente após um mínimo local.
  3. Entrada vendida quando hist3 < hist2, hist2 > hist1, e hist1 > hist0 — uma sequência descendente após um máximo local.
  4. Apenas uma posição pode estar aberta por vez. A estratégia ignora novos sinais enquanto uma negociação está ativa.

Gerenciamento de posição

  • As ordens são enviadas com BuyMarket() ou SellMarket() usando o TradeVolume configurado.
  • StartProtection anexa offsets de stop-loss e take-profit baseados nas entradas de pips. O tamanho do pip segue a convenção forex (passo de preço × 10 para instrumentos de 3/5 decimais, caso contrário o próprio passo de preço).
  • Não há regras de saída adicionais; as posições são gerenciadas exclusivamente pelas ordens de proteção ou por intervenção manual.

Notas

  • Certifique-se de que o Security tem valores corretos de PriceStep e Decimals para que a conversão de pips coincida com a especificação do broker.
  • Ajuste o período do candle e o volume para corresponder ao horizonte de negociação do mercado alvo.
  • Como a estratégia aguarda a execução do stop ou do alvo, sinais consecutivos na mesma direção são ignorados enquanto uma posição permanece aberta.
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>
/// OsMA histogram pattern strategy converted from the "OsMaSter v0" MQL expert.
/// Enters on four-bar momentum reversals identified by the MACD histogram.
/// </summary>
public class OsMaSterV0Strategy : Strategy
{
	private readonly StrategyParam<int> _fastPeriod;
	private readonly StrategyParam<int> _slowPeriod;
	private readonly StrategyParam<int> _signalPeriod;
	private readonly StrategyParam<int> _stopLossPips;
	private readonly StrategyParam<int> _takeProfitPips;
	private readonly StrategyParam<decimal> _tradeVolume;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _histCurrent;
	private decimal? _histPrev1;
	private decimal? _histPrev2;
	private decimal? _histPrev3;

	/// <summary>
	/// Initializes a new instance of the strategy.
	/// </summary>
	public OsMaSterV0Strategy()
	{
		_fastPeriod = Param(nameof(FastPeriod), 9)
			.SetDisplay("Fast EMA", "Fast EMA period for MACD histogram", "Indicators")
			.SetGreaterThanZero();

		_slowPeriod = Param(nameof(SlowPeriod), 26)
			.SetDisplay("Slow EMA", "Slow EMA period for MACD histogram", "Indicators")
			.SetGreaterThanZero();

		_signalPeriod = Param(nameof(SignalPeriod), 5)
			.SetDisplay("Signal Smoothing", "Signal moving average period", "Indicators")
			.SetGreaterThanZero();

		_stopLossPips = Param(nameof(StopLossPips), 500)
			.SetDisplay("Stop Loss (pips)", "Stop loss distance in pips", "Risk");

		_takeProfitPips = Param(nameof(TakeProfitPips), 1000)
			.SetDisplay("Take Profit (pips)", "Take profit distance in pips", "Risk");

		_tradeVolume = Param(nameof(TradeVolume), 1m)
			.SetDisplay("Trade Volume", "Order volume in lots", "Trading")
			.SetGreaterThanZero();

		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles for calculations", "General");

		Volume = TradeVolume;
	}

	/// <summary>
	/// Fast EMA period used in MACD histogram calculation.
	/// </summary>
	public int FastPeriod
	{
		get => _fastPeriod.Value;
		set => _fastPeriod.Value = value;
	}

	/// <summary>
	/// Slow EMA period used in MACD histogram calculation.
	/// </summary>
	public int SlowPeriod
	{
		get => _slowPeriod.Value;
		set => _slowPeriod.Value = value;
	}

	/// <summary>
	/// Signal moving average period.
	/// </summary>
	public int SignalPeriod
	{
		get => _signalPeriod.Value;
		set => _signalPeriod.Value = value;
	}

	/// <summary>
	/// Stop loss size expressed in pips.
	/// </summary>
	public int StopLossPips
	{
		get => _stopLossPips.Value;
		set => _stopLossPips.Value = value;
	}

	/// <summary>
	/// Take profit size expressed in pips.
	/// </summary>
	public int TakeProfitPips
	{
		get => _takeProfitPips.Value;
		set => _takeProfitPips.Value = value;
	}

	/// <summary>
	/// Trading volume used for market orders.
	/// </summary>
	public decimal TradeVolume
	{
		get => _tradeVolume.Value;
		set
		{
			_tradeVolume.Value = value;
			Volume = value;
		}
	}

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_histCurrent = null;
		_histPrev1 = null;
		_histPrev2 = null;
		_histPrev3 = null;

		Volume = TradeVolume;
	}

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

		Volume = TradeVolume;

		var macd = new MovingAverageConvergenceDivergenceHistogram
		{
			Macd =
			{
				ShortMa = { Length = FastPeriod },
				LongMa = { Length = SlowPeriod }
			},
			SignalMa = { Length = SignalPeriod }
		};

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(macd, ProcessCandle)
			.Start();

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

		var step = Security?.PriceStep ?? 1m;
		var decimals = Security?.Decimals ?? 0;
		var pipSize = (decimals == 3 || decimals == 5) ? step * 10m : step;

		// Convert pip-based risk controls into absolute price offsets.
		StartProtection(
			takeProfit: TakeProfitPips > 0 ? new Unit(TakeProfitPips * pipSize, UnitTypes.Absolute) : null,
			stopLoss: StopLossPips > 0 ? new Unit(StopLossPips * pipSize, UnitTypes.Absolute) : null);
	}

	private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
	{
		// Ignore incomplete candles because signals rely on closed data.
		if (candle.State != CandleStates.Finished)
			return;

		// Ensure the strategy is synchronized with the market and permitted to trade.
		if (!macdValue.IsFormed)
			return;

		var macdTyped = (MovingAverageConvergenceDivergenceHistogramValue)macdValue;
		if (macdTyped.Macd is not decimal histogram)
			return;

		// Shift stored histogram values to maintain the last four observations.
		_histPrev3 = _histPrev2;
		_histPrev2 = _histPrev1;
		_histPrev1 = _histCurrent;
		_histCurrent = histogram;

		if (_histCurrent is not decimal hist0 ||
			_histPrev1 is not decimal hist1 ||
			_histPrev2 is not decimal hist2 ||
			_histPrev3 is not decimal hist3)
		{
			return;
		}

		// Detect the specific four-bar rising pattern used for long entries.
		var bullishPattern = hist3 > hist2 && hist2 < hist1 && hist1 < hist0;

		// Detect the mirrored falling pattern used for short entries.
		var bearishPattern = hist3 < hist2 && hist2 > hist1 && hist1 > hist0;

		// The original expert opens a position only when no trades are active.
		if (Position != 0)
			return;

		if (bullishPattern)
		{
			// Enter long when the histogram forms a higher-low sequence.
			BuyMarket();
		}
		else if (bearishPattern)
		{
			// Enter short when the histogram forms a lower-high sequence.
			SellMarket();
		}
	}
}