// Expert Advisor parameters
input int FibonacciLevel = 78; // Fibonacci retracement level to take trades
input int StopLoss = 50; // Stop loss in pips
input int TakeProfit = 100; // Take profit in pips

// Define global variables
int ma_4h, ma_1d; // Moving averages of 4 hour and 1 day timeframes
double low_15m, high_15m; // Low and high swings of 15 minute timeframe

// Expert Advisor initialization function
int OnInit()
{
    // Define indicators
    ma_4h = iMA(_Symbol, PERIOD_H4, 50, 0, MODE_SMA, PRICE_CLOSE);
    ma_1d = iMA(_Symbol, PERIOD_D1, 50, 0, MODE_SMA, PRICE_CLOSE);
    return(INIT_SUCCEEDED);
}

// Expert Advisor tick function
void OnTick()
{
    // Check if current timeframe is 15 minutes
    if (Period() == PERIOD_M15) return;
    
    // Check trend direction of 4 hour and 1 day timeframes
    int trend_4h = ma_4h > Close[0] ? -1 : 1;
    int trend_1d = ma_1d > Close[0] ? -1 : 1;
    
    // Determine trend direction and set Fibonacci levels
    int trend = trend_4h == trend_1d ? trend_4h : 0;
    double level = trend == -1 ? High[0] : Low[0];
    
    // Calculate Fibonacci levels
    double fib0 = level;
    double fib1 = level - (trend * (High[0] - Low[0]) * 0.236);
    double fib2 = level - (trend * (High[0] - Low[0]) * 0.382);
    double fib3 = level - (trend * (High[0] - Low[0]) * 0.618);
    double fib4 = level - (trend * (High[0] - Low[0]) * 0.786);
    double fib5 = level - (trend * (High[0] - Low[0]) * 1.0);
    
    // Determine low and high swings of 15 minute timeframe
    low_15m = Low[0];
    high_15m = High[0];
    for (int i = 1; i < 16; i++)
    {
        if (Low[i] < low_15m) low_15m = Low[i];
        if (High[i] > high_15m) high_15m = High[i];
    }
    
    // Check if price is at Fibonacci retracement level
    double price = trend == -1 ? Bid : Ask;
    if (price <= fib4 && price >= fib5)
    {
        // Check if price is above 15 minute high swing for buy or below 15 minute low swing for sell
        if (trend == 1 && price > high_15m || trend == -1 && price < low_15m)
        {
            // Open trade at Fibonacci retracement level
            int ticket = OrderSend(_Symbol, OP_BUYSTOP, 0.01, price, 3, price - StopLoss * _Point, price + TakeProfit * _Point, "Fibonacci trade", 0, 0, clrGreen);
            if (ticket > 0) Print

            ("Buy order opened successfully");
        }
    }
}

// Expert Advisor deinitialization function
void OnDeinit(const int reason)
{
    // Perform cleanup tasks
}

// Utility function to print messages to the Experts log
void Print(const string message)
{
    Print("[Fibonacci Expert Advisor] " + message);
}

3 thoughts on “MetaTrader Expert Adviser Fibonacci retracement level to take trades”

Leave a Reply

Your email address will not be published. Required fields are marked *