'SendSellOrder' - function already defined and has body Scalping_GOLD__006_NEURAL_.mq5 241 6
see declaration of function 'SendSellOrder' Scalping_GOLD__006_NEURAL_.mq5 135 6
'IsNewBar' - function already defined and has body Scalping_GOLD__006_NEURAL_.mq5 317 6
errros acima:
codigo abaixo:
//+------------------------------------------------------------------+
//| Scalper |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, MetaQuotes Ltd."
#property link "https://www.mql5.com"
#property version "1.03"
#include <Trade/Trade.mqh>
CTrade trade;
CPositionInfo pos;
COrderInfo ord;
//+------------------------------------------------------------------+
//| Inputs Gerais |
//+------------------------------------------------------------------+
input group "*** Trading Inputs ***"
input double LotSize = 0.01; // Lot size for trading
input int Tppoints = 800; // Take Profit (10 points = 1 pip)
input int Slpoints = 800; // Stoploss Points (10 points = 1 pip)
input int TslTriggerPoints = 35; // Points in profit before Trailing SL is activated
input int TslPoints = 10; // Trailing Stoploss
input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; // Time frame to run
input int InpMagic = 891245; // EA identification no
input string TradeComment = "Wendel Cassiano";
input int MaxSpread = 100; // Maximum spread allowed (in points)
input int Slippage = 50; // Slippage in points
input int MaxOrders = 2; // Máximo de ordens permitidas simultaneamente
int BarsN = 5;
int ExpirationBars = 100;
int OrderDistPoints = 100;
//+------------------------------------------------------------------+
//| Variáveis da Rede Neural |
//+------------------------------------------------------------------+
#define NodeCount 10 // Número de entradas
double Inputs[NodeCount]; // Entradas normalizadas
double Weights[NodeCount]; // Pesos para as entradas
double NNOutput = 0; // Saída da Rede Neural
input double LearningRate = 0.1; // Taxa de aprendizado
const double NormMin = -1; // Limite inferior da normalização
const double NormMax = 1; // Limite superior da normalização
//+------------------------------------------------------------------+
//| Função de Inicialização do Robô |
//+------------------------------------------------------------------+
int OnInit()
{
trade.SetExpertMagicNumber(InpMagic);
ChartSetInteger(0, CHART_SHOW_GRID, false);
// Inicialização dos pesos da rede neural com valores pequenos e aleatórios
for (int i = 0; i < NodeCount; i++)
Weights[i] = MathRand() * 0.01;
Print("Expert Advisor initialized successfully.");
return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
//| Função Chamda A Cada Novo Tick |
//+------------------------------------------------------------------+
void OnTick()
{
// Trailing Stop e controle para evitar duplicação em cada tick
TrailStop();
if (!IsNewBar())
return;
// Controle de spread
double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
if (spread > MaxSpread)
{
Print("Spread demasiado alto: ", spread);
return;
}
// Lógica da Rede Neural: Normaliza entradas e calcula saída
for (int i = 0; i < NodeCount; i++)
{
// Pequena modificação para garantir valores significativos no cálculo
Inputs[i] = Normalize(iHigh(_Symbol, Timeframe, i), 1.0, 5000.0);
}
NNOutput = CalculateNNOutput(Inputs, Weights);
Print("NN Output: ", NNOutput);
// Treinamento da Rede Neural — ajusta pesos com base no erro de saída
double targetOutput = (iClose(_Symbol, Timeframe, 1) > iOpen(_Symbol, Timeframe, 1)) ? 0.5 : -0.5;
TrainNeuralNetwork(Inputs, Weights, targetOutput, NNOutput);
// Contagem de ordens abertas separando por tipo
int BuyTotal = 0, SellTotal = 0;
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (pos.SelectByIndex(i) && pos.Magic() == InpMagic)
{
if (pos.PositionType() == POSITION_TYPE_BUY)
BuyTotal++;
if (pos.PositionType() == POSITION_TYPE_SELL)
SellTotal++;
}
}
// Lógica de abertura com base nos resultados da Rede Neural
if (NNOutput > 0.3 && BuyTotal < MaxOrders) // Decisão de compra
{
double high = findHigh();
if (high > 0)
SendBuyOrder(high);
}
else if (NNOutput < -0.3 && SellTotal < MaxOrders) // Decisão de venda
{
double low = findLow(); // Obtém valor mínimo
if (low > 0)
SendSellOrder(low);
}
}
//+------------------------------------------------------------------+
//| Funções Auxiliares de negociação |
//+------------------------------------------------------------------+
// Função para criar ordem de compra
void SendBuyOrder(double entry)
{
double tp = entry + Tppoints * _Point;
double sl = entry - Slpoints * _Point;
trade.BuyStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED,
TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe));
}
// Função para criar ordem de venda
void SendSellOrder(double entry)
{
double tp = entry - Tppoints * _Point;
double sl = entry + Slpoints * _Point;
trade.SellStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED,
TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe));
}
//+------------------------------------------------------------------+
// Função para normalizar entrada baseada em valores mínimo e máximo
double Normalize(double value, double min, double max)
{
return ((value - min) * (NormMax - NormMin)) / (max - min) + NormMin;
}
// Função de ativação (tanh)
double ActivationFunction(double x)
{
return (exp(x) - exp(-x)) / (exp(x) + exp(-x));
}
// Calcula saída da rede neural
double CalculateNNOutput(double &inputs[], double &weights[])
{
double weightedSum = 0.0;
for (int i = 0; i < NodeCount; i++)
{
weightedSum += inputs[i] * weights[i];
}
return ActivationFunction(weightedSum);
}
// Ajusta pesos da Rede Neural com base no erro (retropropagação)
void TrainNeuralNetwork(double &inputs[], double &weights[], double targetOutput, double actualOutput)
{
double error = targetOutput - actualOutput;
double derivative = 1 - MathPow(actualOutput, 2); // Derivada de tanh
for (int i = 0; i < NodeCount; i++)
{
double gradient = error * derivative * inputs[i];
weights[i] += LearningRate * gradient;
}
}
//+------------------------------------------------------------------+
//| Função Auxiliar: verifica se há uma nova barra |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol, Timeframe, 0);
if (currentTime != previousTime)
{
previousTime = currentTime;
return true;
}
return false;
}
// Busca o preço mais alto
double findHigh()
{
double highestHigh = 0.0;
for (int i = 0; i < BarsN; i++)
{
double high = iHigh(_Symbol, Timeframe, i);
if (high > highestHigh)
highestHigh = high;
}
return highestHigh;
}
// Busca o preço mais baixo
double findLow()
{
double lowestLow = DBL_MAX;
for (int i = 0; i < BarsN; i++)
{
double low = iLow(_Symbol, Timeframe, i);
if (low < lowestLow)
lowestLow = low;
}
return lowestLow;
}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Função para criar ordens de compra |
//+------------------------------------------------------------------+
void SendBuyOrder(double entry)
{
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
if (ask > entry - OrderDistPoints * _Point) return;
double tp = entry + Tppoints * _Point;
double sl = entry - Slpoints * _Point;
double lots = LotSize;
datetime expiration = TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe);
trade.BuyStop(lots, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, expiration);
}
//+------------------------------------------------------------------+
//| Função para criar ordens de venda |
//+------------------------------------------------------------------+
void SendSellOrder(double entry)
{
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
if (bid < entry + OrderDistPoints * _Point) return;
double tp = entry - Tppoints * _Point;
double sl = entry + Slpoints * _Point;
double lots = LotSize;
datetime expiration = TimeCurrent() + ExpirationBars * PeriodSeconds(Timeframe);
trade.SellStop(lots, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, expiration);
}
//+------------------------------------------------------------------+
//| Função para trailing stop (stop móvel) |
//+------------------------------------------------------------------+
void TrailStop()
{
double sl = 0, tp = 0;
double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (pos.SelectByIndex(i))
{
ulong ticket = pos.Ticket();
if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
{
if (pos.PositionType() == POSITION_TYPE_BUY)
{
if (bid - pos.PriceOpen() > TslTriggerPoints * _Point)
{
tp = pos.TakeProfit();
sl = bid - (TslPoints * _Point);
if (sl > pos.StopLoss() && sl != 0)
trade.PositionModify(ticket, sl, tp);
}
}
else if (pos.PositionType() == POSITION_TYPE_SELL)
{
if (ask + (TslTriggerPoints * _Point) < pos.PriceOpen())
{
tp = pos.TakeProfit();
sl = ask + (TslPoints * _Point);
if (sl < pos.StopLoss() && sl != 0)
trade.PositionModify(ticket, sl, tp);
}
}
}
}
}
}
//+------------------------------------------------------------------+
//| Função para fechar todas as ordens |
//+------------------------------------------------------------------+
void CloseAllOrders()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
if (ord.SelectByIndex(i))
{
ulong ticket = ord.Ticket();
if (ord.Symbol() == _Symbol && ord.Magic() == InpMagic)
{
trade.OrderDelete(ticket);
}
}
}
}
//+------------------------------------------------------------------+
//| Função para verificar se há uma nova barra |
//+------------------------------------------------------------------+
bool IsNewBar()
{
static datetime previousTime = 0;
datetime currentTime = iTime(_Symbol, Timeframe, 0);
if (previousTime != currentTime)
{
previousTime = currentTime;
return true;
}
return false;
}
//+------------------------------------------------------------------+