TradingView Alerts to MT5: How to Automate Trades with Webhooks

TradingView cannot place trades on MetaTrader 5 directly, because MT5 has no way to receive a webhook. To automate TradingView alerts on MT5 you put a small server in between: TradingView sends the alert to the server, and the server places the order in MT5. This guide explains the options and builds a working bridge in Python.

The three ways to connect TradingView to MT5

  • A webhook server using the MetaTrader5 Python package. A Python script receives the alert and sends the order to an MT5 terminal on the same Windows machine. This is the approach built below. You own all of it.
  • An Expert Advisor that polls a server. The server stores incoming alerts, and an EA inside MT5 asks for new ones every second or so using WebRequest. It needs more code, but the trading logic stays inside MT5.
  • A third-party bridge service. You install their EA and pay a subscription. It is the fastest to set up, but your signals pass through someone else's servers and you are limited to their features.

There is also a fourth route that avoids the bridge completely: convert the Pine Script strategy to MQL5 and run it as a native EA. That is usually the most reliable option when the whole strategy can be expressed in code.

What you need

  • A paid TradingView plan. Webhook alerts are not available on the free plan, and two-factor authentication must be enabled on your TradingView account.
  • A Windows VPS. The official MetaTrader5 Python package only runs on Windows, next to an installed MT5 terminal.
  • MT5 logged in to your broker account with Algo Trading enabled.
  • A public HTTPS address for the server. TradingView only sends webhooks to ports 80 and 443.

Step 1: Design the alert message

The alert carries everything the server needs as JSON. Include a secret so nobody else can send orders to your server.

{
  "secret": "long-random-string",
  "symbol": "EURUSD",
  "side": "buy",
  "volume": 0.10,
  "sl_points": 300,
  "tp_points": 600,
  "id": "{{timenow}}-{{ticker}}"
}

In a strategy alert you can use {{strategy.order.action}} for the side, so one alert covers both buys and sells. Paste the JSON into the alert's message box and put your server address in the webhook URL field.

Step 2: Build the webhook server

pip install flask MetaTrader5
import MetaTrader5 as mt5
from flask import Flask, request, jsonify

SECRET = "long-random-string"
MAGIC = 20261101
seen_ids = set()

app = Flask(__name__)
if not mt5.initialize():
    raise SystemExit(f"MT5 initialize failed: {mt5.last_error()}")

def place_order(symbol, side, volume, sl_points, tp_points):
    info = mt5.symbol_info(symbol)
    if info is None or not mt5.symbol_select(symbol, True):
        return None, "unknown symbol"
    tick = mt5.symbol_info_tick(symbol)
    buy = side == "buy"
    price = tick.ask if buy else tick.bid
    point = info.point
    sl = price - sl_points * point if buy else price + sl_points * point
    tp = price + tp_points * point if buy else price - tp_points * point

    result = mt5.order_send({
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": float(volume),
        "type": mt5.ORDER_TYPE_BUY if buy else mt5.ORDER_TYPE_SELL,
        "price": price,
        "sl": round(sl, info.digits),
        "tp": round(tp, info.digits),
        "deviation": 20,
        "magic": MAGIC,
        "comment": "tradingview",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC,
    })
    if result is None:
        return None, str(mt5.last_error())
    if result.retcode != mt5.TRADE_RETCODE_DONE:
        return None, f"retcode {result.retcode}: {result.comment}"
    return result.order, None

@app.post("/webhook")
def webhook():
    data = request.get_json(silent=True) or {}
    if data.get("secret") != SECRET:
        return jsonify(error="unauthorized"), 401
    if data.get("id") in seen_ids:
        return jsonify(status="duplicate ignored")
    seen_ids.add(data.get("id"))

    if data.get("side") not in ("buy", "sell"):
        return jsonify(error="bad side"), 400

    order, error = place_order(data["symbol"], data["side"], data["volume"],
                               data["sl_points"], data["tp_points"])
    if error:
        return jsonify(error=error), 500
    return jsonify(status="ok", order=order)

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=5000)

This is the minimum that works. It checks the secret, ignores a repeated alert, attaches a stop loss and take profit, and reports the reason when MT5 rejects the order.

Step 3: Put it online safely

  • Run the script on the Windows VPS next to the MT5 terminal.
  • Put a reverse proxy with an HTTPS certificate in front of it, listening on port 443 and forwarding to the script. The script itself stays bound to localhost.
  • Respond quickly. TradingView drops a webhook request that takes more than a few seconds, so place the order and return without long waits.
  • Start the script automatically when the server boots, and restart it if it stops.

Step 4: Add the checks a real account needs

  • Position check. Before a buy, look at mt5.positions_get(symbol=symbol) and decide what should happen if you are already long.
  • Closing trades. Add a "close" action that closes positions with your magic number.
  • Lot sizing. Calculate the volume on the server from account balance and stop distance, so the alert does not have to carry a fixed lot.
  • Symbol mapping. TradingView's ticker and your broker's symbol often differ, for example XAUUSD and XAUUSD.m. Keep a mapping table.
  • Persistent duplicate protection. Store handled alert IDs in a file or database so a restart does not forget them.
  • Daily loss limit. Stop accepting new entries after a set loss for the day.
  • Logging and alerts. Write every alert and result to a log, and send failures to Telegram.

Common problems

  • Retcode 10030, unsupported filling mode. Your broker does not accept IOC for that symbol. Try ORDER_FILLING_FOK or ORDER_FILLING_RETURN.
  • Retcode 10016, invalid stops. The stop is closer than the broker's minimum distance.
  • Retcode 10027, autotrading disabled. Turn on the Algo Trading button in the terminal.
  • Alert fires but nothing arrives. The webhook URL is not reachable from the internet, is not on port 80 or 443, or the alert was created without the webhook option ticked.
  • Signals differ from the chart. The strategy repaints or the alert triggers before the bar closes. Use "once per bar close" for bar-based strategies.

Frequently asked questions

How fast are orders placed?

Usually within a few seconds of the alert. Most of the delay is TradingView delivering the webhook.

Can this run on Mac or Linux?

The MetaTrader5 Python package is Windows only. On other systems, use the EA polling approach or a Windows VPS.

Does it work with prop firm accounts?

Technically yes, since it is a normal MT5 account. Check your firm's rules on automated trading first.

Should I use a bridge or convert the strategy to an EA?

If the full strategy is in Pine Script, converting it removes the dependency on TradingView alerts. If you rely on TradingView indicators you cannot reproduce, a bridge is the way.

Want it built for you?

We build private TradingView bridges and convert strategies to native EAs, with full source code. See MT5 Expert Advisor (EA) development and Pine Script to MQL5 conversion. Trading on Interactive Brokers instead? See TradingView to IBKR automation.