// Configurações de trailing stop
input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado
input int TslPoints = 10; // Trailing stop em pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
code
Assistant
User
esta implementação esta sendo tanto para caasos de vendacomo de compra? ou seja na alta e baixa?
Assistant
Sim, a implementação considera tanto a abertura de posições de compra quanto de venda, verificando a direção da tendência no gráfico H1 para ambas as situações. Vamos recapitular como o código funciona para cada caso:
Verificação da Tendência Macro em H1:
Usa uma média móvel simples (SMA) de 20 períodos para determinar a tendência no gráfico H1.
Define tendenciaH1Alta como true se o preço de fechamento atual estiver acima da SMA, o que indica uma tendência de alta.
Define tendenciaH1Baixa como true se o preço de fechamento atual estiver abaixo da SMA, o que indica uma tendência de baixa.
User
Assistant
// Configurações das Bandas de Bollinger (período 20, desvio 2)
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0)
{
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
// Verifica se a posição está no lucro e se o preço está perto da linha do meio
if (positionProfit > 0 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
{
if (trade.PositionClose(positionTicket))
{
Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
// Atualizar informações de rompimento e confirmação
if (lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0]) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0]) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
// Gerenciamento de trailing stop
TrailStop();
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
{
ulong ticket = PositionGetTicket(i);
double currentSL = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
{
double newSL = bid - TslPoints * _Point;
if (newSL > currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de compra.");
}
}
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
{
double newSL = ask + TslPoints * _Point;
if (newSL < currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de venda.");
}
}
}
}
}
}
alem das regras ja existe no codigo sobre abertua de orden, quero que leve em consideração a endencia macro de H1 abra ordens em M2 somente se em H1 estiver na mesma tendencia H1 e M2 precisam esta na mesma tendencia e evite abrir ordens caso houver divergencia.por exemplo sem H1 estiver em alta procura abrir ordens em M2 caso preço esteja acima da media de 20 ou espere dar os sinais de rompimento das laterais da banda de bollinger como ja tem no codigo.
adicione essa implementação no codigo e me entregue completo.
Para adicionar a consideração da tendência macro de H1 às suas regras de abertura de ordens no gráfico M2, podemos implementar a verificação da média móvel simples (SMA) de 20 períodos no gráfico H1. A ideia é comparar o preço de fechamento atual com esta média para determinar a tendência macro. Aqui está o código atualizado com essa lógica implementada:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
// Variáveis para armazenar rompimento anterior
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
// Configurações de trailing stop
input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado
input int TslPoints = 10; // Trailing stop em pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Verificação da tendência macro de H1
bool tendenciaH1Alta, tendenciaH1Baixa;
VerificarTendenciaH1(tendenciaH1Alta, tendenciaH1Baixa);
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
// Configurações das Bandas de Bollinger (período 20, desvio 2)
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0)
{
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
// Verifica se a posição está no lucro e se o preço está perto da linha do meio
if (positionProfit > 0 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
{
if (trade.PositionClose(positionTicket))
{
Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
// Atualizar informações de rompimento e confirmação
if (tendenciaH1Alta && lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (tendenciaH1Baixa && lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && tendenciaH1Alta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && tendenciaH1Baixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
// Gerenciamento de trailing stop
TrailStop();
}
//+------------------------------------------------------------------+
//| Verificar tendência macro de H1 |
//+------------------------------------------------------------------+
void VerificarTendenciaH1(bool &tendenciaH1Alta, bool &tendenciaH1Baixa)
{
// Calcular a SMA de 20 períodos no gráfico H1
int smaPeriod = 20;
double smaValue = iMA(_Symbol, PERIOD_H1, smaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
double priceCloseH1 = iClose(_Symbol, PERIOD_H1, 0);
tendenciaH1Alta = priceCloseH1 > smaValue;
tendenciaH1Baixa = priceCloseH1 < smaValue;
}
//+------------------------------------------------------------------+
//| Gerenciamento de trailing stop |
//+------------------------------------------------------------------+
void TrailStop()
{
CTrade trade;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
{
ulong ticket = PositionGetTicket(i);
double currentSL = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
{
double newSL = bid - TslPoints * _Point;
if (newSL > currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de compra.");
}
}
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
{
double newSL = ask + TslPoints * _Point;
if (newSL < currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de venda.");
}
}
}
}
}
}
Principais alterações:
Verificação da Tendência H1: Adicionamos a função VerificarTendenciaH1(), que calcula a média móvel simples (SMA) de 20 períodos no gráfico H1. Isso nos ajuda a determinar se a tendência macro está em alta ou em baixa.
Condições de Abertura de Ordem: As ordens só serão abertas no gráfico M2 se a tendência em H1 for compatível. Isso é verificado usando as variáveis tendenciaH1Alta e tendenciaH1Baixa, derivadas da comparação do preço de fechamento com a SMA de H1.
Verificações de Rompimento: Além das verificações já existentes de rompimento pelas bandas de Bollinger, agora verificamos se a tendência em H1 está de acordo antes de definir as variáveis lastBreakoutAlta ou lastBreakoutBaixa.
Essa abordagem garante que as decisões de trading considerem as tendências maiores, evitando operações contra a tendência macro.
Condições para Abrir Posições de Compra (Alta):
O código verifica a variável tendenciaH1Alta junto com os sinais de rompimento de alta das bandas de Bollinger (preço de fechamento acima do limite superior).
Uma ordem de compra é aberta somente se ambos os sinais (rompimento de alta em M2 e tendência de alta em H1) estiverem presentes.
Condições para Abrir Posições de Venda (Baixa):
O código verifica a variável tendenciaH1Baixa junto com os sinais de rompimento de baixa das bandas de Bollinger (preço de fechamento abaixo do limite inferior).
Uma ordem de venda é aberta somente se ambos os sinais (rompimento de baixa em M2 e tendência de baixa em H1) estiverem presentes.
Dessa forma, o código garante que as decisões de trading no gráfico M2 estão alinhadas com a tendência macro observada no gráfico H1, tanto para operações de compra (alta) como de venda (baixa). Se uma divergência entre os sinais de M2 e H1 ocorrer, não será aberta nenhuma ordem, conforme sua solicitação.
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
// Configurações de trailing stop
input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado
input int TslPoints = 10; // Trailing stop em pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Verificação da tendência macro de H1
bool tendenciaH1Alta, tendenciaH1Baixa;
VerificarTendenciaH1(tendenciaH1Alta, tendenciaH1Baixa);
code
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
// Configurações das Bandas de Bollinger (período 20, desvio 2)
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0)
{
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
// Verifica se a posição está no lucro e se o preço está perto da linha do meio
if (positionProfit > 0 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
{
if (trade.PositionClose(positionTicket))
{
Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
// Atualizar informações de rompimento e confirmação
if (tendenciaH1Alta && lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (tendenciaH1Baixa && lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && tendenciaH1Alta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && tendenciaH1Baixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
// Gerenciamento de trailing stop
TrailStop();
}
//+------------------------------------------------------------------+
//| Verificar tendência macro de H1 |
//+------------------------------------------------------------------+
void VerificarTendenciaH1(bool &tendenciaH1Alta, bool &tendenciaH1Baixa)
{
// Calcular a SMA de 20 períodos no gráfico H1
int smaPeriod = 20;
double smaValue = iMA(_Symbol, PERIOD_H1, smaPeriod, 0, MODE_SMA, PRICE_CLOSE, 0);
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionGetTicket(i) > 0 && PositionSelectByTicket(PositionGetTicket(i)))
{
ulong ticket = PositionGetTicket(i);
double currentSL = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
{
double newSL = bid - TslPoints * _Point;
if (newSL > currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de compra.");
}
}
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
{
double newSL = ask + TslPoints * _Point;
if (newSL < currentSL || currentSL == 0)
{
trade.PositionModify(ticket, newSL, tp);
Print("Trailing Stop atualizado para posição de venda.");
}
}
}
}
}
}
erro:
'NASDAQ_010.mq5' 1
Trade.mqh
Object.mqh
StdLibErr.mqh
OrderInfo.mqh
HistoryOrderInfo.mqh
PositionInfo.mqh
DealInfo.mqh
possible loss of data due to type conversion NASDAQ_010.mq5 54 57
'iMA' - wrong parameters count NASDAQ_010.mq5 166 23
built-in: int iMA(const string,ENUM_TIMEFRAMES,int,int,ENUM_MA_METHOD,int) NASDAQ_010.mq5 166 23
1 errors, 1 warnings 2 2
A mensagem de erro e aviso que você está recebendo indica problemas no código que precisam ser corrigidos:
Aviso de possível perda de dados devido à conversão de tipos (linha 54): Isso pode estar relacionado ao uso de diferentes tipos de dados numéricos, como double e int. É uma boa prática garantir que as operações numéricas envolvam tipos de dados compatíveis ou que a conversão de tipos seja feita de forma explícita.
Erro de parâmetros incorretos na chamada de iMA (linha 166): Esta função está sendo chamada com o número errado de argumentos. Vamos corrigir ambos os problemas:
Alteração Código Corrigido
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
// Variáveis globais para controle de ordens
bool orderOpened = false;
ulong orderTicket = 0;
// Variáveis para armazenar rompimento anterior
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
// Configurações de trailing stop
input int TslTriggerPoints = 15; // Pontos de lucro antes do trailing stop ser ativado
input int TslPoints = 10; // Trailing stop em pips
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configurações do EA
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
// Função de finalização
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Verificação da tendência macro de H1
bool tendenciaH1Alta, tendenciaH1Baixa;
VerificarTendenciaH1(tendenciaH1Alta, tendenciaH1Baixa);
// Variáveis para bandas de Bollinger
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
// Configurações das Bandas de Bollinger (período 20, desvio 2)
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
// Obtenção das Bandas de Bollinger
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
// Verifique se o handle é válido
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
// Inicializar os buffers das bandas de Bollinger
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
// Preencher os buffers
if (CopyBuffer(bbHandle, 0, 0, 1, bollingerUpper) <= 0 ||
CopyBuffer(bbHandle, 1, 0, 1, bollingerMiddle) <= 0 ||
CopyBuffer(bbHandle, 2, 0, 1, bollingerLower) <= 0) {
Print("Erro ao copiar buffer das Bandas de Bollinger: ", GetLastError());
return;
}
// Preço atual e range da vela
double priceHigh = iHigh(_Symbol, PERIOD_M2, 0);
double priceLow = iLow(_Symbol, PERIOD_M2, 0);
double priceClose = iClose(_Symbol, PERIOD_M2, 0);
double range = priceHigh - priceLow;
// Objeto para enviar ordens
CTrade trade;
// Fechar todas as posições no lucro se o preço estiver perto da linha do meio da Banda de Bollinger
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(i))
{
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
// Verifica se a posição está no lucro e se o preço está perto da linha do meio
if (positionProfit > 0 && positionPrice >= bollingerMiddle[0] - slippage && positionPrice <= bollingerMiddle[0] + slippage)
{
if (trade.PositionClose(positionTicket))
{
Print("Posição lucrativa fechada perto da linha central da Banda de Bollinger. Ticket: ", positionTicket);
}
else
{
Print("Erro ao fechar a posição: ", GetLastError());
}
}
}
}
// Atualizar informações de rompimento e confirmação
if (tendenciaH1Alta && lastBreakoutAlta && priceClose > breakoutHigh)
{
double slBuy = priceClose - 10 * _Point;
if (trade.Buy(lotSize, _Symbol, slBuy))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de compra aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutAlta = false;
}
else
{
Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
if (tendenciaH1Baixa && lastBreakoutBaixa && priceClose < breakoutLow)
{
double slSell = priceClose + 10 * _Point;
if (trade.Sell(lotSize, _Symbol, slSell))
{
orderOpened = true;
orderTicket = trade.ResultOrder();
Print("Ordem de venda aberta com sucesso após confirmação! Ticket: ", orderTicket);
lastBreakoutBaixa = false;
}
else
{
Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Verificar rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && tendenciaH1Alta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
}
// Verificar rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && tendenciaH1Baixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
}
// Gerenciamento de trailing stop
TrailStop();
}
//+------------------------------------------------------------------+
//| Verificar tendência macro de H1 |
//+------------------------------------------------------------------+
void VerificarTendenciaH1(bool &tendenciaH1Alta, bool &tendenciaH1Baixa)
{
// Calcular a SMA de 20 períodos no gráfico H1
int smaPeriod = 20;
double smaValue = iMA(_Symbol, PERIOD_H1, smaPeriod, 0, MODE_SMA, PRICE_CLOSE);
double priceCloseH1 = iClose(_Symbol, PERIOD_H1, 0);
tendenciaH1Alta = priceCloseH1 > smaValue;
tendenciaH1Baixa = priceCloseH1 < smaValue;
}
//+------------------------------------------------------------------+
//| Gerenciamento de trailing stop |
//+------------------------------------------------------------------+
void TrailStop()
{
CTrade trade;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (PositionSelect(i))
{
ulong ticket = PositionGetTicket(i);
double currentSL = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
{
if (bid - PositionGetDouble(POSITION_PRICE_OPEN) > TslTriggerPoints * _Point)
{
double newSL = bid - TslPoints * _Point;
if (newSL > currentSL || currentSL == 0)
{
if (trade.PositionModify(ticket, newSL, tp))
{
Print("Trailing Stop atualizado para posição de compra.");
}
else
{
Print("Erro ao atualizar Trailing Stop: ", GetLastError());
}
}
}
}
else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
{
if (PositionGetDouble(POSITION_PRICE_OPEN) - ask > TslTriggerPoints * _Point)
{
double newSL = ask + TslPoints * _Point;
if (newSL < currentSL || currentSL == 0)
{
if (trade.PositionModify(ticket, newSL, tp))
{
Print("Trailing Stop atualizado para posição de venda.");
}
else
{
Print("Erro ao atualizar Trailing Stop: ", GetLastError());
}
}
}
}
}
}
}
Correções Feitas:
Erro de iMA: A função iMA() no MQL5 não possui o sexto parâmetro (o último parâmetro era desnecessário). Removi o parámetro adicional.
Uso de PositionSelect: Substitute PositionGetTicket(i) > 0 com PositionSelect(i) para garantir que a seleção da posição está correta.
Tratamento de Possível Perda de Dados: Cuidado ao lidar com operações que envolvem _Point e certifique-se de que os cálculos com variáveis de tipos diferentes são apropriados. Não há alterações específicas aqui, pois a operação era bastante direta, mas esteja ciente de possíveis conversões implícitas.
Essas correções devem ajudar a resolver os erros e assegurar que o código funcione conforme esperado.