Ver no GitHub

Estratégia Elite eFibo Trader

Visão geral

A Estratégia Elite eFibo Trader é uma conversão do expert advisor MQL5 "Elite eFibo Trader". Ela implementa uma grade de médias baseada em Fibonacci que abre uma posição inicial de mercado e camadas ordens stop adicionais a distâncias fixas. A estratégia opera com dados de tick e gerencia automaticamente os trailing stops conforme a grade se expande.

Como funciona

  1. Quando não há posições ou ordens pendentes ativas e o trading está permitido, a estratégia inicia um novo ciclo na direção selecionada (compra ou venda).
  2. A primeira ordem é enviada a mercado usando o volume configurado para LotsLevel1. Treze ordens stop adicionais são colocadas em múltiplos de LevelDistance a partir do preço atual. Seus volumes seguem a sequência de Fibonacci definida por LotsLevel2LotsLevel14.
  3. Cada ordem executada define um nível de stop individual a StopLossPoints do preço de entrada. O mais alto (para posições compradas) ou mais baixo (para posições vendidas) desses stops torna-se o nível de trailing ativo para todas as posições abertas.
  4. Se o preço atingir o nível de trailing, a posição inteira é fechada e todas as ordens pendentes restantes são canceladas.
  5. O lucro não realizado é monitorado na moeda da conta. Quando atingir MoneyTakeProfit, a grade é fechada. Dependendo de TradeAgainAfterProfit, a estratégia reinicia automaticamente ou aguarda reativação manual.

A estratégia requer dados de mercado em nível de tick via SubscribeTrades() e espera que apenas uma direção (OpenBuy xor OpenSell) esteja habilitada por vez.

Parâmetros

  • OpenBuy – habilita a versão somente comprado da grade.
  • OpenSell – habilita a versão somente vendido da grade.
  • TradeAgainAfterProfit – inicia automaticamente um novo ciclo após a realização de lucros.
  • LevelDistance – espaçamento entre ordens pendentes, medido em passos de preço do instrumento.
  • StopLossPoints – distância do stop-loss de cada entrada, medida em passos de preço.
  • MoneyTakeProfit – meta de lucro não realizado expresso em moeda da conta.
  • LotsLevel1LotsLevel14 – volumes individuais para cada nível da grade. Os valores padrão seguem a sequência de Fibonacci (1, 1, 2, 3, 5, …, 377).

Detalhes da lógica de trading

  • Os deslocamentos de preço são calculados com o PriceStep do instrumento; se for zero, a estratégia não colocará ordens.
  • Apenas um ciclo de trading está ativo por vez. Todas as ordens pendentes são criadas no início do ciclo e permanecem até serem executadas ou explicitamente canceladas.
  • Os trailing stops são recalculados sempre que um novo nível da grade é preenchido ou partes da posição são fechadas. Isso garante que todas as ordens compartilhem o melhor nível de proteção disponível.
  • O controle de lucros é baseado no PnL flutuante derivado de Position, PositionPrice, PriceStep e StepPrice.
  • Quando TradeAgainAfterProfit está desabilitado, a estratégia permanece inativa após atingir a meta monetária até que o parâmetro seja reativado manualmente.

Notas de uso

  • Configure a direção correta antes de iniciar (comprado ou vendido). Habilitar ambas as direções simultaneamente impede o lançamento da grade.
  • Ajuste as distâncias entre níveis e os volumes de acordo com a volatilidade do instrumento e o tamanho do contrato. Volumes grandes de Fibonacci criam escalonamento agressivo e devem ser testados cuidadosamente com dados históricos.
  • Certifique-se de que a conta de trading e o corretor suportem ordens stop nos níveis de preço calculados; caso contrário, as ordens podem ser rejeitadas.
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>
/// Elite eFibo Trader grid strategy converted from MQL5.
/// Builds a Fibonacci-based sequence of market entries at price levels.
/// Buys or sells at progressively worse prices with increasing volume (Fibonacci sequence).
/// Exits when total PnL target is reached or stop loss is hit.
/// </summary>
public class EliteEFiboTraderStrategy : Strategy
{
	private readonly StrategyParam<int> _levelsCount;
	private readonly StrategyParam<bool> _openBuy;
	private readonly StrategyParam<bool> _openSell;
	private readonly StrategyParam<decimal> _levelDistance;
	private readonly StrategyParam<decimal> _stopLossPoints;
	private readonly StrategyParam<decimal> _takeProfitPoints;
	private readonly StrategyParam<DataType> _candleType;

	private decimal _entryPrice;
	private int _currentLevel;
	private int _activeDirection;
	private bool _cycleActive;

	// Fibonacci volumes for grid levels
	private static readonly decimal[] FibVolumes = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };

	/// <summary>
	/// Enable buy-only mode.
	/// </summary>
	public bool OpenBuy
	{
		get => _openBuy.Value;
		set => _openBuy.Value = value;
	}

	/// <summary>
	/// Enable sell-only mode.
	/// </summary>
	public bool OpenSell
	{
		get => _openSell.Value;
		set => _openSell.Value = value;
	}

	/// <summary>
	/// Number of Fibonacci grid levels.
	/// </summary>
	public int LevelsCount
	{
		get => _levelsCount.Value;
		set => _levelsCount.Value = value;
	}

	/// <summary>
	/// Distance between successive pending levels in price steps.
	/// </summary>
	public decimal LevelDistance
	{
		get => _levelDistance.Value;
		set => _levelDistance.Value = value;
	}

	/// <summary>
	/// Stop-loss size in price steps.
	/// </summary>
	public decimal StopLossPoints
	{
		get => _stopLossPoints.Value;
		set => _stopLossPoints.Value = value;
	}

	/// <summary>
	/// Take profit size in price steps.
	/// </summary>
	public decimal TakeProfitPoints
	{
		get => _takeProfitPoints.Value;
		set => _takeProfitPoints.Value = value;
	}

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

	/// <summary>
	/// Initializes strategy parameters.
	/// </summary>
	public EliteEFiboTraderStrategy()
	{
		_levelsCount = Param(nameof(LevelsCount), 6)
			.SetGreaterThanZero()
			.SetDisplay("Levels Count", "Number of Fibonacci levels", "Grid");

		_openBuy = Param(nameof(OpenBuy), true)
			.SetDisplay("Open Buy", "Enable buying", "General");

		_openSell = Param(nameof(OpenSell), true)
			.SetDisplay("Open Sell", "Enable selling", "General");

		_levelDistance = Param(nameof(LevelDistance), 50m)
			.SetGreaterThanZero()
			.SetDisplay("Level Distance", "Distance between orders in price steps", "Grid");

		_stopLossPoints = Param(nameof(StopLossPoints), 200m)
			.SetGreaterThanZero()
			.SetDisplay("Stop Loss", "Stop-loss size in price steps", "Risk");

		_takeProfitPoints = Param(nameof(TakeProfitPoints), 100m)
			.SetGreaterThanZero()
			.SetDisplay("Take Profit", "Take profit size in price steps", "Risk");

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

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

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

		_cycleActive = false;
		_currentLevel = 0;
		_activeDirection = 0;
		_entryPrice = 0;

		var sma = new SMA { Length = 20 };

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

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var close = candle.ClosePrice;
		var step = Security.PriceStep ?? 1m;

		if (!_cycleActive && Position == 0)
		{
			// Start a new cycle based on trend direction
			if (OpenBuy && close > smaValue)
			{
				_activeDirection = 1;
				_entryPrice = close;
				_currentLevel = 0;
				_cycleActive = true;
				BuyMarket();
			}
			else if (OpenSell && close < smaValue)
			{
				_activeDirection = -1;
				_entryPrice = close;
				_currentLevel = 0;
				_cycleActive = true;
				SellMarket();
			}
		}
		else if (_cycleActive)
		{
			var stopDistance = StopLossPoints * step;
			var tpDistance = TakeProfitPoints * step;
			var levelDist = LevelDistance * step;

			// Check stop loss
			if (_activeDirection == 1 && close <= _entryPrice - stopDistance)
			{
				SellMarket(Math.Abs(Position));
				ResetCycle();
				return;
			}
			else if (_activeDirection == -1 && close >= _entryPrice + stopDistance)
			{
				BuyMarket(Math.Abs(Position));
				ResetCycle();
				return;
			}

			// Check take profit
			if (_activeDirection == 1 && close >= _entryPrice + tpDistance)
			{
				SellMarket(Math.Abs(Position));
				ResetCycle();
				return;
			}
			else if (_activeDirection == -1 && close <= _entryPrice - tpDistance)
			{
				BuyMarket(Math.Abs(Position));
				ResetCycle();
				return;
			}

			// Check for grid level additions (averaging into losing positions)
			var nextLevel = _currentLevel + 1;
			if (nextLevel < LevelsCount && nextLevel < FibVolumes.Length)
			{
				if (_activeDirection == 1 && close <= _entryPrice - levelDist * nextLevel)
				{
					BuyMarket(FibVolumes[nextLevel]);
					_currentLevel = nextLevel;
				}
				else if (_activeDirection == -1 && close >= _entryPrice + levelDist * nextLevel)
				{
					SellMarket(FibVolumes[nextLevel]);
					_currentLevel = nextLevel;
				}
			}
		}
	}

	private void ResetCycle()
	{
		_cycleActive = false;
		_currentLevel = 0;
		_activeDirection = 0;
		_entryPrice = 0;
	}
}