2024.07.29 02:26:16.839	MetaTester 5 started on 127.0.0.1:3000
2024.07.29 02:26:16.846	cloud network mode is off
2024.07.29 02:26:16.846	initialization finished
2024.07.29 02:26:16.955	login (build 4424)
2024.07.29 02:26:17.132	11604 bytes of account info loaded
2024.07.29 02:26:17.132	1478 bytes of tester parameters loaded
2024.07.29 02:26:17.132	2756 bytes of input parameters loaded
2024.07.29 02:26:17.133	1280 bytes of symbols list loaded (172 symbols)
2024.07.29 02:26:17.133	expert file added: Experts\Wende_Testando_01.ex5. 10271 bytes loaded
2024.07.29 02:26:17.170	calculate profit in pips, initial deposit 10000, leverage 1:100
2024.07.29 02:26:17.173	successfully initialized
2024.07.29 02:26:17.173	12 Kb of total initialization data received
2024.07.29 02:26:17.173	AMD FX-6300 Six-Core, 4095 MB
2024.07.29 02:26:17.203	EURUSD: symbol to be synchronized
2024.07.29 02:26:17.204	EURUSD: symbol synchronized, 3880 bytes of symbol info received
2024.07.29 02:26:17.204	EURUSD: history synchronization started
2024.07.29 02:26:17.220	EURUSD: load 27 bytes of history data to synchronize in 0:00:00.007
2024.07.29 02:26:17.220	EURUSD: history synchronized from 1971.01.04 to 2024.07.26
2024.07.29 02:26:17.350	EURUSD,H1: history cache allocated for 9824 bars and contains 6207 bars from 2023.01.02 09:00 to 2023.12.29 23:00
2024.07.29 02:26:17.350	EURUSD,H1: history begins from 2023.01.02 09:00
2024.07.29 02:26:17.351	EURUSD,H1 (XMGlobal-MT5 6): every tick generating
2024.07.29 02:26:17.351	EURUSD,H1: testing of Experts\Wende_Testando_01.ex5 from 2024.01.01 00:00 to 2024.07.28 00:00 started with inputs:
2024.07.29 02:26:17.351	  sma_length=20
2024.07.29 02:26:17.351	  sma_offset=1.3
2024.07.29 02:26:17.351	  ema_length=9
2024.07.29 02:26:17.351	  sma200_length=200
2024.07.29 02:26:17.351	  MAGIC_NUMBER=123456
2024.07.29 02:26:17.375	2024.01.01 00:00:00   Erro ao copiar buffer da SMA: 4806
2024.07.29 02:26:17.375	2024.01.01 00:00:00   Erro ao copiar os buffers de indicadores.
2024.07.29 02:26:17.375	tester stopped because OnInit returns non-zero code 1
2024.07.29 02:26:17.375	log file "C:\Users\Wendel\AppData\Roaming\MetaQuotes\Tester\BB16F565FAAA6B23A20C26C49416FF05\Agent-127.0.0.1-3000\logs\20240729.log" written
2024.07.29 02:26:17.376	test Experts\Wende_Testando_01.ex5 on EURUSD,H1 thread finished
2024.07.29 02:26:17.386	prepare for shutdown
2024.07.29 02:26:17.386	shutdown finished



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

input int sma_length = 20;      // Comprimento da SMA
input double sma_offset = 1.3;  // Deslocamento da SMA
input int ema_length = 9;       // Comprimento da EMA
input int sma200_length = 200;  // Comprimento da SMA 200

double sma[], ema[], sma200[];

int sma_handle, ema_handle, sma200_handle;
bool position_open = false;
input int MAGIC_NUMBER = 123456;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Inicializando buffers
    ArraySetAsSeries(sma, true);
    ArraySetAsSeries(ema, true);
    ArraySetAsSeries(sma200, true);

    // Indicadores
    sma_handle = iMA(_Symbol, _Period, sma_length, 0, MODE_SMA, PRICE_CLOSE);
    ema_handle = iMA(_Symbol, _Period, ema_length, 0, MODE_EMA, PRICE_CLOSE);
    sma200_handle = iMA(_Symbol, _Period, sma200_length, 0, MODE_SMA, PRICE_CLOSE);

    // Verificação de sucesso na criação dos handles
    if (sma_handle < 0 || ema_handle < 0 || sma200_handle < 0)
    {
        Print("Erro ao criar handles de indicadores: SMA Handle = ", sma_handle, ", EMA Handle = ", ema_handle, ", SMA200 Handle = ", sma200_handle, ", Erro: ", GetLastError());
        return INIT_FAILED;
    }

    // Verificar se há barras suficientes no gráfico
    if (iBars(_Symbol, _Period) < sma_length || iBars(_Symbol, _Period) < ema_length || iBars(_Symbol, _Period) < sma200_length)
    {
        Print("Dados insuficientes no gráfico para calcular os indicadores.");
        return INIT_FAILED;
    }

    // Cálculo inicial das médias
    if (!CopyIndicatorBuffers())
    {
        Print("Erro ao copiar os buffers de indicadores.");
        return INIT_FAILED;
    }

    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Função para copiar buffers dos indicadores                      |
//+------------------------------------------------------------------+
bool CopyIndicatorBuffers()
{
    int copied;

    // Verifica o número de barras disponíveis
    int bars_available = iBars(_Symbol, _Period);
    
    // Copiar buffers para SMA
    int start_sma = MathMax(sma_length, 0);
    copied = CopyBuffer(sma_handle, 0, 0, start_sma, sma);
    if (copied < sma_length)
    {
        Print("Erro ao copiar buffer da SMA: ", GetLastError());
        return false;
    }

    // Copiar buffers para EMA
    int start_ema = MathMax(ema_length, 0);
    copied = CopyBuffer(ema_handle, 0, 0, start_ema, ema);
    if (copied < ema_length)
    {
        Print("Erro ao copiar buffer da EMA: ", GetLastError());
        return false;
    }

    // Copiar buffers para SMA 200
    int start_sma200 = MathMax(sma200_length, 0);
    copied = CopyBuffer(sma200_handle, 0, 0, start_sma200, sma200);
    if (copied < sma200_length)
    {
        Print("Erro ao copiar buffer da SMA 200: ", GetLastError());
        return false;
    }

    return true;
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    // Limpeza dos gráficos de indicadores, se necessário
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    double sma_current, ema_current, sma200_current;
    double close_prices[];

    // Atualização dos buffers das médias móveis
    if (!CopyIndicatorBuffers())
    {
        Print("Erro ao atualizar buffers de indicadores.");
        return;
    }

    // Obter preços de fechamento
    ArraySetAsSeries(close_prices, true);
    if (CopyClose(_Symbol, _Period, 0, 1, close_prices) <= 0)
    {
        Print("Erro ao copiar preços de fechamento: ", GetLastError());
        return;
    }
    double close_price = close_prices[0];

    // Obter preços bid e ask
    double bid_price = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double ask_price = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

    // Verificar a tendência atual
    sma_current = sma[0] * sma_offset;
    ema_current = ema[0];
    sma200_current = sma200[0];

    int trend_color_20_9 = (ema_current > sma_current) ? clrGreen : clrRed;
    int trend_color_200 = (close_price > sma200_current) ? clrGreen : clrRed;

    // Análise de tendência
    bool uptrend = (ema_current > sma_current && close_price > sma200_current);
    bool downtrend = (ema_current < sma_current && close_price < sma200_current);

    MqlTradeRequest request;
    MqlTradeResult result;

    // Preparar request para envio de ordens
    request.action = TRADE_ACTION_DEAL;
    request.symbol = _Symbol;
    request.volume = 0.1;
    request.deviation = 2;
    request.magic = MAGIC_NUMBER;
    request.comment = "";

    if (uptrend && !position_open)
    {
        // Abrir posição de compra
        request.type = ORDER_TYPE_BUY;
        request.price = ask_price;
        request.comment = "Comprando devido à tendência de alta";
        if (!OrderSend(request, result))
        {
            Print("Erro ao enviar ordem de compra: ", GetLastError());
        }
        else
        {
            position_open = true;
        }
    }
    else if (downtrend && !position_open)
    {
        // Abrir posição de venda
        request.type = ORDER_TYPE_SELL;
        request.price = bid_price;
        request.comment = "Vendendo devido à tendência de baixa";
        if (!OrderSend(request, result))
        {
            Print("Erro ao enviar ordem de venda: ", GetLastError());
        }
        else
        {
            position_open = true;
        }
    }
    else if ((!uptrend && !downtrend) && position_open)
    {
        // Fechar posição se a tendência não for sustentada
        if (PositionSelect(_Symbol))
        {
            request.type = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? ORDER_TYPE_SELL : ORDER_TYPE_BUY;
            request.price = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? bid_price : ask_price;
            request.volume = PositionGetDouble(POSITION_VOLUME);
            request.comment = "Fechando posição devido à mudança de tendência";
            if (!OrderSend(request, result))
            {
                Print("Erro ao fechar a posição: ", GetLastError());
            }
            else
            {
                position_open = false;
            }
        }
    }
}
//+------------------------------------------------------------------+