//+------------------------------------------------------------------+
//|                                       EA_MA_Cross.mq5          |
//|                        Expert Advisor for MA Cross Strategy     |
//+------------------------------------------------------------------+
#property strict

input int movingAveragePeriod20 = 20; // Período da Média Móvel Exponencial 20
input int movingAveragePeriod200 = 200; // Período da Média Móvel Simples 200
input int movingAveragePeriod10 = 10; // Período da Média Móvel Exponencial 10
input double takeProfitPips = 20; // Take Profit em pips
input double stopLossPips = 400; // Stop Loss em pips
input double lotSize = 0.1; // Tamanho do Lote
input double trailingStopPips = 20; // Trailing Stop em pips

double ma20, ma200, ma10;
double trailingStopLevel;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
void OnTick()
{
    // Calcular as médias móveis
    ma20 = iMA(NULL, 0, movingAveragePeriod20, 0, MODE_EMA, PRICE_CLOSE);
    ma200 = iMA(NULL, 0, movingAveragePeriod200, 0, MODE_SMA, PRICE_CLOSE);
    ma10 = iMA(NULL, 0, movingAveragePeriod10, 0, MODE_EMA, PRICE_CLOSE);

    // Fechar ordens existentes com base nas regras
    CloseOpenOrders();

    // Verificar se o preço está lateralizando
    if (IsPriceConsolidating())
        return;

    // Abrir ordens de compra ou venda
    if (CanOpenBuy())
    {
        OpenBuy();
    }
    else if (CanOpenSell())
    {
        OpenSell();
    }

    // Gerenciar Trailing Stop
    ManageTrailingStop();
}

//+------------------------------------------------------------------+
//| Verifica se pode abrir uma ordem de compra                        |
//+------------------------------------------------------------------+
bool CanOpenBuy()
{
    return (ma20 > ma200 && iClose(NULL, 0, 1) > ma200 && iClose(NULL, 0, 2) > ma200);
}

//+------------------------------------------------------------------+
//| Verifica se pode abrir uma ordem de venda                         |
//+------------------------------------------------------------------+
bool CanOpenSell()
{
    return (ma20 < ma200 && iClose(NULL, 0, 1) < ma200 && iClose(NULL, 0, 2) < ma200);
}

//+------------------------------------------------------------------+
//| Abre uma ordem de compra                                          |
//+------------------------------------------------------------------+
void OpenBuy()
{
    MqlTradeRequest request;
    MqlTradeResult result;

    request.action = TRADE_ACTION_DEAL;
    request.symbol = Symbol();
    request.volume = lotSize;
    request.type = ORDER_BUY;
    request.price = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_BID), _Digits);
    request.tp = NormalizeDouble(request.price + takeProfitPips * _Point, _Digits);
    request.sl = NormalizeDouble(request.price - stopLossPips * _Point, _Digits);
    
    if (OrderSend(request, result))
    {
        Print("Buy order opened: ", result.order);
    }
    else
    {
        Print("Error opening buy order: ", GetLastError());
    }
}

//+------------------------------------------------------------------+
//| Abre uma ordem de venda                                           |
//+------------------------------------------------------------------+
void OpenSell()
{
    MqlTradeRequest request;
    MqlTradeResult result;

    request.action = TRADE_ACTION_DEAL;
    request.symbol = Symbol();
    request.volume = lotSize;
    request.type = ORDER_SELL;
    request.price = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_ASK), _Digits);
    request.tp = NormalizeDouble(request.price - takeProfitPips * _Point, _Digits);
    request.sl = NormalizeDouble(request.price + stopLossPips * _Point, _Digits);
    
    if (OrderSend(request, result))
    {
        Print("Sell order opened: ", result.order);
    }
    else
    {
        Print("Error opening sell order: ", GetLastError());
    }
}

//+------------------------------------------------------------------+
//| Fecha ordens existentes                                           |
//+------------------------------------------------------------------+
void CloseOpenOrders()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionSelect(Symbol()))
        {
            ulong position_ticket = PositionGetInteger(POSITION_TICKET); // Corrigido
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && !CanOpenBuy())
            {
                if (OrderClose(position_ticket)) // Corrigido
                {
                    Print("Closed buy order: ", position_ticket);
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && !CanOpenSell())
            {
                if (OrderClose(position_ticket)) // Corrigido
                {
                    Print("Closed sell order: ", position_ticket);
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| Verifica se o preço está lateralizando                            |
//+------------------------------------------------------------------+
bool IsPriceConsolidating()
{
    // Aqui você pode implementar a lógica de lateralização
    return false; // Modifique conforme necessário
}

//+------------------------------------------------------------------+
//| Gerencia o Trailing Stop                                          |
//+------------------------------------------------------------------+
void ManageTrailingStop()
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (PositionSelect(Symbol()))
        {
            ulong position_ticket = PositionGetInteger(POSITION_TICKET); // Corrigido
            double currentProfit = PositionGetDouble(POSITION_PROFIT);
            double currentStopLoss = PositionGetDouble(POSITION_SL);

            // Calcular o novo nível de trailing stop
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY)
                trailingStopLevel = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_BID) - trailingStopPips * _Point, _Digits);
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL)
                trailingStopLevel = NormalizeDouble(SymbolInfoDouble(Symbol(), SYMBOL_ASK) + trailingStopPips * _Point, _Digits);

            // Ajustar o trailing stop se necessário
            if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && currentStopLoss < trailingStopLevel)
            {
                if (OrderModify(position_ticket, PositionGetDouble(POSITION_PRICE_OPEN), trailingStopLevel, PositionGetDouble(POSITION_TP), 0)) // Corrigido
                {
                    Print("Adjusted trailing stop for buy order: ", position_ticket);
                }
            }
            else if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && currentStopLoss > trailingStopLevel)
            {
                if (OrderModify(position_ticket, PositionGetDouble(POSITION_PRICE_OPEN), trailingStopLevel, PositionGetDouble(POSITION_TP), 0)) // Corrigido
                {
                    Print("Adjusted trailing stop for sell order: ", position_ticket);
                }
            }
        }
    }
}

//+------------------------------------------------------------------+


erro:
'ORDER_BUY' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	76	20
'ORDER_SELL' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	102	20
'OrderClose' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	129	21
'position_ticket' - some operator expected	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	129	32
'OrderClose' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	136	21
'position_ticket' - some operator expected	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	136	32
'OrderModify' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	21
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	48
'position_ticket' - some operator expected	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	33
'(' - unbalanced left parenthesis	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	20
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	88
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	107
expression has no effect	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	90
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	139
')' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	142
expression has no effect	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	141
')' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	176	143
'OrderModify' - undeclared identifier	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	21
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	48
'position_ticket' - some operator expected	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	33
'(' - unbalanced left parenthesis	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	20
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	88
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	107
expression has no effect	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	90
',' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	139
')' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	142
expression has no effect	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	141
')' - unexpected token	HTF_Wendel_Cassiano2_V2_ Arrumando_0001_Lot_001.mq5	183	143