//--- Input Parameters
input bool DragonContra = true; // Ativar Dragon Contra
input bool DragonAFavor = true; // Ativar Dragon a Favor
input double TakeProfitPoints = 50.0; // Take Profit em pontos
input double StopLossPoints = 0.0; // Stop Loss em pontos (0 para nenhum)
input bool UseBollinger = true; // Usar Bollinger Bands
input double BollingerDeviation = 2.0; // Desvio das Bollinger Bands
input int BollingerPeriod = 20; // Período das Bollinger Bands
input ENUM_MA_METHOD MaMethod = MODE_SMA; // Tipo de média móvel
input int MaPeriod = 20; // Período da média móvel
input double Volume = 1.0; // Volume padrão (1 contrato)
input int MaxPendingOrders = 10; // Máximo de ordens pendentes por tipo
//--- Global Variables
double ma_value;
double bollinger_upper;
double bollinger_lower;
// Indicator handles
int ma_handle = INVALID_HANDLE;
int bb_handle = INVALID_HANDLE;
// CTrade object para gerenciar operações de trade
CTrade trade;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Criar handle da Média Móvel
ma_handle = iMA(_Symbol, _Period, MaPeriod, 0, MaMethod, PRICE_CLOSE);
if(ma_handle == INVALID_HANDLE)
{
Print("Erro ao criar o handle da Média Móvel (MA): ", GetLastError());
return INIT_FAILED;
}
// Criar handle das Bollinger Bands
if(UseBollinger)
{
bb_handle = iBands(_Symbol, _Period, BollingerPeriod, 0, BollingerDeviation, PRICE_CLOSE);
if(bb_handle == INVALID_HANDLE)
{
Print("Erro ao criar o handle das Bollinger Bands: ", GetLastError());
IndicatorRelease(ma_handle);
return INIT_FAILED;
}
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Atualizar valor do ponto
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
// Atualizar valores dos indicadores
if(!RetrieveIndicators())
return; // Sair se falhar ao obter indicadores
// Atualizar linhas gráficas
PlotLines();
// Lógica Dragon Contra
if(DragonContra)
{
HandleDragonContra(point);
}
// Lógica Dragon a Favor
if(DragonAFavor)
{
HandleDragonAFavor(point);
}
//+------------------------------------------------------------------+
//| Função para criar linhas gráficas no gráfico |
//+------------------------------------------------------------------+
bool CreateChartLine(string name, color clr, int width)
{
if(ObjectFind(0, name) == -1)
{
if(!ObjectCreate(0, name, OBJ_HLINE, 0, 0, 0))
{
Print("Erro ao criar linha gráfica: ", name);
return false;
}
ObjectSetInteger(0, name, OBJPROP_COLOR, clr);
ObjectSetInteger(0, name, OBJPROP_WIDTH, width);
}
return true;
}
//+------------------------------------------------------------------+
//| Função para obter valores dos indicadores |
//+------------------------------------------------------------------+
bool RetrieveIndicators()
{
// Obter valor da Média Móvel
double ma_buffer[];
if(CopyBuffer(ma_handle, 0, 0, 1, ma_buffer) <= 0)
{
Print("Falha ao copiar dados da Média Móvel (MA): ", GetLastError());
return false;
}
ma_value = ma_buffer[0];
//+------------------------------------------------------------------+
//| Função para verificar se há posições abertas no símbolo |
//+------------------------------------------------------------------+
bool HasPosition()
{
return PositionSelect(_Symbol);
}
//+------------------------------------------------------------------+
//| Função para verificar se há Buy Position |
//+------------------------------------------------------------------+
bool IsBought()
{
if(PositionSelect(_Symbol))
return PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY;
else
return false;
}
//+------------------------------------------------------------------+
//| Função para verificar se há Sell Position |
//+------------------------------------------------------------------+
bool IsSold()
{
if(PositionSelect(_Symbol))
return PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL;
else
return false;
}
//+------------------------------------------------------------------+
//| Função para verificar se o preço é válido para o tipo de ordem |
//+------------------------------------------------------------------+
bool IsValidPrice(ENUM_ORDER_TYPE order_type, double price)
{
double current_bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double current_ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
int stop_level = SymbolInfoInteger(_Symbol, SYMBOL_TRADE_STOPS_LEVEL);
// Verificar validade do preço conforme tipo de ordem
if(order_type == ORDER_TYPE_BUY_LIMIT)
{
// Para Buy Limit, o preço deve ser menor que o Bid atual menos o Stop Level
if(price >= (current_bid - stop_level * _Point))
return false;
}
else if(order_type == ORDER_TYPE_SELL_LIMIT)
{
// Para Sell Limit, o preço deve ser maior que o Ask atual mais o Stop Level
if(price <= (current_ask + stop_level * _Point))
return false;
}
else if(order_type == ORDER_TYPE_BUY_STOP)
{
// Para Buy Stop, o preço deve ser maior que o Ask atual mais o Stop Level
if(price <= (current_ask + stop_level * _Point))
return false;
}
else if(order_type == ORDER_TYPE_SELL_STOP)
{
// Para Sell Stop, o preço deve ser menor que o Bid atual menos o Stop Level
if(price >= (current_bid - stop_level * _Point))
return false;
}
// Normalizar o preço
price = NormalizeDouble(price, _Digits);
// Verificar se o preço está dentro dos limites permitidos pelo broker
double min_price = SymbolInfoDouble(_Symbol, SYMBOL_BID) - stop_level * _Point;
double max_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK) + stop_level * _Point;
Print("Sell Stop colocado com sucesso: Ticket ", result.order, " a preço ", price);
return true;
}
//+------------------------------------------------------------------+
//| Função para contar ordens pendentes de um tipo específico |
//+------------------------------------------------------------------+
int CountPendingOrders(ENUM_ORDER_TYPE order_type)
{
int count = 0;
int total_orders = OrdersTotal();
for(int i = 0; i < total_orders; i++)
{
ulong ticket = OrderGetTicket(i);
if(ticket == 0)
continue;
code
// Seleciona a ordem pelo ticket
if(!OrderSelect(ticket, SELECT_BY_TICKET))
{
Print("Falha ao selecionar a ordem (Ticket ", ticket, "): ", GetLastError());
continue;
}
// Obtém o símbolo da ordem
string order_symbol;
if(!OrderGetString(ORDER_SYMBOL, order_symbol))
{
Print("Falha ao obter o símbolo da ordem (Ticket ", ticket, "): ", GetLastError());
continue;
}
if(order_symbol != _Symbol)
continue;
// Obtém o tipo da ordem
ENUM_ORDER_TYPE current_order_type;
if(!OrderGetInteger(ORDER_TYPE, current_order_type))
{
Print("Falha ao obter o tipo da ordem (Ticket ", ticket, "): ", GetLastError());
continue;
}
if(current_order_type == order_type)
count++;
}
return count;
}
//+------------------------------------------------------------------+
//| Função para verificar ordens pendentes Dragon Contra |
//+------------------------------------------------------------------+
bool HasPendingOrdersContra()
{
int pending_buy_limit = CountPendingOrders(ORDER_TYPE_BUY_LIMIT);
int pending_sell_limit = CountPendingOrders(ORDER_TYPE_SELL_LIMIT);
//+------------------------------------------------------------------+
//| Função para gerenciar posições abertas |
//+------------------------------------------------------------------+
void ManagePositions()
{
int total_positions = PositionsTotal();
for(int i = 0; i < total_positions; i++)
{
// Seleciona a posição pelo índice
if(!PositionSelectByIndex(i))
{
Print("Falha ao selecionar a posição no índice: ", i, " - Erro: ", GetLastError());
continue;
}
code
// Obtém o ticket da posição
ulong ticket = PositionGetInteger(POSITION_TICKET);
if(ticket == 0)
{
Print("Ticket inválido para a posição: ", ticket);
continue;
}
// Obtém o símbolo da posição
string symbol;
if(!PositionGetString(POSITION_SYMBOL, symbol))
{
Print("Falha ao obter o símbolo da posição (Ticket ", ticket, "): ", GetLastError());
continue;
}
// Verifica se a posição pertence ao símbolo atual
if(symbol != _Symbol)
continue;
// Obtém o preço de abertura e o tipo da posição
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
ENUM_POSITION_TYPE pos_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
// Obtém o preço atual baseado no tipo da posição
double current_price = (pos_type == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
// Calcula os preços para Take Profit e Média Móvel
double tp_price = (pos_type == POSITION_TYPE_BUY) ? open_price + TakeProfitPoints * _Point : open_price - TakeProfitPoints * _Point;
double distance_to_tp = MathAbs(tp_price - current_price);
double distance_to_ma = MathAbs(ma_value - current_price);
// Decide onde fechar a posição
double close_price = (distance_to_tp < distance_to_ma) ? tp_price : ma_value;
// Prepara a requisição para modificar a posição (definir novo Take Profit)
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_SLTP; // Alteração de SL/TP
request.symbol = _Symbol;
request.position = ticket;
request.tp = NormalizeDouble(close_price, _Digits);
// Envia a requisição
if(!trade.OrderSend(request, result))
{
Print("Falha ao modificar posição (Ticket ", ticket, "): ", result.retcode, " - ", result.comment);
}
else
{
Print("Posição modificada com sucesso (Ticket ", ticket, "): ", result.retcode, " - ", result.comment);
}
}
}
//+------------------------------------------------------------------+
possible loss of data due to type conversion from 'long' to 'int' dragon47round.mq5 252 19
'SELECT_BY_TICKET' - undeclared identifier dragon47round.mq5 536 31
'OrderSelect' - wrong parameters count dragon47round.mq5 536 11
built-in: bool OrderSelect(ulong) dragon47round.mq5 536 11
'OrderGetInteger' - no one of the overloads can be applied to the function call dragon47round.mq5 555 11
could be one of 2 function(s) dragon47round.mq5 555 11
built-in: long OrderGetInteger(ENUM_ORDER_PROPERTY_INTEGER) dragon47round.mq5 555 11
built-in: bool OrderGetInteger(ENUM_ORDER_PROPERTY_INTEGER,long&) dragon47round.mq5 555 11
possible use of uninitialized variable 'current_order_type' dragon47round.mq5 561 10
'PositionSelectByIndex' - undeclared identifier dragon47round.mq5 668 11
'i' - some operator expected dragon47round.mq5 668 33
5 errors, 2 warnings 6 3
compile por favor antes para nao ter nenhum erro
Olá! Identifiquei os erros no seu código e fiz as correções necessárias para que ele compile sem erros. Abaixo, explico cada erro e apresento o código corrigido.
Erro 1: Possible loss of data due to type conversion from 'long' to 'int'
Correção: As funções OrdersTotal() e PositionsTotal() retornam um valor do tipo uint. Portanto, é melhor declarar as variáveis que recebem esses valores como uint.
Erro 2 e 3: 'SELECT_BY_TICKET' - undeclared identifier' e 'OrderSelect' - wrong parameters count
Correção: No MQL5, a função OrderSelect aceita apenas um parâmetro (o ticket da ordem). Não é necessário especificar o modo de seleção como no MQL4. Remova o segundo parâmetro SELECT_BY_TICKET.
Erro 4: 'OrderGetInteger' - no one of the overloads can be applied to the function call
Correção: A função OrderGetInteger no MQL5 retorna diretamente o valor. Portanto, não precisa passar uma variável por referência. Use OrderGetInteger(ENUM_ORDER_PROPERTY_INTEGER property_id).
Erro 5: Possible use of uninitialized variable 'current_order_type'
Correção: Inicialize a variável current_order_type antes de usá-la.
Erro 6 e 7: 'PositionSelectByIndex' - undeclared identifier' e 'i' - some operator expected
Correção: A função correta é PositionGetSymbol(i) em vez de PositionSelectByIndex(i). Além disso, ajuste a sintaxe na linha correspondente.