var int idx = 0
maxBar = bar_index > lookback ? ta.highestbars(high, lookback) : ta.highestbars(high, bar_index + 1)
for i = 0 to lookback - 1 by 1
if high[i+1] > high[i+2] and high[i] <= high[i+1] and ((i+1) * -1) >= maxBar
idx := (i+1) * -1
//break
idx := idx == 0 ? maxBar : idx
get_structure_lowest_bar(lookback) =>
code
var int idx = 0
minBar = bar_index > lookback ? ta.lowestbars(low, lookback) : ta.lowestbars(low, bar_index + 1)
for i = 0 to lookback - 1 by 1
if low[i+1] < low[i+2] and low[i] >= low[i+1] and ((i+1) * -1) >= minBar
idx := (i+1) * -1
//break
idx := idx == 0 ? minBar : idx
is_structure_high_broken(_highStructBreakPrice, _structureHigh, _structureHighStartIndex, _structureDirection) =>
var bool res = false
code
if (_highStructBreakPrice > _structureHigh and bar_index[1] > _structureHighStartIndex) or (_structureDirection == 1 and _highStructBreakPrice > _structureHigh)
res := true
else
res := false
res
// Fear Value Gap
isFvgToShow = input(true, title='Display FVG', group="Fear Value Gap")
bullishFvgColor = input(color.new(#b2b5be, 70), 'Bullish FVG Color', group="Fear Value Gap")
bearishFvgColor = input(color.new(#b2b5be, 70), 'Bearish FVG Color', group="Fear Value Gap")
mitigatedFvgColor = input(color.new(#b2b5be, 70), 'Mitigated FVG Color', group="Fear Value Gap")
fvgHistoryNbr = input.int(5, 'Number of FVG to show', minval=1, maxval=50)
isMitigatedFvgToReduce = input(false, title='Reduce mitigated FVG', group="Fear Value Gap")
// Draw FVG into graph
FVGDraw(_boxes, _fvgTypes, _isFvgMitigated) =>
code
// Loop into all values of the array
for [index, value] in _boxes
// Processing bullish FVG
if(array.get(_fvgTypes, index))
// Check if FVG has been totally mitigated
if(low <= box.get_bottom(value))
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
box.delete(value)
else
if(low < box.get_top((value)))
box.set_bgcolor(value, mitigatedFvgColor)
// Mitigated FVG Alert
if(not(array.get(_isFvgMitigated, index)))
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
// Reduce FVG if needed
if(isMitigatedFvgToReduce)
box.set_top(value, low)
box.set_right(value, bar_index)
// Processing bearish FVG
else
// Check if FVG has been mitigated
if(high >= box.get_top(value))
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
box.delete(value)
else
if(high > box.get_bottom((value)))
box.set_bgcolor(value, mitigatedFvgColor)
// Mitigated FVG Alert
if(not(array.get(_isFvgMitigated, index)))
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
// Reduce FVG if needed
if(isMitigatedFvgToReduce)
box.set_bottom(value, high)
box.set_right(value, bar_index)
// Arrays variable
var array structureLines = array.new_line(0)
var array structureLabels = array.new_label(0)
var array fvgBoxes = array.new_box(0)
var array fvgTypes = array.new_bool(0)
var array isFvgMitigated = array.new_bool(0)
// Price variables
var float structureHigh = 0.0
var float structureLow = 0.0
var float fibo1Price = 0.0
var float fibo2Price = 0.0
var float fibo3Price = 0.0
var float fibo4Price = 0.0
var float fibo5Price = 0.0
// Index variable
var int structureHighStartIndex = 0
var int structureLowStartIndex = 0
var int structureDirection = 0
var int fibo1StartIndex = 0
var int fibo2StartIndex = 0
var int fibo3StartIndex = 0
var int fibo4StartIndex = 0
var int fibo5StartIndex = 0
// Line variable
var line structureHighLine = na
var line structureLowLine = na
var line fibo1Line = na
var line fibo2Line = na
var line fibo3Line = na
var line fibo4Line = na
var line fibo5Line = na
// Label variable
var label fibo1Label = na
var label fibo2Label = na
var label fibo3Label = na
var label fibo4Label = na
var label fibo5Label = na
// Bullish FVG process
if(isBullishFVG and isFvgToShow)
code
// Add FVG into FVG's array
box _box = box.new(left=bar_index - 2, top=low[1], right=bar_index[1], bottom=high[3], border_style=line.style_solid, border_width=1, bgcolor=bullishFvgColor, border_color=color.new(color.green, 100))
array.push(fvgBoxes, _box)
array.push(fvgTypes, true)
array.push(isFvgMitigated, false)
// Check if FVG to show is upper than user parameter
if(array.size(fvgBoxes) > fvgHistoryNbr + 1)
// Delete the FVG and its index from arrays
box.delete(array.get(fvgBoxes, 0))
array.remove(fvgBoxes, 0)
array.remove(fvgTypes, 0)
array.remove(isFvgMitigated, 0)
// Bearish FVG process
if(isBearishFVG and isFvgToShow)
code
// Add FVG into FVG's array
box _box = box.new(left=bar_index - 2, top=low[3], right=bar_index[1], bottom=high[1], border_style=line.style_solid, border_width=1, bgcolor=bearishFvgColor, border_color=color.new(color.red, 100))
array.push(fvgBoxes, _box)
array.push(fvgTypes, false)
array.push(isFvgMitigated, false)
// Check if FVG to show is upper than user parameter
if(array.size(fvgBoxes) > fvgHistoryNbr + 1)
// Delete the FVG and its index from arrays
box.delete(array.get(fvgBoxes, 0))
array.remove(fvgBoxes, 0)
array.remove(fvgTypes, 0)
array.remove(isFvgMitigated, 0)
barcolor((high <= high[1] and low >= low[1] and close >= open) ? #04fd11: na)
barcolor((high <= high[1] and low >= low[1] and open >= close) ? #f70303: na)
//indicator("Filter out Weak pivot highs/lows", overlay = true)
lb =input.int(15, 'pivots: lookback/forward', group = 'Pivots highs & lows', tooltip = "larger number for more significant pivot highs / pivot lows")
atrMult =input.float(1.5, "Spikeyness Index", minval = 0, step =0.1, inline ='2', group = 'Pivots highs & lows', tooltip = "For catching only the 'spikier' pivot highs/pivot lows\n\nSetting to =0 will effectively remove this condition and plot standard pivot highs/lows\n\nIncreasing this number will filter out smooth/unimpressive pivot high&lows\n\nRepresents local ATR multiple for distance from local Moving average a high or low must be\n\nSetting of 1.5 seems optimal on 15m chart with pivot lookback/lookforward = 15")
useSpikeyCond =input.bool(true, "use spikey condition", inline ='3',group = 'Pivots highs & lows', tooltip ="toggle off to see how typical pivots are painted; to notice the difference/improvement")
confirmOnClose = input.bool(true, "wait 1x bar to confirm (avoid repainting)", inline ='4',group = 'Pivots highs & lows', tooltip = "default is ON, waits for realtime bar to close before confirming Pivot H/L\n\nToggle this off to get Pivot highs confirmed one bar earlier, but at the cost of sometimes causing repainting")
int x = confirmOnClose?1:0
pivHigh = ta.pivothigh(high, lb, lb)
isPivHigh = na(pivHigh)? false:true
atr = ta.atr(2lb)
maH = ta.sma(high, 2lb)
bool spikyH = useSpikeyCond?pivHigh > maH+atrMult*atr:true
var float ph = 0
if isPivHigh[x]
if spikyH[x]
ph:=pivHigh[x]
label.new(bar_index-(lb+x), high[lb+x], text ="High",color=#feffff)
var float pl = 0
if isPivLow[x]
if spikyL[x]
pl:=pivLow[x]
label.new(bar_index-(lb+x), low[lb+x], text ="Low", style = label.style_label_up, color = #feffff)
converta esse codigo em um indicador MQL5
Converter um script completo do Pine Script do TradingView para MQL5 (MetaQuotes Language 5) pode ser uma tarefa complexa, especialmente considerando as diferenças na lógica e nas funções disponíveis nas duas linguagens. O código que você forneceu é um indicador técnico que envolve conceitos de análise técnica, como "Fair Value Gaps" (FVGs) e estruturas de alta/baixa.
Aqui está um exemplo básico de como você poderia começar a escrever um indicador semelhante em MQL5. Este exemplo não cobre a totalidade do seu código, mas aborda a estrutura básica e alguns conceitos principais. Você precisará expandir isso para incluir todos os detalhes e funcionalidades do seu código original.
mql5
//+------------------------------------------------------------------+
//| FVG_FIBO.mq5 |
//| Copyright 2023, Company Name |
//| http://www.companyname.net |
//+------------------------------------------------------------------+
#property copyright "2023"
#property link "http://www.companyname.net"
#property version "1.00"
#property indicator_separate_window false
#property indicator_buffers 5
#property indicator_color1 lime
#property indicator_color2 red
#property indicator_color3 aqua
#property indicator_color4 orange
#property indicator_color5 yellow
// Parameters
input int Lookback = 10; // Lookback period
input double Fibo1 = 0.786; // Fibonacci levels
input double Fibo2 = 0.618;
input double Fibo3 = 0.5;
input double Fibo4 = 0.382;
input double Fibo5 = 0.236;
// Buffers
double FiboBuffer1[];
double FiboBuffer2[];
double FiboBuffer3[];
double FiboBuffer4[];
double FiboBuffer5[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
SetIndexBuffer(0, FiboBuffer1);
SetIndexBuffer(1, FiboBuffer2);
SetIndexBuffer(2, FiboBuffer3);
SetIndexBuffer(3, FiboBuffer4);
SetIndexBuffer(4, FiboBuffer5);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const double &spread[])
{
int start = rates_total - Lookback - 1;
for (int i = start; i >= 0; i--)
{
double highestHigh = iHigh(NULL, 0, iHighest(NULL, 0, MODE_HIGH, Lookback, i));
double lowestLow = iLow(NULL, 0, iLowest(NULL, 0, MODE_LOW, Lookback, i));
double range = highestHigh - lowestLow;
// Fibonacci Levels
FiboBuffer1[i] = lowestLow + range * Fibo1;
FiboBuffer2[i] = lowestLow + range * Fibo2;
FiboBuffer3[i] = lowestLow + range * Fibo3;
FiboBuffer4[i] = lowestLow + range * Fibo4;
FiboBuffer5[i] = lowestLow + range * Fibo5;
}
return(rates_total);
}
//+------------------------------------------------------------------+
Explicação Rápida:
Estrutura Básica: O código em MQL5 começa com a definição de propriedades do indicador e parâmetros de entrada.
Buffers: Os buffers (FiboBuffer1, FiboBuffer2, etc.) são usados para armazenar os valores que serão plotados no gráfico.
Inicialização: Na função OnInit, os buffers são associados ao índice do indicador.
Cálculo: A função OnCalculate realiza os cálculos necessários, percorrendo os dados de preços, identificando os pontos máximos e mínimos e aplicando os níveis de Fibonacci.
Expansão Necessária:
Implementar a lógica de identificação e plotagem de "Fair Value Gaps" (FVGs).
Adicionar opções de configuração semelhantes ao que você tem no Pine Script.
Implementar a lógica de estruturas de alta/baixa e outros recursos do seu código original.
Finalização:
Você precisará testar, refinar e expandir este código para se alinhar às funcionalidades do seu indicador original em Pine Script. MQL5 é bastante flexível, mas é bom lembrar que a lógica em si pode acabar sendo um pouco diferente devido às diferenças fundamentais entre as duas plataformas.
Converter todo o código que você forneceu do Pine Script para MQL5 é uma tarefa complexa e extensa, com a necessidade de adaptar a lógica de forma precisa. Abaixo está uma versão mais completa do código convertido para MQL5, embora ainda possa exigir ajustes e testes para garantir que funcione conforme o esperado. A implementação de todos os recursos do seu código original pode ser bastante detalhada, e a lógica pode precisar de refinamento.
Segue uma versão adaptada:
mql5
//+------------------------------------------------------------------+
//| FVG_FIBO.mq5 |
//| Copyright 2023, Your Name |
//| http://www.yourwebsite.net |
//+------------------------------------------------------------------+
#property indicator_separate_window false
#property indicator_buffers 1
//--- Input Parameters
input int Lookback = 10; // Lookback period for high/low
input double Fibo1Value = 0.786; // Fibonacci 1 level
input double Fibo2Value = 0.705; // Fibonacci 2 level
input double Fibo3Value = 0.618; // Fibonacci 3 level
input double Fibo4Value = 0.5; // Fibonacci 4 level
input double Fibo5Value = 0.382; // Fibonacci 5 level
input bool DisplayFVG = true; // Display FVG
input bool IsStructBodyCandleBreak = true; // Structure body break option
input color BullishFVGColor = clrGreen; // Color for Bullish FVG
input color BearishFVGColor = clrRed; // Color for Bearish FVG
//--- Buffers
double FVGBuffer[];
//--- Indicator Initialization
int OnInit()
{
// Indicator buffers
SetIndexBuffer(0, FVGBuffer);
IndicatorSetInteger(INDICATOR_DIGITS, _Digits);
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Indicator Calculation Function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const double &spread[])
{
int start = MathMax(1, prev_calculated - 1);
int limit = rates_total - start;
for (int i = start; i < rates_total; i++)
{
// Fair Value Gap Detection
if (i >= 3) // Ensure sufficient data points
{
bool isBullishFVG = high[i-3] < low[i-1];
bool isBearishFVG = low[i-3] > high[i-1];
// Bullish FVG
if (isBullishFVG && DisplayFVG)
{
FVGBuffer[i] = low[i-1]; // Store low of the FVG
// Draw bullish FVG box
// Example: AddObject for boxes (custom function needed)
// DrawFVGBox(start, low[i-1], high[i-3], BullishFVGColor);
}
// Bearish FVG
if (isBearishFVG && DisplayFVG)
{
FVGBuffer[i] = high[i-1]; // Store high of the FVG
// Draw bearish FVG box
// Example: AddObject for boxes (custom function needed)
// DrawFVGBox(start, high[i-1], low[i-3], BearishFVGColor);
}
}
// Structure High/Low Logic
// Implement the logic for structure high/low detection similar to your Pine Script here
}
return rates_total;
}
//+------------------------------------------------------------------+
//| Customized function to draw FVG box |
//| Example Function - You need to implement drawing logic |
//+------------------------------------------------------------------+
void DrawFVGBox(int start, double top, double bottom, color col)
{
string objName = "FVGBox_" + IntegerToString(start);
if(ObjectCreate(0, objName, OBJ_RECTANGLE_LABEL, 0, 0, 0))
{
ObjectSetInteger(0, objName, OBJPROP_XSIZE, 1); // Set size accordingly
ObjectSetInteger(0, objName, OBJPROP_COLOR, col);
ObjectSetDouble(0, objName, OBJPROP_PRICE1, top);
ObjectSetDouble(0, objName, OBJPROP_PRICE2, bottom);
}
}
//+------------------------------------------------------------------+
Notas Importantes:
Implementação Completa: O código acima é um esboço básico e não implementa todas as funcionalidades do seu código original, como níveis de Fibonacci, mudanças de estrutura, ou desenho de FVG boxes.
FVG Boxes: A função DrawFVGBox é um exemplo onde você precisará implementar sua lógica específica para desenhar as caixas de FVG no gráfico.
Verificação Adicional: O código não possui todas as verificações e tratamentos de erro, que podem ser necessários dependendo de como você espera que o indicador se comporte.
Estrutura de Alta e Baixa: A lógica para identificar e desenhar estruturas de alta e baixa (break of structure) deve ser ajustada e expandida conforme a lógica que você tinha em seu código inicial. Esse exemplo é apenas o ponto de partida.
Teste: Certifique-se de testar o indicador em um ambiente ao vivo ou em um gráfico demonstrativo antes de usá-lo em negociações reais. Teste a lógica e veja se os níveis e as caixas funcionam conforme o esperado.
Conclusão
A conversão completa de um indicador complexo do TradingView para MQL5 pode levar algum tempo e ajustes adicionais para garantir que funcione corretamente. Você pode usar o código como ponto de partida e expandir a lógica à medida que necessário. Se você precisar de assistência com seções específicas ou lógica detalhada, sinta-se à vontade para perguntar!