DEV Community

Cover image for Build vs Buy: Should You Code Your Own TradingView Webhook Listener in Python?
Sraboni Sarker
Sraboni Sarker

Posted on Edited on

Build vs Buy: Should You Code Your Own TradingView Webhook Listener in Python?

If you trade forex and write a little Python, sooner or later you'll have this thought:

> "TradingView can send a webhook. MT5 has a Python package. How hard can it be to glue them together?"

Not very hard to get working. Quite a bit harder to keep working when real money is on the line.

This post walks through what a minimal TradingView → Python → MT5 listener looks like, the parts tutorials usually skip, and a simple way to decide whether you should build it yourself or use a hosted tool.

How the pieces fit together

The flow is short:

  1. A TradingView alert fires (from a Pine Script strategy or a manual alert).
  2. TradingView sends an HTTP POST to your webhook URL with the alert message as the body.
  3. Your server reads that message, works out the order, and sends it to your broker's platform.
  4. For MT5, that usually means the official MetaTrader5 Python package talking to a running MT5 terminal.

A few TradingView rules worth knowing before you write any code:

  • Webhook alerts need a paid TradingView plan, and two-factor authentication must be enabled on the account.
  • TradingView only sends to port 80 or 443. So no :5000 URLs in production. You need a reverse proxy or a platform that gives you HTTPS.
  • If the alert message is valid JSON, it's sent as application/json; otherwise as plain text.
  • TradingView expects a fast response. If your endpoint takes more than a few seconds, the request can time out.

That last point affects how you design the listener.

A minimal listener (FastAPI)

Let's say your TradingView alert message looks like this:

{
  "secret": "change-me",
  "symbol": "EURUSD",
  "side": "buy",
  "volume": 0.10,
  "sl": 1.0820,
  "tp": 1.0910,
  "alert_id": "{{timenow}}-{{ticker}}"
}
Enter fullscreen mode Exit fullscreen mode

{{timenow}} and {{ticker}} are TradingView placeholders, so each alert gets a reasonably unique ID.

Here's a small FastAPI app that receives it:

# app.py
import os
from fastapi import FastAPI, Request, HTTPException, BackgroundTasks
from pydantic import BaseModel, Field

app = FastAPI()

WEBHOOK_SECRET = os.environ["WEBHOOK_SECRET"]

# TradingView's published webhook source IPs (check their docs for updates)
TV_IPS = {"52.89.214.238", "34.212.75.30", "54.218.53.128", "52.32.178.7"}

seen_ids: set[str] = set()  # use Redis or a DB in real life


class Alert(BaseModel):
    secret: str
    symbol: str
    side: str = Field(pattern="^(buy|sell)$")
    volume: float = Field(gt=0, le=5)
    sl: float | None = None
    tp: float | None = None
    alert_id: str


@app.post("/webhook")
async def webhook(alert: Alert, request: Request, tasks: BackgroundTasks):
    # 1. Only accept requests from TradingView
    client_ip = request.headers.get("x-forwarded-for", request.client.host).split(",")[0].strip()
    if client_ip not in TV_IPS:
        raise HTTPException(status_code=403)

    # 2. Check the shared secret
    if alert.secret != WEBHOOK_SECRET:
        raise HTTPException(status_code=401)

    # 3. Ignore duplicates (retries, double-fired alerts)
    if alert.alert_id in seen_ids:
        return {"status": "duplicate"}
    seen_ids.add(alert.alert_id)

    # 4. Respond fast, place the order in the background
    tasks.add_task(place_order, alert)
    return {"status": "accepted"}
Enter fullscreen mode Exit fullscreen mode

Three things are already doing real work here:

  • IP allowlist + secret: your webhook URL will leak eventually (screenshots, shared Pine scripts, logs). Without these checks, anyone with the URL can open trades on your account.
  • Duplicate check: alerts can fire twice. Without an ID check you get double positions.
  • Background task: you answer TradingView immediately and do the slow broker work afterwards.

Sending the order to MT5

# broker.py
import MetaTrader5 as mt5

SYMBOL_MAP = {"EURUSD": "EURUSD.m"}  # broker suffixes differ!


def place_order(alert):
    if not mt5.initialize():
        print("MT5 init failed:", mt5.last_error())
        return

    symbol = SYMBOL_MAP.get(alert.symbol, alert.symbol)
    if not mt5.symbol_select(symbol, True):
        print("Symbol not available:", symbol)
        return

    tick = mt5.symbol_info_tick(symbol)
    is_buy = alert.side == "buy"

    request = {
        "action": mt5.TRADE_ACTION_DEAL,
        "symbol": symbol,
        "volume": alert.volume,
        "type": mt5.ORDER_TYPE_BUY if is_buy else mt5.ORDER_TYPE_SELL,
        "price": tick.ask if is_buy else tick.bid,
        "sl": alert.sl or 0.0,
        "tp": alert.tp or 0.0,
        "deviation": 20,
        "magic": 240501,
        "comment": "tv-webhook",
        "type_time": mt5.ORDER_TIME_GTC,
        "type_filling": mt5.ORDER_FILLING_IOC,
    }

    result = mt5.order_send(request)
    if result is None or result.retcode != mt5.TRADE_RETCODE_DONE:
        print("Order failed:", result)
    else:
        print("Order placed:", result.order)
Enter fullscreen mode Exit fullscreen mode

Run it with uvicorn app:app, put it behind HTTPS, paste the URL into a TradingView alert, and you have working automation.

The part tutorials skip

The code above is roughly a weekend of work. Running it for months is the harder part.

1. The MT5 package needs Windows and a running terminal.
The MetaTrader5 Python package talks to a local MT5 terminal. That terminal has to be open, logged in and connected, 24/5. In practice, that means a Windows VPS, which usually costs somewhere around $10–40 a month depending on the provider. Then you're also patching Windows and dealing with restarts.

2. Broker quirks add up.
EURUSD vs EURUSD.m vs EURUSDpro. Different filling modes (IOC, FOK, RETURN) per broker. Minimum lot sizes and lot steps. Stops that are too close to price. Each one is a small fix, and each one usually shows up first as a missed trade.

3. Lot sizing is rarely "just 0.10".
Once you want risk-based sizing (e.g., 1% of balance with a given SL distance), or different sizes for different accounts, your "simple listener" now has a position-sizing engine.

4. Monitoring is on you.
If the VPS reboots at 3 a.m. or the MT5 terminal logs out, nothing tells you. You find out when a trade didn't open. You'll want health checks, alerts (Telegram or email), and logs you can read.

5. Security is ongoing.
Rotating secrets, keeping the IP allowlist up to date, protecting the broker login on the server, keeping dependencies patched. None of it is hard, but someone has to do it.

6. More platforms, more code.
MT5 has a Python package. cTrader, DXTrade, and TradeLocker each have their own APIs and auth flows. Supporting a second platform roughly doubles the integration work.

Build vs buy: a quick checklist

Building your own makes sense if:

  • You enjoy the engineering and want full control over the logic.
  • You trade one account on one platform with one broker.
  • You already run servers and are comfortable maintaining a Windows VPS.
  • Your strategy needs custom logic no tool offers (e.g. calling your own ML model before placing an order).

A hosted tool makes more sense if:

  • You care more about the trading than the plumbing.
  • You don't want to pay for and look after a VPS.
  • You trade several accounts, or more than one platform.
  • You want risk-based lot sizing, symbol mapping, and logs without writing them yourself.
  • A missed trade costs you more than a monthly subscription.

A middle path also works well: prototype your own listener to understand how webhooks behave, then move live trading to a hosted service once you know exactly what you need.

What the hosted route looks like

Hosted TradingView webhook tools handle the parts listed above for you: an HTTPS endpoint, authentication, symbol mapping, lot sizing, and the broker connection, running in the cloud, so you don't need a VPS or an EA on your machine.

For example, trade2sync gives you a webhook URL you paste into your TradingView alert, and it places the trade on your connected MT4, MT5, cTrader, DXTrade, or TradeLocker account from the cloud. Your alert message stays simple, and the broker side is handled for you.

Whichever tool you look at, check:

  • Does it run in the cloud, or does it still need your PC/VPS online?
  • How does it secure the webhook (tokens, IP checks)?
  • Can it map broker symbol suffixes and calculate lot size from risk?
  • Does it keep logs, so you can see why a trade did or didn't open?

Wrapping up

Writing a TradingView webhook listener in Python is a great learning project, and the core of it fits in under 100 lines. The real cost is in running it: the VPS, the broker edge cases, the monitoring, and the security.

If you enjoy that work, build it, and use the snippets above as a starting point. If you'd rather spend your time on strategy, a hosted webhook tool will usually be cheaper than your time.

Have you built your own TradingView → broker bridge? I'd love to hear what broke first. Drop it in the comments. 👇

Top comments (0)