Esta estratégia é uma porta direta do consultor especialista MetaTrader 4 Fractal ZigZag Expert.mq4. Ele reconstrói o projeto de lei Williams
sequência fractal e interpreta o extremo confirmado mais recente como a perna ativa do mercado. Quando o último fractal válido é um
oscilar para baixo, o sistema abre uma posição longa; quando uma oscilação alta é confirmada, ele abre uma posição curta. A implementação mantém o
parâmetros originais - profundidade fractal, take-profit, distâncias de stop inicial e trailing stop - enquanto adapta o roteamento do pedido para
o StockSharp API de alto nível.
A estratégia é mais adequada para velas H1, replicando o gráfico padrão usado na versão MetaTrader. No entanto, o
O parâmetro CandleType permite alternar para qualquer outro período compatível com o feed de dados. Todas as distâncias são expressas em preço
pontos (etapas de preço do instrumento), que reflete a maneira como MetaTrader usa a constante Point.
Regras de negociação
Detecção de sinal
O algoritmo verifica cada vela finalizada e constrói uma janela contínua com elementos 2 * Level + 1.
Um fractal alto é confirmado quando a vela do meio tem a máxima mais alta dentro dessa janela; um fractal baixo requer o menor
baixo.
Apenas o último fractal confirmado controla a direção: um mínimo define a tendência interna para 2 (alta), um máximo define-a para
1 (baixa).
Inscrições
Quando a tendência interna é igual a 2 e não há posição aberta, uma compra de mercado é enviada usando o volume Lots.
Quando a tendência é igual a 1 sem posição, uma venda no mercado é enviada.
A estratégia entrará novamente na mesma direção após o fechamento de uma posição, se a tendência não tiver mudado.
Saídas e gerenciamento de risco
Cada entrada recebe um stop loss inicial e um takeprofit fixo definido em pontos. Um valor de parada de 0 desativa o
respectiva proteção.
O trailing stop opcional (também em pontos) é ativado quando o preço se move pela distância configurada. A parada é então movida para
manter o mesmo deslocamento do preço de fechamento, nunca cruzando o stop de proteção inicial.
As ordens de proteção são emuladas monitorando os máximos/mínimos das velas para aproximar os toques intrabarras, correspondendo de perto ao original
Lógica MQL4.
Parâmetros padrão
Parâmetro
Padrão
Descrição
Level
2
Número de velas de cada lado necessárias para confirmar um fractal.
TakeProfitPoints
25
Distância até a meta de lucro em faixas de preço.
InitialStopPoints
20
Distância até o stop loss inicial em pontos de preço.
TrailingStopPoints
10
Distância do trailing stop em faixas de preço (definida como 0 para desativar).
Lots
1
Volume de pedidos usado para entradas no mercado.
CandleType
H1
Prazo de velas processadas pela estratégia.
Notas
A estratégia chama StartProtection() uma vez na inicialização para que StockSharp possa gerenciar a liquidação de posição de emergência, se necessário.
Todos os registros e comentários são fornecidos em inglês, enquanto as descrições seguem o idioma de cada variante README, conforme exigido pelo
diretrizes de conversão.
A implementação evita buffers de indicadores e imita a abordagem MetaTrader mantendo apenas a janela contínua mínima
necessário para avaliar um fractal.
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Fractal ZigZag: Confirms Bill Williams fractals then trades
/// in the direction of the last confirmed extremum.
/// Bullish after low fractal, bearish after high fractal.
/// </summary>
public class FractalZigZagStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _level;
private readonly StrategyParam<int> _atrLength;
private readonly List<(decimal high, decimal low, DateTimeOffset time)> _window = new();
private int _trend; // 1=bearish (last was high), 2=bullish (last was low)
private int _prevTrend;
private decimal _entryPrice;
public FractalZigZagStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame())
.SetDisplay("Candle Type", "Timeframe.", "General");
_level = Param(nameof(Level), 2)
.SetDisplay("Fractal Depth", "Candles on each side to confirm fractal.", "Signals");
_atrLength = Param(nameof(AtrLength), 14)
.SetDisplay("ATR Length", "ATR period for stops.", "Indicators");
}
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
public int Level
{
get => _level.Value;
set => _level.Value = value;
}
public int AtrLength
{
get => _atrLength.Value;
set => _atrLength.Value = value;
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_window.Clear();
_trend = 0;
_prevTrend = 0;
_entryPrice = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal atrVal)
{
if (candle.State != CandleStates.Finished)
return;
// Update fractal window
var depth = Math.Max(1, Level);
var windowSize = depth * 2 + 1;
_window.Add((candle.HighPrice, candle.LowPrice, candle.OpenTime));
while (_window.Count > windowSize)
_window.RemoveAt(0);
// Evaluate fractals
if (_window.Count >= windowSize)
{
var centerIndex = _window.Count - 1 - depth;
var center = _window[centerIndex];
var isHigh = true;
var isLow = true;
for (var i = 0; i < _window.Count; i++)
{
if (i == centerIndex)
continue;
if (_window[i].high >= center.high)
isHigh = false;
if (_window[i].low <= center.low)
isLow = false;
if (!isHigh && !isLow)
break;
}
if (isHigh)
_trend = 1; // bearish: last fractal was a high
if (isLow)
_trend = 2; // bullish: last fractal was a low
}
if (atrVal <= 0 || _trend == 0)
{
_prevTrend = _trend;
return;
}
var close = candle.ClosePrice;
// Exit management
if (Position > 0)
{
if (close <= _entryPrice - atrVal * 2m || close >= _entryPrice + atrVal * 3m || _trend == 1)
{
SellMarket();
_entryPrice = 0;
}
}
else if (Position < 0)
{
if (close >= _entryPrice + atrVal * 2m || close <= _entryPrice - atrVal * 3m || _trend == 2)
{
BuyMarket();
_entryPrice = 0;
}
}
// Entry on trend change
if (Position == 0 && _prevTrend != 0 && _trend != _prevTrend)
{
if (_trend == 2)
{
_entryPrice = close;
BuyMarket();
}
else if (_trend == 1)
{
_entryPrice = close;
SellMarket();
}
}
_prevTrend = _trend;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import AverageTrueRange
class fractal_zig_zag_strategy(Strategy):
def __init__(self):
super(fractal_zig_zag_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(8))) \
.SetDisplay("Candle Type", "Timeframe", "General")
self._level = self.Param("Level", 2) \
.SetDisplay("Fractal Depth", "Candles on each side to confirm fractal", "Signals")
self._atr_length = self.Param("AtrLength", 14) \
.SetDisplay("ATR Length", "ATR period for stops", "Indicators")
self._window = []
self._trend = 0 # 1=bearish (last was high), 2=bullish (last was low)
self._prev_trend = 0
self._entry_price = 0.0
@property
def CandleType(self):
return self._candle_type.Value
@property
def Level(self):
return self._level.Value
@property
def AtrLength(self):
return self._atr_length.Value
def OnStarted2(self, time):
super(fractal_zig_zag_strategy, self).OnStarted2(time)
self._window = []
self._trend = 0
self._prev_trend = 0
self._entry_price = 0.0
self._atr = AverageTrueRange()
self._atr.Length = self.AtrLength
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(self._atr, self.ProcessCandle).Start()
def ProcessCandle(self, candle, atr_val):
if candle.State != CandleStates.Finished:
return
av = float(atr_val)
high = float(candle.HighPrice)
low = float(candle.LowPrice)
close = float(candle.ClosePrice)
depth = max(1, self.Level)
window_size = depth * 2 + 1
self._window.append((high, low))
while len(self._window) > window_size:
self._window.pop(0)
# Evaluate fractals
if len(self._window) >= window_size:
center_index = len(self._window) - 1 - depth
center = self._window[center_index]
is_high = True
is_low = True
for i in range(len(self._window)):
if i == center_index:
continue
if self._window[i][0] >= center[0]:
is_high = False
if self._window[i][1] <= center[1]:
is_low = False
if not is_high and not is_low:
break
if is_high:
self._trend = 1
if is_low:
self._trend = 2
if av <= 0 or self._trend == 0:
self._prev_trend = self._trend
return
# Exit management
if self.Position > 0:
if close <= self._entry_price - av * 2.0 or close >= self._entry_price + av * 3.0 or self._trend == 1:
self.SellMarket()
self._entry_price = 0.0
elif self.Position < 0:
if close >= self._entry_price + av * 2.0 or close <= self._entry_price - av * 3.0 or self._trend == 2:
self.BuyMarket()
self._entry_price = 0.0
if not self.IsFormedAndOnlineAndAllowTrading():
self._prev_trend = self._trend
return
# Entry on trend change
if self.Position == 0 and self._prev_trend != 0 and self._trend != self._prev_trend:
if self._trend == 2:
self._entry_price = close
self.BuyMarket()
elif self._trend == 1:
self._entry_price = close
self.SellMarket()
self._prev_trend = self._trend
def OnReseted(self):
super(fractal_zig_zag_strategy, self).OnReseted()
self._window = []
self._trend = 0
self._prev_trend = 0
self._entry_price = 0.0
def CreateClone(self):
return fractal_zig_zag_strategy()