The error you're encountering is because SymbolInfoDouble requires a specific property of the symbol to be passed as an argument, and there might be issues if it's not used correctly in your code. In your particular case, you've written something similar to:
User
meresponda em portugues
voce consegue corrigir esse problema no meu codigo?
Assistant
Claro! Vamos tentar corrigir o problema no seu código.
Pelo erro que você mencionou, parece que há um problema na chamada da função . Vamos revisar algumas partes do código para garantir que está tudo correto.
User
Assistant
User
Assistant
User
existe outra alternativa para acabar com esse problema?
Assistant
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
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;
}
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;
CTrade trade;
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (PositionSelectByTicket(PositionGetTicket(i))) {
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
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());
}
}
}
}
double spread = SymbolInfoDouble(_Symbol, SYMBOL_SPREAD) * _Point;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
// Rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
double buyStopPrice = priceHigh + 5 * _Point + spread;
if (ask > buyStopPrice - OrderDistPoints * _Point) return;
double slBuy = buyStopPrice - Slpoints * _Point;
double tpBuy = buyStopPrice + Tppoints * _Point;
double lots = calcLots(slBuy - buyStopPrice);
if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
double sellStopPrice = priceLow - 5 * _Point - spread;
if (bid < sellStopPrice + OrderDistPoints * _Point) return;
double slSell = sellStopPrice + Slpoints * _Point;
double tpSell = sellStopPrice - Tppoints * _Point;
double lots = calcLots(slSell - sellStopPrice);
if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
TrailStop();
These lines are correct in terms of syntax as far as the SymbolInfoDouble function is used in MQL5, assuming _Symbol and the constant values (SYMBOL_SPREAD, SYMBOL_ASK, SYMBOL_BID) are being used correctly.
However, the issue might be related to either the include directives or the environment setup. Here are some things to check or try:
Check the Include Path:
Ensure that the path or inclusion of <Trade\Trade.mqh> is correct and that it provides the necessary definitions. This include file should provide definitions related to trading operations including CTrade.
Environment Check:
Make sure that you're actually compiling this with the correct version of MetaTrader which supports MQL5. If you are in a MetaEditor or a similar environment, make sure the logs don't show any loading issues with other included files.
Libraries and Environment Support:
Double-check if the library that provides SymbolInfoDouble and related constants are correctly linked and you've got the latest or compatible version of the environment (like MetaTrader 5).
Function Overrides:
Although likely not the cause, ensure there isn't any redefinition or macro that overrides SymbolInfoDouble elsewhere, causing conflict or confusion.
MetaTrader Version:
Ensure that you are using a platform that fully supports all the features used in the MQL5 language, as some trading platforms might have different sets of supported features based on their updates.
If none of these solve the problem, it would be useful to know exactly which version of MetaTrader you are using and make sure it is fully updated, as there might be newer versions of MetaTrader or MQL5 that include additional functionalities or improvements for better error handling and clearer debugging.
SymbolInfoDouble
Possíveis Soluções:
Verifique o nome da função e parâmetros:
Certifique-se de que os parâmetros passados estão corretos. Por exemplo, SymbolInfoDouble deve receber o símbolo e uma constante como SYMBOL_SPREAD, SYMBOL_ASK, ou SYMBOL_BID.
Verifique a biblioteca e constantes:
Certifique-se de que as constantes como SYMBOL_SPREAD, SYMBOL_ASK e SYMBOL_BID estão definidas e disponíveis no contexto do seu script. Às vezes, isso ocorre se há problemas com o arquivo de inclusão ou a versão do MetaEditor.
Alternativa para depuração:
Tente adicionar uma verificação de erro após a chamada SymbolInfoDouble para ver se isso lhe dá mais informações:
cpp
double spread = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
Print("Erro ao obter o spread: ", GetLastError());
}
spread *= _Point;
Isso adiciona uma verificação para garantir que SymbolInfoDouble seja bem-sucedido. Faça o mesmo para SYMBOL_ASK e SYMBOL_BID.
Atualização do Ambiente:
Certifique-se de que você está usando a versão mais recente do MetaTrader 5 e do MetaEditor. Assegure-se também de que não há problemas com a instalação do seu ambiente que poderiam estar causando este erro.
Recompile e teste:
Depois de fazer essas alterações, recompile o seu código e execute-o novamente para verificar se o problema persiste.
Código Atualizado com Verificação de Erro:
Você pode modificar a seção relevante do seu código da seguinte forma:
cpp
double spread = 0.0, ask = 0.0, bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
Print("Erro ao obter spread: ", GetLastError());
return;
}
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
Print("Erro ao obter ASK: ", GetLastError());
return;
}
if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter BID: ", GetLastError());
return;
}
spread *= _Point;
Com essas alterações, você recebe informações detalhadas sobre possíveis erros ao chamar SymbolInfoDouble, o que pode ajudar a diagnosticar problemas potenciais no ambiente ou na chamada da função.
faça essa correção e me entregue ocodigo completo:
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
input double RiskPercent = 3;
input int TslTriggerPoints = 15;
input int TslPoints = 10;
input int OrderDistPoints = 30;
input int Tppoints = 200;
input int Slpoints = 200;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (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 modificado para compra. Novo SL: ", newSL);
}
}
} 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 modificado para venda. Novo SL: ", newSL);
}
}
}
}
}
}
Claro! Vamos ajustar o seu código para incluir verificações de erro após as chamadas de SymbolInfoDouble e garantir que os valores desejados sejam obtidos corretamente antes de prosseguir. Aqui está o código corrigido:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
input double RiskPercent = 3;
input int TslTriggerPoints = 15;
input int TslPoints = 10;
input int OrderDistPoints = 30;
input int Tppoints = 200;
input int Slpoints = 200;
bool orderOpened = false;
ulong orderTicket = 0;
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
void OnTick()
{
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
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;
}
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;
CTrade trade;
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (PositionSelectByTicket(PositionGetTicket(i))) {
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
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());
}
}
}
}
double spread = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
Print("Erro ao obter spread: ", GetLastError());
return;
}
spread *= _Point;
double ask = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
Print("Erro ao obter ASK: ", GetLastError());
return;
}
double bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter BID: ", GetLastError());
return;
}
// Rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
double buyStopPrice = priceHigh + 5 * _Point + spread;
if (ask > buyStopPrice - OrderDistPoints * _Point) return;
double slBuy = buyStopPrice - Slpoints * _Point;
double tpBuy = buyStopPrice + Tppoints * _Point;
double lots = calcLots(slBuy - buyStopPrice);
if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
double sellStopPrice = priceLow - 5 * _Point - spread;
if (bid < sellStopPrice + OrderDistPoints * _Point) return;
double slSell = sellStopPrice + Slpoints * _Point;
double tpSell = sellStopPrice - Tppoints * _Point;
double lots = calcLots(slSell - sellStopPrice);
if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
TrailStop();
}
double calcLots(double slPoints)
{
double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
double ticksize = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, ticksize)) {
Print("Erro ao obter TICK SIZE: ", GetLastError());
return 0.0;
}
double tickvalue = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickvalue)) {
Print("Erro ao obter TICK VALUE: ", GetLastError());
return 0.0;
}
double lotstep = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotstep)) {
Print("Erro ao obter VOLUME STEP: ", GetLastError());
return 0.0;
}
double minvolume = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minvolume)) {
Print("Erro ao obter VOLUME MIN: ", GetLastError());
return 0.0;
}
double maxvolume = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxvolume)) {
Print("Erro ao obter VOLUME MAX: ", GetLastError());
return 0.0;
}
double moneyPerLotstep = (slPoints / ticksize) * tickvalue * lotstep;
double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
lots = MathMin(MathMax(lots, minvolume), maxvolume);
return NormalizeDouble(lots, 2);
}
void TrailStop()
{
CTrade trade;
double ask = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
Print("Erro ao obter ASK: ", GetLastError());
return;
}
double bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter BID: ", GetLastError());
return;
}
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (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) {
if (trade.PositionModify(ticket, newSL, tp)) {
Print("Trailing Stop modificado para compra. Novo SL: ", newSL);
} else {
Print("Erro ao modificar Trailing Stop para compra. Ticket: ", ticket);
}
}
}
} 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 modificado para venda. Novo SL: ", newSL);
} else {
Print("Erro ao modificar Trailing Stop para venda. Ticket: ", ticket);
}
}
}
}
}
}
}
As alterações feitas consistem em adicionar verificações para garantir que SymbolInfoDouble foi chamado com sucesso. Isso ajudará a identificar onde o código pode estar falhando e fornecerá mensagens úteis de erro.
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
input double RiskPercent = 3;
input int TslTriggerPoints = 15;
input int TslPoints = 10;
input int OrderDistPoints = 30;
input int Tppoints = 200;
input int Slpoints = 200;
// Asegure-se de obter todos os valores necessários para o cálculo de lotes
if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, ticksize) ||
!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickvalue) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotstep) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minvolume) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxvolume))
{
Print("Erro ao obter informações de símbolo para cálculo de lotes: ", GetLastError());
return 0.0; // Retorna zero se falhar no cálculo das informações
}
double moneyPerLotstep = (slPoints / ticksize) * tickvalue * lotstep;
double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
lots = MathMin(MathMax(lots, minvolume), maxvolume);
return NormalizeDouble(lots, 2);
}
void TrailStop()
{
CTrade trade;
code
double ask = 0.0;
double bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) ||
!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid))
{
Print("Erro ao obter preços de mercado: ", GetLastError());
return;
}
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (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 modificado para compra. Novo SL: ", newSL);
}
}
} 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 modificado para venda. Novo SL: ", newSL);
}
}
}
}
}
}
erro:
'NASDAQ V2_003_.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 V2_003_.mq5 34 57
'SymbolInfoDouble' - no one of the overloads can be applied to the function call NASDAQ V2_003_.mq5 78 10
could be one of 2 function(s) NASDAQ V2_003_.mq5 78 10
built-in: double SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE) NASDAQ V2_003_.mq5 78 10
built-in: bool SymbolInfoDouble(const string,ENUM_SYMBOL_INFO_DOUBLE,double&) NASDAQ V2_003_.mq5 78 10
1 errors, 1 warnings 2 2
Para corrigir os erros mencionados no seu código, precisamos prestar atenção em duas áreas principais: a função SymbolInfoDouble e o tipo de conversão que pode causar a perda de dados. Vamos abordar ambos os problemas.
1. Ajuste no uso da função SymbolInfoDouble
Você está tentando usar a função SymbolInfoDouble incorretamente. Para obter um valor em uma variável passada por referência, a função deve ser chamada com a assinatura que retorna um bool e recebe um double por referência. Precisamos garantir que estamos utilizando corretamente.
2. Possível perda de dados por conversão de tipo
Vamos revisar e garantir que todos os cálculos ou atribuições de variáveis estejam adequados, especialmente onde tipos de dados diferentes interagem.
Aqui está o código corrigido:
cpp
#include <Trade\Trade.mqh>
input double lotSize = 0.1;
input double RiskPercent = 3;
input int TslTriggerPoints = 15;
input int TslPoints = 10;
input int OrderDistPoints = 30;
input int Tppoints = 200;
input int Slpoints = 200;
bool orderOpened = false;
ulong orderTicket = 0;
bool lastBreakoutAlta = false;
bool lastBreakoutBaixa = false;
double breakoutHigh = 0.0;
double breakoutLow = 0.0;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
void OnTick()
{
double bollingerUpper[], bollingerLower[], bollingerMiddle[];
int bbPeriod = 20;
double bbDeviation = 2.0;
double slippage = 3 * _Point;
int bbHandle = iBands(_Symbol, PERIOD_M2, bbPeriod, bbDeviation, 0, PRICE_CLOSE);
if (bbHandle == INVALID_HANDLE) {
Print("Erro ao obter handle das Bandas de Bollinger: ", GetLastError());
return;
}
ArraySetAsSeries(bollingerUpper, true);
ArraySetAsSeries(bollingerMiddle, true);
ArraySetAsSeries(bollingerLower, true);
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;
}
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;
CTrade trade;
// Checando as posições existentes
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (PositionSelectByTicket(PositionGetTicket(i))) {
ulong positionTicket = PositionGetTicket(i);
double positionProfit = PositionGetDouble(POSITION_PROFIT);
double positionPrice = PositionGetDouble(POSITION_PRICE_CURRENT);
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());
}
}
}
}
// Obtendo os valores de spread, ask e bid
double spread = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_SPREAD, spread)) {
Print("Erro ao obter informações sobre o spread: ", GetLastError());
return;
}
spread *= _Point;
double ask = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask)) {
Print("Erro ao obter o preço de oferta: ", GetLastError());
return;
}
double bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid)) {
Print("Erro ao obter o preço de demanda: ", GetLastError());
return;
}
// Rompimento de alta
if (range >= 30 * _Point && priceClose > bollingerUpper[0] && !lastBreakoutAlta) {
lastBreakoutAlta = true;
breakoutHigh = priceHigh;
Print("Possível rompimento de alta detectado.");
double buyStopPrice = priceHigh + 5 * _Point + spread;
if (ask > buyStopPrice - OrderDistPoints * _Point) return;
double slBuy = buyStopPrice - Slpoints * _Point;
double tpBuy = buyStopPrice + Tppoints * _Point;
double lots = calcLots(slBuy - buyStopPrice);
if (trade.BuyStop(lots, buyStopPrice, _Symbol, slBuy, tpBuy)) {
Print("Ordem pendente de compra (buy stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de compra: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
// Rompimento de baixa
if (range >= 30 * _Point && priceClose < bollingerLower[0] && !lastBreakoutBaixa) {
lastBreakoutBaixa = true;
breakoutLow = priceLow;
Print("Possível rompimento de baixa detectado.");
double sellStopPrice = priceLow - 5 * _Point - spread;
if (bid < sellStopPrice + OrderDistPoints * _Point) return;
double slSell = sellStopPrice + Slpoints * _Point;
double tpSell = sellStopPrice - Tppoints * _Point;
double lots = calcLots(slSell - sellStopPrice);
if (trade.SellStop(lots, sellStopPrice, _Symbol, slSell, tpSell)) {
Print("Ordem pendente de venda (sell stop) configurada com sucesso.");
} else {
Print("Erro ao configurar ordem pendente de venda: ", trade.ResultRetcode(), " - ", GetLastError());
}
}
TrailStop();
}
double calcLots(double slPoints)
{
double risk = AccountInfoDouble(ACCOUNT_BALANCE) * RiskPercent / 100;
double ticksize = 0.0, tickvalue = 0.0, lotstep = 0.0, minvolume = 0.0, maxvolume = 0.0;
// Asegure-se de obter todos os valores necessários para o cálculo de lotes
if (!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE, ticksize) ||
!SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE, tickvalue) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP, lotstep) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN, minvolume) ||
!SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX, maxvolume))
{
Print("Erro ao obter informações de símbolo para cálculo de lotes: ", GetLastError());
return 0.0; // Retorna zero se falhar no cálculo das informações
}
double moneyPerLotstep = (MathAbs(slPoints) / ticksize) * tickvalue * lotstep; // Certifique-se de que slPoints é positivo
if(moneyPerLotstep <= 0)
{
Print("Erro no cálculo do moneyPerLotstep. Verifique os valores de entrada.");
return 0.0;
}
double lots = MathFloor(risk / moneyPerLotstep) * lotstep;
lots = MathMin(MathMax(lots, minvolume), maxvolume);
return NormalizeDouble(lots, 2);
}
void TrailStop()
{
CTrade trade;
double ask = 0.0;
double bid = 0.0;
if (!SymbolInfoDouble(_Symbol, SYMBOL_ASK, ask) ||
!SymbolInfoDouble(_Symbol, SYMBOL_BID, bid))
{
Print("Erro ao obter preços de mercado: ", GetLastError());
return;
}
for (int i = PositionsTotal() - 1; i >= 0; i--) {
if (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) {
if (trade.PositionModify(ticket, newSL, tp)) {
Print("Trailing Stop modificado para compra. Novo SL: ", newSL);
} else {
Print("Erro ao modificar Trailing Stop para compra. Ticket: ", ticket);
}
}
}
} 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 modificado para venda. Novo SL: ", newSL);
} else {
Print("Erro ao modificar Trailing Stop para venda. Ticket: ", ticket);
}
}
}
}
}
}
}
Notas Importantes:
Eu adicionei verificações adicionais para garantir que moneyPerLotstep seja sempre positivo. Isso resolverá quaisquer problemas que possam surgir de cálculos com slPoints negativos.
Todas as chamadas a SymbolInfoDouble agora garantem que o valor é obtido corretamente e são acompanhadas de verificações de erros para diagnóstico mais fácil.
Sim, além de garantir que a função SymbolInfoDouble está sendo usada corretamente, você pode adotar algumas outras abordagens para resolver ou contornar os problemas mencionados. Aqui estão algumas sugestões que podem ajudar a eliminar o erro e tornar seu código mais robusto:
1. Verificar a Versão do MetaTrader
Certifique-se de que você está usando a versão mais recente do MetaTrader 5. Algumas funções e constantes podem ter atualizações ou correções em versões mais recentes do software.
2. Revisar o Ambiente de Desenvolvimento
Verifique se o ambiente de desenvolvimento está configurado corretamente e se todos os arquivos de inclusão necessários (como <Trade\Trade.mqh>) estão disponíveis e sem erros.
3. Depuração Manual
Adicione mensagens de depuração (usando Print) para inspecionar os valores retornados a cada etapa, o que pode ajudar a identificar rapidamente onde o problema ocorre:
Se ainda estiver enfrentando problemas relacionados aos cálculos de volumes, considere simplificar as funções de cálculo, ou então refatorar para testar componentes pequenos individualmente:
Se o MetaEditor suportar, considere criar testes unitários para testar pequenos blocos do seu código separadamente, especialmente os cálculos de tamanho de lote e verificações de erro.
6. Considere a Ajuda de Fóruns ou Comunidades
Às vezes, pode ser útil consultar fóruns ou comunidades de desenvolvedores MQL para verificar se há problemas semelhantes relatados por outros usuários, e quais soluções foram sugeridas ou implementadas.
7. Refatoração e Modularização
Modularize o código para que cada função tenha uma responsabilidade única e clara. Isso pode ajudar a isolar erros e facilitar a depuração.
8. Utilização de uma Alternativa para Ordens
Considerar configurações alternativas para a gestão das ordens, utilizando temporariamente uma lógica simplificada para garantir que o erro não esteja no processamento de ordens.
Ao aplicar essas estratégias, você poderá identificar a causa raiz do problema e encontrar maneiras eficazes de solucioná-lo.