""
Gold (XAUUSD) scalping bot for Deriv MT5
----------------------------------------
Fast, aggressive M1 scalper with hard risk controls.
Setup (Windows only, MT5 terminal must be installed and logged in to your Deriv MT5 account):
pip install MetaTrader5 pandas numpy
python gold_bot.py
START ON A DEMO ACCOUNT. Aggressive scalping can lose money fast.
"""
import time
import logging
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import MetaTrader5 as mt5
# ============================== SETTINGS ==============================
SYMBOL = "XAUUSD" # check the exact name in your Market Watch (may be "XAUUSD" or "XAU/USD")
TIMEFRAME = mt5.TIMEFRAME_M1
MAGIC = 20260311
# Login (leave None to use whatever account the open MT5 terminal is logged in to)
LOGIN = None
PASSWORD = None
SERVER = None
# Risk
RISK_PER_TRADE_PCT = 1.0 # % of balance risked per trade (aggressive = 1-2, safer = 0.25-0.5)
MAX_OPEN_POSITIONS = 3
MAX_DAILY_LOSS_PCT = 5.0 # bot stops trading for the day at this loss
MAX_DAILY_PROFIT_PCT = 10.0 # optional: lock in a great day (set 0 to disable)
MAX_CONSEC_LOSSES = 4 # pause after this many losses in a row
PAUSE_MINUTES_AFTER_LOSSES = 30
MIN_LOT_OVERRIDE = None # e.g. 0.01 to force a lot size instead of risk-based sizing
# Strategy
EMA_FAST, EMA_SLOW, EMA_TREND = 9, 21, 100
RSI_PERIOD = 14
ATR_PERIOD = 14
BREAKOUT_LOOKBACK = 10
SL_ATR = 1.2 # stop loss = 1.2 x ATR
TP_ATR = 1.8 # take profit = 1.8 x ATR
BREAKEVEN_ATR = 0.8 # move SL to breakeven after this much profit (in ATR)
TRAIL_ATR = 1.0 # then trail the stop this many ATR behind price
MAX_SPREAD_POINTS = 40 # skip trades when spread is wider than this (news / rollover)
MIN_ATR_POINTS = 30 # skip dead markets
TRADE_HOURS_UTC = (7, 20) # London open to NY afternoon, where gold moves most. Set None for 24h
COOLDOWN_SECONDS = 60 # min time between entries
DEVIATION = 20 # max slippage in points
# =====================================================================
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s",
handlers=[logging.StreamHandler(), logging.FileHandler("gold_bot.log")],
)
log = logging.getLogger("gold_bot")
# ------------------------------ Indicators ------------------------------
def ema(s, n):
return s.ewm(span=n, adjust=False).mean()
def rsi(close, n=14):
d = close.diff()
up = d.clip(lower=0).ewm(alpha=1 / n, adjust=False).mean()
dn = (-d.clip(upper=0)).ewm(alpha=1 / n, adjust=False).mean()
rs = up / dn.replace(0, np.nan)
return 100 - 100 / (1 + rs)
def atr(df, n=14):
pc = df["close"].shift()
tr = pd.concat([df["high"] - df["low"], (df["high"] - pc).abs(), (df["low"] - pc).abs()], axis=1).max(axis=1)
return tr.ewm(alpha=1 / n, adjust=False).mean()
def get_data(n=300):
rates = mt5.copy_rates_from_pos(SYMBOL, TIMEFRAME, 0, n)
if rates is None or len(rates) < EMA_TREND + 5:
return None
df = pd.DataFrame(rates)
df["time"] = pd.to_datetime(df["time"], unit="s")
df["ef"] = ema(df["close"], EMA_FAST)
df["es"] = ema(df["close"], EMA_SLOW)
df["et"] = ema(df["close"], EMA_TREND)
df["rsi"] = rsi(df["close"], RSI_PERIOD)
df["atr"] = atr(df, ATR_PERIOD)
df["hh"] = df["high"].shift(1).rolling(BREAKOUT_LOOKBACK).max()
df["ll"] = df["low"].shift(1).rolling(BREAKOUT_LOOKBACK).min()
return df
# ------------------------------ Signal ------------------------------
def get_signal(df):
"""Uses the last CLOSED candle (index -2). Returns ('buy'|'sell'|None, atr_value)."""
c, p = df.iloc[-2], df.iloc[-3]
a = c["atr"]
if np.isnan(a):
return None, a
uptrend = c["close"] > c["et"] and c["ef"] > c["es"]
downtrend = c["close"] < c["et"] and c["ef"] < c["es"]
# 1) Momentum cross in trend direction
cross_up = p["ef"] <= p["es"] and c["ef"] > c["es"]
cross_dn = p["ef"] >= p["es"] and c["ef"] < c["es"]
# 2) Breakout with strong candle body
body = abs(c["close"] - c["open"])
strong = body > 0.6 * a
break_up = c["close"] > c["hh"] and strong and c["close"] > c["open"]
break_dn = c["close"] < c["ll"] and strong and c["close"] < c["open"]
if uptrend and (cross_up or break_up) and 50 < c["rsi"] < 78:
return "buy", a
if downtrend and (cross_dn or break_dn) and 22 < c["rsi"] < 50:
return "sell", a
return None, a
# ------------------------------ MT5 helpers ------------------------------
def connect():
ok = mt5.initialize(login=LOGIN, password=PASSWORD, server=SERVER) if LOGIN else mt5.initialize()
if not ok:
raise SystemExit(f"MT5 init failed: {mt5.last_error()}")
if not mt5.symbol_select(SYMBOL, True):
raise SystemExit(f"Symbol {SYMBOL} not found. Check the exact name in Market Watch.")
acc = mt5.account_info()
log.info(f"Connected | account {acc.login} | balance {acc.balance} {acc.currency} | server {acc.server}")
def filling_mode():
info = mt5.symbol_info(SYMBOL)
fm = info.filling_mode
if fm & 1:
return mt5.ORDER_FILLING_FOK
if fm & 2:
return mt5.ORDER_FILLING_IOC
return mt5.ORDER_FILLING_RETURN
def calc_lot(sl_distance):
if MIN_LOT_OVERRIDE:
return MIN_LOT_OVERRIDE
info = mt5.symbol_info(SYMBOL)
bal = mt5.account_info().balance
risk_money = bal * RISK_PER_TRADE_PCT / 100
loss_per_lot = sl_distance / info.trade_tick_size * info.trade_tick_value
if loss_per_lot <= 0:
return info.volume_min
lot = risk_money / loss_per_lot
step = info.volume_step
lot = max(info.volume_min, min(info.volume_max, np.floor(lot / step) * step))
return round(lot, 2)
def my_positions():
pos = mt5.positions_get(symbol=SYMBOL)
return [p for p in (pos or []) if p.magic == MAGIC]
def open_trade(side, a):
tick = mt5.symbol_info_tick(SYMBOL)
info = mt5.symbol_info(SYMBOL)
digits = info.digits
sl_d, tp_d = SL_ATR * a, TP_ATR * a
# respect broker minimum stop distance
min_d = info.trade_stops_level * info.point
sl_d, tp_d = max(sl_d, min_d * 1.1), max(tp_d, min_d * 1.1)
if side == "buy":
price, sl, tp, typ = tick.ask, tick.ask - sl_d, tick.ask + tp_d, mt5.ORDER_TYPE_BUY
else:
price, sl, tp, typ = tick.bid, tick.bid + sl_d, tick.bid - tp_d, mt5.ORDER_TYPE_SELL
lot = calc_lot(sl_d)
req = {
"action": mt5.TRADE_ACTION_DEAL,
"symbol": SYMBOL,
"volume": lot,
"type": typ,
"price": price,
"sl": round(sl, digits),
"tp": round(tp, digits),
"deviation": DEVIATION,
"magic": MAGIC,
"comment": "gold_bot",
"type_time": mt5.ORDER_TIME_GTC,
"type_filling": filling_mode(),
}
res = mt5.order_send(req)
if res is None or res.retcode != mt5.TRADE_RETCODE_DONE:
log.warning(f"Order failed: {res.retcode if res else mt5.last_error()} {getattr(res, 'comment', '')}")
return False
log.info(f"OPENED {side.upper()} {lot} lots @ {price} SL {sl:.2f} TP {tp:.2f}")
return True
def manage_positions(a):
"""Breakeven + ATR trailing stop."""
info = mt5.symbol_info(SYMBOL)
tick = mt5.symbol_info_tick(SYMBOL)
digits = info.digits
min_d = info.trade_stops_level * info.point
for p in my_positions():
if p.type == mt5.POSITION_TYPE_BUY:
profit_d = tick.bid - p.price_open
if profit_d >= BREAKEVEN_ATR * a:
new_sl = max(p.price_open + info.point * 2, tick.bid - TRAIL_ATR * a)
if new_sl > p.sl and tick.bid - new_sl >= min_d:
modify_sl(p, round(new_sl, digits))
else:
profit_d = p.price_open - tick.ask
if profit_d >= BREAKEVEN_ATR * a:
new_sl = min(p.price_open - info.point * 2, tick.ask + TRAIL_ATR * a)
if (p.sl == 0 or new_sl < p.sl) and new_sl - tick.ask >= min_d:
modify_sl(p, round(new_sl, digits))
def modify_sl(p, new_sl):
req = {"action": mt5.TRADE_ACTION_SLTP, "symbol": SYMBOL, "position": p.ticket, "sl": new_sl, "tp": p.tp, "magic": MAGIC}
res = mt5.order_send(req)
if res and res.retcode == mt5.TRADE_RETCODE_DONE:
log.info(f"Stop moved on #{p.ticket} -> {new_sl}")
def today_stats():
"""Returns (pnl_today, consecutive_losses, last_loss_time)."""
start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
deals = mt5.history_deals_get(start - timedelta(hours=3), datetime.now() + timedelta(hours=3))
deals = [d for d in (deals or []) if d.magic == MAGIC and d.entry == mt5.DEAL_ENTRY_OUT]
deals.sort(key=lambda d: d.time)
pnl = sum(d.profit + d.commission + d.swap for d in deals)
streak, last_loss = 0, None
for d in reversed(deals):
if d.profit + d.commission + d.swap < 0:
streak += 1
last_loss = last_loss or datetime.fromtimestamp(d.time)
else:
break
return pnl, streak, last_loss
def in_session():
if not TRADE_HOURS_UTC:
return True
h = datetime.utcnow().hour
return TRADE_HOURS_UTC[0] <= h < TRADE_HOURS_UTC[1] and datetime.utcnow().weekday() < 5
# ------------------------------ Main loop ------------------------------
def main():
connect()
last_bar = None
last_entry = 0
log.info("Bot running. Ctrl+C to stop.")
try:
while True:
df = get_data()
if df is None:
time.sleep(2)
continue
a = df.iloc[-2]["atr"]
manage_positions(a) # runs every loop so trailing is fast
bar_time = df.iloc[-1]["time"]
if bar_time == last_bar:
time.sleep(1)
continue
last_bar = bar_time # new candle opened -> evaluate once per candle
# ----- guards -----
info = mt5.symbol_info(SYMBOL)
if info.spread > MAX_SPREAD_POINTS:
log.info(f"Spread too wide ({info.spread}), skipping")
continue
if a / info.point < MIN_ATR_POINTS:
continue
if not in_session():
continue
if len(my_positions()) >= MAX_OPEN_POSITIONS:
continue
if time.time() - last_entry < COOLDOWN_SECONDS:
continue
bal = mt5.account_info().balance
pnl, streak, last_loss = today_stats()
if pnl <= -bal * MAX_DAILY_LOSS_PCT / 100:
log.warning(f"Daily loss limit hit ({pnl:.2f}). Done for today.")
continue
if MAX_DAILY_PROFIT_PCT and pnl >= bal * MAX_DAILY_PROFIT_PCT / 100:
log.info(f"Daily profit target hit ({pnl:.2f}). Done for today.")
continue
if streak >= MAX_CONSEC_LOSSES and last_loss and datetime.now() - last_loss < timedelta(minutes=PAUSE_MINUTES_AFTER_LOSSES):
log.info(f"{streak} losses in a row, cooling off.")
continue
# ----- entry -----
side, a = get_signal(df)
if side:
# don't stack same-direction trades on the same candle
if open_trade(side, a):
last_entry = time.time()
except KeyboardInterrupt:
log.info("Stopped by user.")
finally:
mt5.shutdown()
if __name__ == "__main__":
main()

New comment