Summary: BTCUSD Trend Guard EA is a low-risk MQL4 expert advisor for Bitcoin. It uses EMA trend direction, ATR volatility filter, and wide stop loss/take profit. Suitable for H4 timeframe.




BTCUSD Trend Guard EA is designed specifically for Bitcoin (BTCUSD) with a low-risk, stable operational approach. Bitcoin is known for extreme volatility, gaps, and sharp reversals. This EA uses a longer-term trend filter (EMA100), volatility-based entry (ATR), and very wide stop loss to avoid being stopped out by normal noise. Each trade has a fixed stop loss and take profit based on ATR multiples, with daily equity protection and spread control.

Recommended Timeframe: H4
Trading Logic:
  • Trend Filter: Price above EMA100 → long only; below → short only.

  • Entry Signal: After trend confirmation, wait for price to pull back within 1.5× ATR from EMA100, then enter on next bar open.

  • Volatility Guard: ATR(14) > 0.5% of price → reduce lot size by half.

  • Risk Control: Dynamic SL (2.5× ATR) and TP (5× ATR), max 1 trade at a time, daily loss limit 5%, maximum spread 100 points (1000 pips for BTC).


  • ``mql4
    //+------------------------------------------------------------------+
    //| BTCGuardEA.mq4 |
    //| |
    //| |
    //+------------------------------------------------------------------+
    #property copyright ""
    #property link ""
    #property version "1.00"
    #property strict

    //--- input parameters with comments
    input double LotSize = 0.01; // Fixed lot size (0.01 BTC = ~100 USD at 10k price)
    input int TrendMAPeriod = 100; // Period of EMA for trend filter (long-term)
    input int ATRPeriod = 14; // Period for ATR volatility indicator
    input double ATRStopMultiplier= 2.5; // Stop loss = ATR multiplier
    input double ATRTPMultiplier = 5.0; // Take profit = ATR
    multiplier (2:1 risk-reward)
    input double PullbackDistance = 1.5; // Max distance from EMA (in ATR units) to enter
    input double VolatilityReduceLot= 0.5; // If ATR > 0.5% of price, reduce lot by this factor
    input int MagicNumber = 202413; // Unique EA identifier
    input int MaxSpread = 100; // Maximum allowed spread (in points, BTC ~1000 pips = 100 points)
    input double DailyLossLimit = 5.0; // Daily loss limit in percentage of balance
    input bool UseCloseOnFriday = true; // Close all trades before Friday 21:00

    //--- global variables
    double dailyStartBalance = 0;
    datetime lastBarTime = 0;
    bool isFridayCloseExecuted = false;
    double lastATR = 0;

    //+------------------------------------------------------------------+
    //| Expert initialization function |
    //+------------------------------------------------------------------+
    int OnInit()
    {
    dailyStartBalance = AccountBalance();
    lastBarTime = 0;
    isFridayCloseExecuted = false;
    lastATR = iATR(Symbol(), PERIOD_H4, ATRPeriod, 1);
    if(lastATR <= 0) lastATR = 100;
    return(INIT_SUCCEEDED);
    }

    //+------------------------------------------------------------------+
    //| Expert deinitialization function |
    //+------------------------------------------------------------------+
    void OnDeinit(const int reason)
    {
    Comment("");
    }

    //+------------------------------------------------------------------+
    //| Expert tick function |
    //+------------------------------------------------------------------+
    void OnTick()
    {
    // Daily equity protection
    double currentEquity = AccountEquity();
    double lossPercent = (dailyStartBalance - currentEquity) / dailyStartBalance 100;
    if(lossPercent >= DailyLossLimit)
    {
    Comment("Daily loss limit reached. No new trades.");
    return;
    }

    // Friday close before weekend (crypto trades 24/7 but broker gaps exist)
    if(UseCloseOnFriday && !isFridayCloseExecuted)
    {
    datetime currentTime = TimeCurrent();
    if(TimeDayOfWeek(currentTime) == 5 && TimeHour(currentTime) >= 21)
    {
    CloseAllOrders();
    isFridayCloseExecuted = true;
    return;
    }
    if(TimeDayOfWeek(currentTime) != 5)
    isFridayCloseExecuted = false;
    }

    // Spread filter for Bitcoin (brokers may have wide spreads)
    if(MarketInfo(Symbol(), MODE_SPREAD) > MaxSpread)
    {
    Comment("Spread too high: ", MarketInfo(Symbol(), MODE_SPREAD));
    return;
    }

    // New bar logic (H4)
    if(Time[0] == lastBarTime)
    return;
    lastBarTime = Time[0];

    // Check for existing position
    if(CountPositions() > 0)
    return;

    // Get current ATR
    double atr = iATR(Symbol(), PERIOD_H4, ATRPeriod, 1);
    if(atr <= 0) atr = lastATR;
    lastATR = atr;

    // Volatility-based lot adjustment
    double currentPrice = iClose(Symbol(), PERIOD_H4, 1);
    double pricePercentVol = atr / currentPrice;
    double actualLot = LotSize;
    if(pricePercentVol > 0.005) // ATR > 0.5% of price
    {
    actualLot = LotSize
    VolatilityReduceLot;
    if(actualLot < 0.01) actualLot = 0.01;
    }

    // Trend filter using EMA100
    double ema = iMA(Symbol(), PERIOD_H4, TrendMAPeriod, 0, MODE_EMA, PRICE_CLOSE, 1);
    double close1 = iClose(Symbol(), PERIOD_H4, 1);
    double close2 = iClose(Symbol(), PERIOD_H4, 2);

    // Pullback detection: distance from EMA in ATR units
    double distanceFromEMA = MathAbs(close1 - ema) / atr;
    bool nearEMA = (distanceFromEMA <= PullbackDistance);

    int cmd = -1;
    double sl = 0, tp = 0;

    // Long condition: uptrend, price above EMA, near EMA after pullback, previous bar bullish
    if(close1 > ema && close2 > ema && nearEMA && close1 > iOpen(Symbol(), PERIOD_H4, 1))
    {
    cmd = OP_BUY;
    sl = SymbolInfoDouble(Symbol(), SYMBOL_BID) - (atr ATRStopMultiplier);
    tp = SymbolInfoDouble(Symbol(), SYMBOL_BID) + (atr
    ATRTPMultiplier);
    }
    // Short condition: downtrend, price below EMA, near EMA after pullback, previous bar bearish
    else if(close1 < ema && close2 < ema && nearEMA && close1 < iOpen(Symbol(), PERIOD_H4, 1))
    {
    cmd = OP_SELL;
    sl = SymbolInfoDouble(Symbol(), SYMBOL_ASK) + (atr ATRStopMultiplier);
    tp = SymbolInfoDouble(Symbol(), SYMBOL_ASK) - (atr
    ATRTPMultiplier);
    }

    if(cmd != -1)
    {
    int ticket = OrderSend(Symbol(), cmd, actualLot, (cmd==OP_BUY?Ask:Bid), 3, sl, tp, "BTC Guard EA", MagicNumber, 0, clrNONE);
    if(ticket < 0)
    Print("OrderSend failed: ", GetLastError());
    }
    }

    //+------------------------------------------------------------------+
    //| Count open positions with this MagicNumber |
    //+------------------------------------------------------------------+
    int CountPositions()
    {
    int count = 0;
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    count++;
    }
    }
    return count;
    }

    //+------------------------------------------------------------------+
    //| Close all orders for this symbol and magic |
    //+------------------------------------------------------------------+
    void CloseAllOrders()
    {
    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
    {
    if(OrderSymbol() == Symbol() && OrderMagicNumber() == MagicNumber)
    {
    if(OrderType() == OP_BUY)
    OrderClose(OrderTicket(), OrderLots(), Bid, 3, clrNONE);
    else if(OrderType() == OP_SELL)
    OrderClose(OrderTicket(), OrderLots(), Ask, 3, clrNONE);
    }
    }
    }
    }
    //+------------------------------------------------------------------+
    ``
    Reference: Original MQL4 code for educational purposes.
    Disclaimer: Bitcoin and cryptocurrency trading carries extremely high risk. This EA is provided as-is without any guarantee of profit. Test thoroughly on demo before live trading. Past performance does not guarantee future results.