Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

//+------------------------------------------------------------------+ // Scalping Robot…

  1. User

    //+------------------------------------------------------------------+ //| Scalping Robot Enhanced with Neural Network | //+------------------------------------------------------------------+ #property copyright "Copyright 2024, MetaQuotes Ltd." #property link "https://www.mql5.com" #property version "1.01"

    #include <Trade/Trade.mqh>

    #define NumNodes 10 CTrade trade; CPositionInfo pos; COrderInfo ord;

    // Trading Parameters 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 (10 points = 1 pip) input int TslPoints = 10; // Trailing Stoploss (10 points = 1 pip) input ENUM_TIMEFRAMES Timeframe = PERIOD_CURRENT; // Time frame to run input int InpMagic = 891245; // EA identification no input string TradeComment = "Wendel Cassiano"; // Trade comment input int MaxSpread = 100; // Maximum spread allowed (in points) input int Slippage = 50; // Slippage in points input int MaxOrders = 2; // Maximum simultaneous orders

    input int BarsN = 5; // Bars to analyze input int ExpirationBars = 100; // Order expiration based on bars input int OrderDistPoints = 100; // Distance in points from price

    // Neural Network Parameters input double Coefficient = 0.1; input double BuyTargetOutput = 0.3; input double SellTargetOutput = -0.3; input double LearningRate = 0.1;

    double Weight[]; double RSIBuffer[NumNodes]; double NormalizedInputs[NumNodes]; double NNOutPut = 0;

    //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { trade.SetExpertMagicNumber(InpMagic); ChartSetInteger(0, CHART_SHOW_GRID, false);

    // Initialize Neural Network Weights ArrayResize(Weight, NumNodes); for (int i = 0; i < NumNodes; i++) Weight[i] = 0.5;

    return (INIT_SUCCEEDED); }

    //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Run TrailStop logic TrailStop();

    // Check for new bar and exit if not if (!IsNewBar()) return;

    // Check spread double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point; if (spread > MaxSpread) return;

    // Count open orders int BuyTotal = 0, SellTotal = 0; for (int i = PositionsTotal() - 1; i >= 0; i--) { pos.SelectByIndex(i); if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol) { if (pos.PositionType() == POSITION_TYPE_BUY) BuyTotal++; if (pos.PositionType() == POSITION_TYPE_SELL) SellTotal++; } }

    for (int i = OrdersTotal() - 1; i >= 0; i--) { ord.SelectByIndex(i); if (ord.Magic() == InpMagic && ord.Symbol() == _Symbol) { if (ord.OrderType() == ORDER_TYPE_BUY_STOP) BuyTotal++; if (ord.OrderType() == ORDER_TYPE_SELL_STOP) SellTotal++; } }

    // Ensure order limit int TotalOrders = BuyTotal + SellTotal; if (TotalOrders >= MaxOrders) return;

    // Neural network prediction NormalizingInputs(); OutPutLayerCalculation();

    // Determine Buy and Sell Signals bool buySignal = (BuyTotal == 0 && NNOutPut > 0); // Neural Buy Signal bool sellSignal = (SellTotal == 0 && NNOutPut < 0); // Neural Sell Signal

    if (buySignal) { double high = findHigh(); if (high > 0) SendBuyOrder(high); }

    if (sellSignal) { double low = findLow(); if (low > 0) SendSellOrder(low); } }

    //+------------------------------------------------------------------+ //| High and Low Search | //+------------------------------------------------------------------+ double findHigh() { double highestHigh = 0; for (int i = 0; i < 200; i++) { double high = iHigh(_Symbol, Timeframe, i); if (i > BarsN && iHighest(_Symbol, Timeframe, MODE_HIGH, BarsN * 2 + 1, i - BarsN) == i) { if (high > highestHigh) return high; } highestHigh = MathMax(high, highestHigh); } return -1; }

    double findLow() { double lowestLow = DBL_MAX; for (int i = 0; i < 200; i++) { double low = iLow(_Symbol, Timeframe, i); if (i > BarsN && iLowest(_Symbol, Timeframe, MODE_LOW, BarsN * 2 + 1, i - BarsN) == i) { if (low < lowestLow) return low; } } return -1; }

    //+------------------------------------------------------------------+ //| Order Sending Logic | //+------------------------------------------------------------------+ 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;
    
    trade.BuyStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, iTime(_Symbol, Timeframe, 0) + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
    

    }

    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;
    
    trade.SellStop(LotSize, entry, _Symbol, sl, tp, ORDER_TIME_SPECIFIED, iTime(_Symbol, Timeframe, 0) + ExpirationBars * PeriodSeconds(Timeframe), Slippage);
    

    }

    //+------------------------------------------------------------------+ //| Neural Network Functions | //+------------------------------------------------------------------+ void NormalizingInputs() { double LowerNormRange = -1; double UpperNormRange = 1;

    for (int i = 0; i < NumNodes; i++)
    {
        NormalizedInputs[i] = (((RSIBuffer[i] - 0) * (UpperNormRange - LowerNormRange)) / (100 - 0)) + LowerNormRange;
    }
    

    }

    void OutPutLayerCalculation() { NNOutPut = HiddenLayerCalculation(NormalizedInputs, Weight); }

    double HiddenLayerCalculation(double &inputs[], double &Weights[]) { double TotalWeightedInputs = 0.0; for (int i = 0; i < ArraySize(inputs); i++) TotalWeightedInputs += inputs[i] * Weights[i]; TotalWeightedInputs *= Coefficient; return TanHActivationFunction(TotalWeightedInputs); }

    double TanHActivationFunction(double WeightedInputs) { return ((exp(WeightedInputs) - exp(-WeightedInputs)) / ((exp(WeightedInputs) + exp(-WeightedInputs)))); }

    //+------------------------------------------------------------------+ //| Is New Bar Function | //+------------------------------------------------------------------+ bool IsNewBar() { static datetime previousTime = 0; datetime currentTime = iTime(_Symbol, Timeframe, 0); if (previousTime != currentTime) { previousTime = currentTime; return true; } return false; }

    //+------------------------------------------------------------------+ //| 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 (pos.SelectByIndex(i) && pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
        {
            double sl = 0;
            double tp = pos.TakeProfit();
            if (pos.PositionType() == POSITION_TYPE_BUY)
            {
                if (bid - pos.PriceOpen() >= TslTriggerPoints * _Point)
                {
                    sl = bid - TslPoints * _Point;
                    if (sl > pos.StopLoss() || pos.StopLoss() == 0)
                        trade.PositionModify(pos.Ticket(), sl, tp);
                }
            }
            if (pos.PositionType() == POSITION_TYPE_SELL)
            {
                if (pos.PriceOpen() - ask >= TslTriggerPoints * _Point)
                {
                    sl = ask + TslPoints * _Point;
                    if (sl < pos.StopLoss() || pos.StopLoss() == 0)
                        trade.PositionModify(pos.Ticket(), sl, tp);
                }
            }
        }
    }
    

    }

    quero que o robo va atualizando novos pontos de negociação sem eu precisar recolcoar o EA no grafico novamente, pois percebi que quando tem novos pontos ele nao se ajusta logo mas demora para fazer o ajuste ou somente quando eu retiro e recoloco o EA no grafico

  2. Assistant

    Para garantir que o seu robô de scalping atualize automaticamente novos pontos de negociação sem a necessidade de re-colocar o EA no gráfico, você pode implementar um mecanismo que recalcula os pontos relevantes durante cada tick ou cada nova barra. Abaixo, apresento algumas sugestões para modificar o seu código.

    1. Atualização da Rede Neural: Você deve garantir que, durante cada tick, sua rede neural possa ser atualizada com os novos dados de entrada. Isso implica que você deve introduzir lógica para re-calcular suas entradas de rede neural com base nos dados mais recentes.

    2. Reavaliação dos Preços de Entrada e Sinais: Você pode criar uma função que seja chamada em cada tick ou nova barra, para reavaliar o estado do mercado e decidir se deve modificar as ordens existentes ou abrir novas.

    3. Uso de um Buffer para Novos Preços: Para garantir que novos preços de entrada sejam sempre considerados, você pode criar um buffer que armazena os preços de compra e venda, expurgando os menos relevantes à medida que novos dados se tornam disponíveis.

    4. Verificação de Barras Novas: Modifique a lógica de verificação para garantir que ela não dependa apenas da data da barra anterior, mas sim da criação de novas barras a cada nova tick.

    Aqui está uma versão revisada do código, focando nas mudanças que podem ajudar a resolver seu problema:

    // +------------------------------------------------------------------+
    // | Scalping Robot Enhanced with Neural Network                      |
    // +------------------------------------------------------------------+
    #property copyright "Copyright 2024, MetaQuotes Ltd."
    #property link "https://www.mql5.com"
    #property version "1.02" // Atualizado para a versão 1.02
    
    #include <Trade/Trade.mqh>
    
    #define NumNodes 10
    CTrade trade;
    CPositionInfo pos;
    COrderInfo ord;
    
    // ... (seus parâmetros de entrada e variáveis)
    
    double Weight[];
    double RSIBuffer[NumNodes];
    double NormalizedInputs[NumNodes];
    double NNOutPut = 0;
    
    // +------------------------------------------------------------------+
    // | Expert initialization function                                   |
    // +------------------------------------------------------------------+
    int OnInit()
    {
        trade.SetExpertMagicNumber(InpMagic);
        ChartSetInteger(0, CHART_SHOW_GRID, false);
    
        ArrayResize(Weight, NumNodes);
        for (int i = 0; i < NumNodes; i++)
            Weight[i] = 0.5;
    
        return (INIT_SUCCEEDED);
    }
    
    // +------------------------------------------------------------------+
    // | Expert tick function                                             |
    // +------------------------------------------------------------------+
    void OnTick()
    {
        // Atualiza informações e pega dados de mercado
        UpdateMarketData();
        
        // Executa a lógica de trailing stop
        TrailStop();
    
        // Verifica se há uma nova barra
        if (!IsNewBar())
            return;
    
        // Verifica o spread
        if (!IsSpreadAcceptable())
            return;
    
        // Contabiliza ordens abertas
        int TotalOrders = CountOpenOrders();
    
        // Garante que não exceda o limite de ordens
        if (TotalOrders >= MaxOrders)
            return;
    
        // Executa a lógica da rede neural
        NormalizingInputs();
        OutPutLayerCalculation();
    
        // Determina sinais de compra e venda
        bool buySignal = (CountOpenBuyOrders() == 0 && NNOutPut > 0);
        bool sellSignal = (CountOpenSellOrders() == 0 && NNOutPut < 0);
    
        if (buySignal)
        {
            double high = findHigh();
            if (high > 0)
                SendBuyOrder(high);
        }
    
        if (sellSignal)
        {
            double low = findLow();
            if (low > 0)
                SendSellOrder(low);
        }
    }
    
    // Adicionando funções auxiliares para contagem de ordens
    int CountOpenOrders() 
    {
        int count = 0;
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            pos.SelectByIndex(i);
            if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol)
                count++;
        }
        return count;
    }
    
    int CountOpenBuyOrders() 
    {
        int count = 0;
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            pos.SelectByIndex(i);
            if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol && pos.PositionType() == POSITION_TYPE_BUY)
                count++;
        }
        return count;
    }
    
    int CountOpenSellOrders() 
    {
        int count = 0;
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            pos.SelectByIndex(i);
            if (pos.Magic() == InpMagic && pos.Symbol() == _Symbol && pos.PositionType() == POSITION_TYPE_SELL)
                count++;
        }
        return count;
    }
    
    // Atualiza os dados do mercado e as entradas da rede neural
    void UpdateMarketData()
    {
        // Aqui você pode atualizar seu buffer RSIBuffer ou outras entradas
        // e garantir que a lógica de previsão da rede neural utilize as informações mais recentes
    }
    
    // Função para verificar a aceitabilidade do spread
    bool IsSpreadAcceptable()
    {
        double spread = (SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SymbolInfoDouble(_Symbol, SYMBOL_BID)) / _Point;
        return spread <= MaxSpread;
    }
    
    // ... (restante do seu código)
    
    // +------------------------------------------------------------------+
    

    Considerações:

    • Certifique-se de que a rotina de atualização do mercado utilize dados atualizados para dinamizar a capacidade do robô de responder rapidamente às mudanças de mercado.
    • O método UpdateMarketData() deverá ser desenvolvido para consumir dados relevantes (como RSI, preços, etc.) necessários para a previsão da rede neural.
    • Essa estrutura ajuda a melhorar a eficiência e a rapidez com que seu robô se adapta a novas informações de mercado.
    • Mantenha uma boa gestão de risco e teste o robô com dados históricos antes de colocá-lo em operação ao vivo.