Preciso implementar um martingale no meu EA mql5

 

ola , nao sou desenvolvedor estou assistindo videos e tentando implementar um martingale ' APENAS EM ORDEM SELL '

se repararem eu coloquei 2 lotes diferentes, lotbuy e lotsell, quero que de martingale apenas em sell, martingale ao tocar no stoloss em sell e ao tocar no take, volte para o lot inicial...

meu codido é simples, se alguem poder me ajudar ficare agradecido.


//+------------------------------------------------------------------+
//|                                                      EA_Simult.mq5 |
//|                        Copyright 2024, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property strict

#include <Trade\Trade.mqh>

// Parâmetros de entrada
input double lotBuy = 0.6;           // Lote inicial para ordem de compra
input double lotSell = 0.2;          // Lote inicial para ordem de venda
input double takeProfit = 100.0;     // Take profit em pontos
input double stopLoss = 50.0;        // Stop loss em pontos
input double martingaleFactor = 2.0; // Fator de multiplicação do Martingale para venda

// Variáveis de controle
bool orderPlaced = false;
ulong buyOrderTicket = 0;
ulong sellOrderTicket = 0;
double currentSellLot = lotSell;     // Tamanho atual do lote de venda
bool martingaleSellActive = false;   // Flag para indicar se o Martingale de venda está ativo

// Criação de objeto de negociação
CTrade trade;


//+------------------------------------------------------------------+
//| Função de inicialização do Expert                                |
//+------------------------------------------------------------------+
int OnInit()
{
    Print("EA Iniciado");
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Função de finalização do Expert                                  |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    Print("EA Desativado");
}

//+------------------------------------------------------------------+
//| Função de tick do Expert                                         |
//+------------------------------------------------------------------+
void OnTick()
{

    

    // Verifica se ordens já foram colocadas e se não há posições abertas
    if (!orderPlaced)
    {
        if (CountOpenPositions() == 0)
        {
            // Obtém os preços atuais
            double priceBuy = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            double priceSell = SymbolInfoDouble(_Symbol, SYMBOL_BID);

            // Calcula o take profit e stop loss para compra
            double takeProfitBuy = priceBuy + takeProfit * _Point;
            double stopLossBuy = priceBuy - stopLoss * _Point;

            // Calcula o take profit e stop loss para venda
            double takeProfitSell = priceSell - takeProfit * _Point;
            double stopLossSell = priceSell + stopLoss * _Point;
    
            // Abre uma ordem de compra com o tamanho de lote atual
            buyOrderTicket = trade.Buy(lotBuy, _Symbol, priceBuy, stopLossBuy, takeProfitBuy);
            if (buyOrderTicket == 0)
            {
                Print("Erro ao abrir ordem de compra: ", trade.ResultRetcode());
            }

            // Abre uma ordem de venda com o tamanho de lote atual
            sellOrderTicket = trade.Sell(currentSellLot, _Symbol, priceSell, stopLossSell, takeProfitSell);
            
            if (sellOrderTicket == 0)
            {
                Print("Erro ao abrir ordem de venda: ", trade.ResultRetcode());
            }
            
            // Define a flag indicando que as ordens foram colocadas
            if (buyOrderTicket > 0 && sellOrderTicket > 0)
            {
                orderPlaced = true;
            }
        }
    }
    else
    {
        // Verifica as ordens abertas e se precisam ser fechadas
        CheckOrders();
    }
}

//+------------------------------------------------------------------+
//| Verifica as ordens e as fecha se necessário                      |
//+------------------------------------------------------------------+
void CheckOrders()
{
    bool ordersClosed = true;

    // Verifica se a posição de compra ainda está aberta
    if (buyOrderTicket > 0 && PositionSelectByTicket(buyOrderTicket))
    {
        double currentPriceBuy = PositionGetDouble(POSITION_PRICE_CURRENT);
        double tpPriceBuy = PositionGetDouble(POSITION_TP);
        double slPriceBuy = PositionGetDouble(POSITION_SL);

        if (currentPriceBuy >= tpPriceBuy)
        {
            // Atingiu o take profit na compra
            CloseAllOrders();
            return;
        }
        else if (currentPriceBuy <= slPriceBuy)
        {
            // Atingiu o stop loss da compra
            CloseAllOrders();
            return;
        }
        else
        {
            ordersClosed = false;
        }
    }

    // Verifica se a posição de venda ainda está aberta
    if (sellOrderTicket > 0 && PositionSelectByTicket(sellOrderTicket))
    {
        double currentPriceSell = PositionGetDouble(POSITION_PRICE_CURRENT);
        double tpPriceSell = PositionGetDouble(POSITION_TP);
        double slPriceSell = PositionGetDouble(POSITION_SL);

        if (currentPriceSell <= tpPriceSell)
        {
            // Atingiu o take profit na venda, reseta o lote de venda
            currentSellLot = lotSell;       // Reseta o lote de venda ao valor inicial
            martingaleSellActive = false;   // Desativa o Martingale para a venda
            Print("Take profit atingido na venda. Lote de venda resetado: ", currentSellLot);
            CloseAllOrders();
            return;
        }
        else if (currentPriceSell >= slPriceSell)
        {
            // Atingiu o stop loss da venda, aplica Martingale
            martingaleSellActive = true;    // Ativa o Martingale para a venda
            currentSellLot *= martingaleFactor; // Multiplica o lote pelo fator de Martingale
            Print("Stop loss atingido na venda. Martingale ativado. Novo lote de venda: ", currentSellLot);
            CloseAllOrders();
            return;
        }
        else
        {
            ordersClosed = false;
        }
    }

    // Se todas as ordens foram fechadas, reseta as variáveis
    if (ordersClosed)
    {
        buyOrderTicket = 0;
        sellOrderTicket = 0;
        orderPlaced = false;
    }
}

//+------------------------------------------------------------------+
//| Fecha todas as ordens abertas                                    |
//+------------------------------------------------------------------+
void CloseAllOrders()
{
    if (buyOrderTicket > 0 && PositionSelectByTicket(buyOrderTicket))
    {
        if (!trade.PositionClose(buyOrderTicket))
        {
            Print("Erro ao fechar a ordem de compra: ", trade.ResultRetcode());
        }
    }
    if (sellOrderTicket > 0 && PositionSelectByTicket(sellOrderTicket))
    {
        if (!trade.PositionClose(sellOrderTicket))
        {
            Print("Erro ao fechar a ordem de venda: ", trade.ResultRetcode());
        }
    }

    buyOrderTicket = 0;
    sellOrderTicket = 0;
    orderPlaced = false;
}

//+------------------------------------------------------------------+
//| Conta quantas posições estão abertas para o símbolo atual        |
//+------------------------------------------------------------------+
int CountOpenPositions()
{
    int count = 0;
    for (int i = 0; i < PositionsTotal(); i++)
    {
        if (PositionGetSymbol(i) == _Symbol)
        {
            count++;
        }
    }
    return count;
}