#include <Trade\Trade.mqh> input double lotSize = 0.1; // Variáveis globais para…
- User
#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
// Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA
CTrade trade;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;
// Cálculo das Bandas de Bollinger double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda superior double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda inferior // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose);}
//+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }
if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); }}
//+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;
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 && IsNearBollingerMiddle(positionPrice, 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()); } } } }}
//+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 1); // Banda média return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }
//+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } }}
//+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } }}
erro:
'NASDAQ V2_007_Working.mq5' 1 Trade.mqh Object.mqh StdLibErr.mqh OrderInfo.mqh HistoryOrderInfo.mqh PositionInfo.mqh DealInfo.mqh 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 55 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 55 29 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 56 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 56 29 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 126 30 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 126 30 3 errors, 0 warnings 4 1
- Assistant
The errors you're encountering in the MQL5 code relate to the incorrect usage of the
iBandsfunction. This function is used to calculate the Bollinger Bands in MetaTrader 5. It seems you've got issues with the parameters specified for this function.Here's the correct syntax for calling the
iBandsfunction:int iBands( const string symbol, // symbol name ENUM_TIMEFRAMES timeframe, // timeframe int period, // averaging period int deviation, // deviation double bands_shift, // bands shift ENUM_APPLIED_PRICE applied_price // applied price );Here are the mistakes in your code:
- Incorrect number of parameters passed to the
iBandsfunction.
To fix these errors, you should update your calls to the
iBandsfunction to match its correct signature. Adjust them as follows:-
For
bollingerUpper:double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_UPPER); -
For
bollingerLower:double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_LOWER); -
For
bollingerMiddle:double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, MODE_MAIN);
Notice that
MODE_UPPER,MODE_LOWER, andMODE_MAINare indices to access the upper, lower, and middle lines of the Bollinger Bands. They are required to correctly specify which line value you want from theiBandscall.Make sure that these changes are made to the respective lines in your
OnTickfunction andIsNearBollingerMiddlefunction as they relate to the Bollinger Bands. By adjusting the parameters and specifying the correct modes, your Bollinger Band calculations should work correctly. - Incorrect number of parameters passed to the
- User
me responda em portugues, e me entregue o codigo completo corrigido:
#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
// Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA
CTrade trade;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;
// Cálculo das Bandas de Bollinger double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda superior double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 0); // Banda inferior // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose);}
//+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }
if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); }}
//+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;
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 && IsNearBollingerMiddle(positionPrice, 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()); } } } }}
//+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2.0, 0, PRICE_CLOSE, 1); // Banda média return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }
//+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } }}
//+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } }}
- Assistant
Claro! Vamos corrigir o uso das funções
iBandspara eliminar os erros referentes ao número incorreto de parâmetros. Aqui está o código corrigido:#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 // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA CTrade trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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; // Cálculo das Bandas de Bollinger double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_UPPER); double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_LOWER); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose); } //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); } if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); } } //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point; 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 && IsNearBollingerMiddle(positionPrice, 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()); } } } } } //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_MAIN); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; } //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } } } //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } } }Corrigi as chamadas da função
iBandspara utilizarMODE_UPPER,MODE_LOWEReMODE_MAIN, que indicam as bandas superior, inferior e média, respectivamente. Agora o código deve compilar corretamente e as bandas de Bollinger serão calculadas conforme esperado. - User
#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
// Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA
CTrade trade;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;
// Cálculo das Bandas de Bollinger double bollingerUpper = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_UPPER); double bollingerLower = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_LOWER); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose);}
//+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }
if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); }}
//+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;
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 && IsNearBollingerMiddle(positionPrice, 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()); } } } }}
//+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger double bollingerMiddle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE, MODE_MAIN); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }
//+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } }}
//+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } }}
erro:
'MODE_UPPER' - undeclared identifier NASDAQ V2_007_Working.mq5 55 79 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 55 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 55 29 'MODE_LOWER' - undeclared identifier NASDAQ V2_007_Working.mq5 56 79 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 56 29 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 56 29 'MODE_MAIN' - undeclared identifier NASDAQ V2_007_Working.mq5 126 80 'iBands' - wrong parameters count NASDAQ V2_007_Working.mq5 126 30 built-in: int iBands(const string,ENUM_TIMEFRAMES,int,int,double,int) NASDAQ V2_007_Working.mq5 126 30
- Assistant
Os erros que você está encontrando estão relacionados ao uso incorreto da função
iBandse dos identificadoresMODE_UPPER,MODE_LOWEReMODE_MAIN, que na verdade se aplicam à função de manipulação de indicadores na biblioteca MQL4. Em MQL5, a funçãoiBandsretorna um handle, e você deve usarCopyBufferpara obter os valores das bandas.Vamos corrigir o código para usar a abordagem correta em MQL5. Aqui está o código atualizado:
#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 // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA CTrade trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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; // Cálculo das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerUpper, bollingerLower, bollingerMiddle; CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 1, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 2, 0, 1, bollingerUpper); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose); } //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); } if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); } } //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point; 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 && IsNearBollingerMiddle(positionPrice, 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()); } } } } } //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerMiddle; CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; } //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } } } //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } } }O código acima foi corrigido para que ele utilize a função
CopyBufferpara obter os valores das bandas de Bollinger. Assim, você acessa corretamente as bandas superior, inferior e o meio em MQL5. As variáveisbollingerUpper,bollingerLowerebollingerMiddlesão usadas para armazenar esses valores após a cópia feita da buffer do indicador. - User
#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
// Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA
CTrade trade;
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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;
// Cálculo das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerUpper, bollingerLower, bollingerMiddle; CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 1, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 2, 0, 1, bollingerUpper); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper, bollingerLower); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose);}
//+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); }
if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); }}
//+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point;
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 && IsNearBollingerMiddle(positionPrice, 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()); } } } }}
//+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerMiddle; CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle); return price >= bollingerMiddle - slippage && price <= bollingerMiddle + slippage; }
//+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } }}
//+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } }}
erro:
'CopyBuffer' - no one of the overloads can be applied to the function call NASDAQ V2_007_Working.mq5 131 5
- Assistant
Os erros que você está enfrentando ocorrem porque a função
CopyBufferrequer uma matriz para armazenar os resultados, em vez de uma variável única. Precisamos alterar a maneira como estamos chamandoCopyBufferpara corrigir isso.Vamos corrigir essas chamadas e garantir que a alocação e o armazenamento das informações das bandas de Bollinger sejam tratados corretamente em buffers do tipo array. Aqui está o código corrigido:
#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 // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA CTrade trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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; // Cálculo das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerUpper[1], bollingerLower[1], bollingerMiddle[1]; CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 1, 0, 1, bollingerLower); CopyBuffer(bollingerHandle, 2, 0, 1, bollingerMiddle); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper[0], bollingerLower[0]); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose); } //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); } if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); } } //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point; 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 && IsNearBollingerMiddle(positionPrice, 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()); } } } } } //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerMiddle[1]; CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle); return price >= bollingerMiddle[0] - slippage && price <= bollingerMiddle[0] + slippage; } //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } } } //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } } }Agora utilizamos arrays (
bollingerUpper,bollingerLower,bollingerMiddle) para armazenar os valores daCopyBuffer, e acessamos os valores usando o índice[0]. Isso deve resolver os erros de compilação. - User
como aumentar a distancia de fechamento da orden?
- Assistant
Para aumentar a distância de fechamento de uma ordem, você pode ajustar a lógica que decide quando fechar as ordens lucrativas. No código atual, a decisão é baseada se o preço da posição está próximo da linha média das Bandas de Bollinger. Se você quer aumentar a "distância de fechamento", pode alterar os fatores que determinam essa proximidade. Isso pode ser feito ajustando o parâmetro
slippagena funçãoCloseProfitablePositions.Atualmente, o código verifica se o lucro da posição é positivo e se o preço está perto da linha média das Bandas de Bollinger usando a função
IsNearBollingerMiddle. Para aumentar a distância de fechamento, você pode alterar o valor doslippageou criar um novo parâmetro de entrada que permita ajustar essa distância com base na sua estratégia.Aqui está uma versão modificada do seu código com um parâmetro de entrada adicionado para controlar a distância de fechamento:
#include <Trade\Trade.mqh> input double lotSize = 0.1; input double closeDistanceMultiplier = 2.0; // Multiplicador para a distância de fechamento // 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 // Configurações de horário input int SHInput = 0; // Horário de início input int EHInput = 0; // Horário de fim input int InpMagic = 298347; // Identificação do EA CTrade trade; //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Função de finalização } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // 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; // Cálculo das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerUpper[1], bollingerLower[1], bollingerMiddle[1]; CopyBuffer(bollingerHandle, 0, 0, 1, bollingerUpper); CopyBuffer(bollingerHandle, 1, 0, 1, bollingerLower); CopyBuffer(bollingerHandle, 2, 0, 1, bollingerMiddle); // Atualizar informações de rompimento e confirmação UpdateBreakouts(priceClose, priceHigh, priceLow, bollingerUpper[0], bollingerLower[0]); // Fechar posições lucrativas CloseProfitablePositions(); // Gerenciamento de trailing stop TrailStop(); // Condições de abertura de ordens OpenOrders(priceClose); } //+------------------------------------------------------------------+ //| Atualizar informações de rompimento | //+------------------------------------------------------------------+ void UpdateBreakouts(double priceClose, double priceHigh, double priceLow, double bollingerUpper, double bollingerLower) { if (priceHigh - priceLow >= 30 * _Point && priceClose > bollingerUpper) { lastBreakoutAlta = true; breakoutHigh = priceHigh; Print("Possível rompimento de alta detectado."); } if (priceHigh - priceLow >= 30 * _Point && priceClose < bollingerLower) { lastBreakoutBaixa = true; breakoutLow = priceLow; Print("Possível rompimento de baixa detectado."); } } //+------------------------------------------------------------------+ //| Fechar posições lucrativas | //+------------------------------------------------------------------+ void CloseProfitablePositions() { double slippage = 3 * _Point * closeDistanceMultiplier; 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 && IsNearBollingerMiddle(positionPrice, 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()); } } } } } //+------------------------------------------------------------------+ //| Verifica se o preço está próximo da linha média da Banda de Bollinger | //+------------------------------------------------------------------+ bool IsNearBollingerMiddle(double price, double slippage) { // Cálculo da linha média das Bandas de Bollinger int bollingerHandle = iBands(_Symbol, PERIOD_M2, 20, 2, 0, PRICE_CLOSE); double bollingerMiddle[1]; CopyBuffer(bollingerHandle, 1, 0, 1, bollingerMiddle); return price >= bollingerMiddle[0] - slippage && price <= bollingerMiddle[0] + slippage; } //+------------------------------------------------------------------+ //| Função para abrir ordens | //+------------------------------------------------------------------+ void OpenOrders(double priceClose) { 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()); } } } //+------------------------------------------------------------------+ //| Gerenciamento de trailing stop | //+------------------------------------------------------------------+ void 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."); } } } } } }Com esse ajuste, você pode controlar a distância de fechamento alterando o valor do parâmetro
closeDistanceMultiplier. Quanto maior for esse valor, maior será a distância antes de uma posição ser considerada próxima o suficiente para fechar.