Ver no GitHub

Estratégia PriceMode do Método Cruzado MA

Visão geral

A estratégia MA Cross Method PriceMode é uma porta StockSharp direta do MetaTrader 4 especialista "MA_cross_Method_PriceMode". Combina duas médias móveis configuráveis ​​e reage sempre que a média rápida cruza a média lenta. Ambas as linhas expõem as entradas originais MetaTrader: período, método de suavização (SMA, EMA, SMMA, LWMA), preço aplicado (fechamento, abertura, máximo, mínimo, mediano, típico, ponderado) e deslocamento horizontal. A estratégia funciona com qualquer instrumento que forneça velas regulares baseadas no tempo.

Indicadores

  • Média Móvel Rápida – comprimento, método e fonte de preço configuráveis. O parâmetro shift MetaTrader é reproduzido armazenando em buffer os valores do indicador concluídos e lendo as barras de valor FirstShift de volta.
  • Média Móvel Lenta – comprimento, método e fonte de preço configuráveis com a mesma emulação de turno via buffer.

Lógica de negociação

  1. A estratégia assina o tipo de vela selecionado e processa apenas velas acabadas para evitar a repintura intra-barra.
  2. Para cada barra fechada alimenta ambas as médias móveis com seus respectivos preços aplicados.
  3. Quando ambas as médias produzem valores finais, a estratégia avalia duas condições:
    • Cruz de alta – a MM rápida estava abaixo ou igual à MM lenta na barra anterior e se move acima dela na barra atual.
    • Cruz de baixa – a MM rápida estava acima ou igual à MM lenta na barra anterior e se move abaixo dela na barra atual.
  4. Numa linha de alta, a estratégia compra OrderVolume contratos. Se uma posição curta estiver aberta, o tamanho da ordem aumenta automaticamente para cobrir a posição curta e estabelecer a nova exposição longa.
  5. Numa linha de baixa, a estratégia vende OrderVolume contratos. Se uma posição longa estiver aberta, o tamanho da ordem aumenta para fechá-la antes de estabelecer a posição curta.
  6. StartProtection() é invocado para que StockSharp módulos de proteção possam ser adicionados se desejado (por exemplo, assistentes de stop-loss ou de ponto de equilíbrio).

Parâmetros

Nome Descrição Padrão
FirstPeriod Período da média móvel rápida. 3
SecondPeriod Período da média móvel lenta. 13
FirstMethod Método de suavização usado para média móvel rápida (Simple, Exponential, Smoothed, LinearWeighted). Simple
SecondMethod Método de suavização usado para a média móvel lenta. LinearWeighted
FirstPriceMode Preço aplicado para a média móvel rápida (Close, Open, High, Low, Median, Typical, Weighted). Close
SecondPriceMode Preço aplicado para a média móvel lenta. Median
FirstShift Deslocamento horizontal (em barras) aplicado à média móvel rápida. 0
SecondShift Deslocamento horizontal (em barras) aplicado à média móvel lenta. 0
OrderVolume Volume base do pedido usado para novas posições. 0.1
CandleType Tipo/prazo de vela processado pela estratégia. Velas de 5 minutos

Diferenças em comparação com a versão MQL

  • A iteração de ordem MetaTrader (OrdersTotal, OrderSelect, OrderClose) é substituída pelo uso direto da propriedade StockSharp Strategy.Position e ordens de mercado dimensionadas para reverter a exposição quando necessário.
  • O sinalizador MetaTrader "nova barra" não é necessário: ProcessCandle é executado exatamente uma vez por vela concluída, garantindo o mesmo comportamento uma vez por barra sem pesquisa em nível de tick.
  • O tratamento de deslocamento MA é implementado com buffers compactos que contêm os últimos shift + 2 valores para cada média. Isso reflete o deslocamento do indicador sem depender de referências anteriores proibidas do indicador (GetValue).
  • A estratégia é independente do corretor; auxiliares de gerenciamento de risco podem ser anexados por meio de StartProtection() em vez dos argumentos fixos de parada/limite MetaTrader.

Notas de uso

  • Escolha a duração da vela que corresponda ao período original (por exemplo, M5 ou H1). Prazos personalizados podem ser fornecidos editando CandleType nos parâmetros da estratégia.
  • Definir FirstShift ou SecondShift para um valor positivo atrasa o cruzamento efetivo naquela quantidade de barras concluídas, assim como a entrada de deslocamento horizontal em MetaTrader.
  • O modo de preço Weighted reproduz a fórmula (High + Low + 2 * Close) / 4 de MetaTrader. Os modos mediano e típico seguem as definições padrão (High + Low) / 2 e (High + Low + Close) / 3.
  • Como cada ordem é uma ordem de mercado, certifique-se de que a configuração da conta tolere o volume solicitado e a derrapagem.
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>
/// Moving average crossover strategy converted from the MetaTrader script "MA_cross_Method_PriceMode".
/// Allows selecting the smoothing method, applied price and horizontal shift for each average.
/// </summary>
public class MaCrossMethodPriceModeStrategy : Strategy
{
	private readonly StrategyParam<int> _firstPeriod;
	private readonly StrategyParam<int> _secondPeriod;
	private readonly StrategyParam<MaMethods> _firstMethod;
	private readonly StrategyParam<MaMethods> _secondMethod;
	private readonly StrategyParam<AppliedPriceModes> _firstPriceMode;
	private readonly StrategyParam<AppliedPriceModes> _secondPriceMode;
	private readonly StrategyParam<int> _firstShift;
	private readonly StrategyParam<int> _secondShift;
	private readonly StrategyParam<decimal> _orderVolume;
	private readonly StrategyParam<DataType> _candleType;

	private DecimalLengthIndicator _firstMa = null!;
	private DecimalLengthIndicator _secondMa = null!;

	private readonly List<decimal> _firstValues = new();
	private readonly List<decimal> _secondValues = new();

	/// <summary>
	/// Initializes a new instance of <see cref="MaCrossMethodPriceModeStrategy"/>.
	/// </summary>
	public MaCrossMethodPriceModeStrategy()
	{
		_firstPeriod = Param(nameof(FirstPeriod), 3)
			.SetGreaterThanZero()
			.SetDisplay("Fast MA Period", "Length of the first moving average.", "Indicators")
			
			.SetOptimize(2, 50, 1);

		_secondPeriod = Param(nameof(SecondPeriod), 13)
			.SetGreaterThanZero()
			.SetDisplay("Slow MA Period", "Length of the second moving average.", "Indicators")
			
			.SetOptimize(5, 100, 1);

		_firstMethod = Param(nameof(FirstMethod), MaMethods.Simple)
			.SetDisplay("Fast MA Method", "Smoothing method applied to the first moving average.", "Indicators")
			;

		_secondMethod = Param(nameof(SecondMethod), MaMethods.LinearWeighted)
			.SetDisplay("Slow MA Method", "Smoothing method applied to the second moving average.", "Indicators")
			;

		_firstPriceMode = Param(nameof(FirstPriceMode), AppliedPriceModes.Close)
			.SetDisplay("Fast MA Price", "Price source used for the first moving average.", "Indicators")
			;

		_secondPriceMode = Param(nameof(SecondPriceMode), AppliedPriceModes.Median)
			.SetDisplay("Slow MA Price", "Price source used for the second moving average.", "Indicators")
			;

		_firstShift = Param(nameof(FirstShift), 0)
			.SetNotNegative()
			.SetDisplay("Fast MA Shift", "Horizontal shift (in bars) applied to the first moving average.", "Indicators");

		_secondShift = Param(nameof(SecondShift), 0)
			.SetNotNegative()
			.SetDisplay("Slow MA Shift", "Horizontal shift (in bars) applied to the second moving average.", "Indicators");

		_orderVolume = Param(nameof(OrderVolume), 0.1m)
			.SetGreaterThanZero()
			.SetDisplay("Order Volume", "Base order volume used for new entries.", "Trading")
			;

		_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
			.SetDisplay("Candle Type", "Timeframe used for price processing.", "General");
	}

	/// <summary>
	/// Period of the first moving average.
	/// </summary>
	public int FirstPeriod
	{
		get => _firstPeriod.Value;
		set => _firstPeriod.Value = value;
	}

	/// <summary>
	/// Period of the second moving average.
	/// </summary>
	public int SecondPeriod
	{
		get => _secondPeriod.Value;
		set => _secondPeriod.Value = value;
	}

	/// <summary>
	/// Smoothing method applied to the first moving average.
	/// </summary>
	public MaMethods FirstMethod
	{
		get => _firstMethod.Value;
		set => _firstMethod.Value = value;
	}

	/// <summary>
	/// Smoothing method applied to the second moving average.
	/// </summary>
	public MaMethods SecondMethod
	{
		get => _secondMethod.Value;
		set => _secondMethod.Value = value;
	}

	/// <summary>
	/// Applied price mode for the first moving average.
	/// </summary>
	public AppliedPriceModes FirstPriceMode
	{
		get => _firstPriceMode.Value;
		set => _firstPriceMode.Value = value;
	}

	/// <summary>
	/// Applied price mode for the second moving average.
	/// </summary>
	public AppliedPriceModes SecondPriceMode
	{
		get => _secondPriceMode.Value;
		set => _secondPriceMode.Value = value;
	}

	/// <summary>
	/// Shift (in bars) applied to the first moving average values.
	/// </summary>
	public int FirstShift
	{
		get => _firstShift.Value;
		set => _firstShift.Value = value;
	}

	/// <summary>
	/// Shift (in bars) applied to the second moving average values.
	/// </summary>
	public int SecondShift
	{
		get => _secondShift.Value;
		set => _secondShift.Value = value;
	}

	/// <summary>
	/// Base order volume used for new positions.
	/// </summary>
	public decimal OrderVolume
	{
		get => _orderVolume.Value;
		set => _orderVolume.Value = value;
	}

	/// <summary>
	/// Candle type (timeframe) processed by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

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

		_firstMa = null!;
		_secondMa = null!;
		_firstValues.Clear();
		_secondValues.Clear();
	}

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

		_firstMa = CreateMovingAverage(FirstMethod, FirstPeriod);
		_secondMa = CreateMovingAverage(SecondMethod, SecondPeriod);

		var subscription = SubscribeCandles(CandleType);
		subscription
			.Bind(_firstMa, _secondMa, ProcessCandle)
			.Start();

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

		StartProtection(null, null);
	}

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

		UpdateBuffer(_firstValues, firstDecimal, FirstShift);
		UpdateBuffer(_secondValues, secondDecimal, SecondShift);

		if (!TryGetShiftedValues(_firstValues, FirstShift, out var firstCurrent, out var firstPrevious))
			return;

		if (!TryGetShiftedValues(_secondValues, SecondShift, out var secondCurrent, out _))
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var bullishCross = IsBullishCross(firstPrevious, firstCurrent, secondCurrent);
		var bearishCross = IsBearishCross(firstPrevious, firstCurrent, secondCurrent);

		if (bullishCross && OrderVolume > 0m && Position <= 0m)
		{
			var volumeToBuy = OrderVolume + (Position < 0m ? Math.Abs(Position) : 0m);
			BuyMarket(volumeToBuy);
		}
		else if (bearishCross && OrderVolume > 0m && Position >= 0m)
		{
			var volumeToSell = OrderVolume + (Position > 0m ? Position : 0m);
			SellMarket(volumeToSell);
		}
	}

	private static void UpdateBuffer(List<decimal> buffer, decimal value, int shift)
	{
		buffer.Add(value);

		var maxCount = Math.Max(shift + 2, 2);
		while (buffer.Count > maxCount)
		{
			buffer.RemoveAt(0);
		}
	}

	private static bool TryGetShiftedValues(IReadOnlyList<decimal> buffer, int shift, out decimal current, out decimal previous)
	{
		var currentIndex = buffer.Count - 1 - shift;
		var previousIndex = buffer.Count - 2 - shift;

		if (previousIndex < 0 || currentIndex < 0 || currentIndex >= buffer.Count)
		{
			current = default;
			previous = default;
			return false;
		}

		current = buffer[currentIndex];
		previous = buffer[previousIndex];
		return true;
	}

	private static bool IsBullishCross(decimal previousFast, decimal currentFast, decimal currentSlow)
	{
		return (previousFast <= currentSlow && currentFast > currentSlow)
			|| (previousFast < currentSlow && currentFast >= currentSlow);
	}

	private static bool IsBearishCross(decimal previousFast, decimal currentFast, decimal currentSlow)
	{
		return (previousFast >= currentSlow && currentFast < currentSlow)
			|| (previousFast > currentSlow && currentFast <= currentSlow);
	}

	private static decimal SelectPrice(ICandleMessage candle, AppliedPriceModes mode)
	{
		return mode switch
		{
			AppliedPriceModes.Close => candle.ClosePrice,
			AppliedPriceModes.Open => candle.OpenPrice,
			AppliedPriceModes.High => candle.HighPrice,
			AppliedPriceModes.Low => candle.LowPrice,
			AppliedPriceModes.Median => (candle.HighPrice + candle.LowPrice) / 2m,
			AppliedPriceModes.Typical => (candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 3m,
			AppliedPriceModes.Weighted => (candle.HighPrice + candle.LowPrice + (2m * candle.ClosePrice)) / 4m,
			_ => candle.ClosePrice
		};
	}

	private static DecimalLengthIndicator CreateMovingAverage(MaMethods method, int period)
	{
		return method switch
		{
			MaMethods.Simple => new SMA { Length = period },
			MaMethods.Exponential => new EMA { Length = period },
			MaMethods.Smoothed => new SmoothedMovingAverage { Length = period },
			MaMethods.LinearWeighted => new WeightedMovingAverage { Length = period },
			_ => new SMA { Length = period }
		};
	}

	/// <summary>
	/// Moving average smoothing methods that mirror the MetaTrader inputs.
	/// </summary>
	public enum MaMethods
	{
		Simple,
		Exponential,
		Smoothed,
		LinearWeighted
	}

	/// <summary>
	/// Applied price options equivalent to the MetaTrader constants.
	/// </summary>
	public enum AppliedPriceModes
	{
		Close,
		Open,
		High,
		Low,
		Median,
		Typical,
		Weighted
	}
}