Episode 35 · AI Trading · Building a Complete Trading System

A TradingView webhook receiver that only notifies

Check JSON, symbol, age, a receiver code and event_id, answer within 3 seconds, then tell Telegram; duplicates and restarts never announce an event twice.

What does a webhook need (TradingView sending an alert to your machine over HTTP), and how do you handle messages that are duplicated, old or wrong?

This post builds a receiver that checks the JSON, the symbol, the signal’s age and the event_id, answers within 3 seconds, and only then sends to Telegram. The easy mistake: reading HTTP 200 (success) as more than it is. It only means the receiver recorded the event. A TradingView webhook is for notifying you, never for feeding an EA or a demo order.

Terms used below:

  • Webhook: an HTTP POST that TradingView sends to a URL you give it when an alert fires.
  • Receiver: the small server on your side that takes that POST.
  • Idempotency: handling the same event many times without creating extra notifications or records.
  • Ack: the receiver’s quick answer that it got the request.

TradingView’s conditions (checked 2026-11-11)

Gate Question If not
Input Your TradingView account
1 Essential plan or higher? The free Basic plan has no webhooks
2 Two-factor authentication (2FA) on? Webhooks can’t be used yet
3 A public URL on port 80 or 443? Other ports are refused; a private localhost doesn’t receive
4 An IPv4 address? IPv6 isn’t supported yet
Passed Create the alert: turn on Webhook URL, paste the JSON message
  • Plans: webhooks come with paid plans from Essential up (Essential, Plus, Premium, Ultimate); the free Basic plan doesn’t have them. The account needs 2FA turned on.
  • The request: TradingView sends an HTTP POST to the URL you enter, on port 80 or 443 only; IPv6 isn’t supported. If the message is valid JSON, the request has content-type application/json; otherwise text/plain.
  • 3 seconds: if the receiver takes longer, the request is cancelled. So the receiver checks quickly, logs and answers at once; Telegram comes after.
  • No promised resend: nothing says TradingView will send again, and a webhook can fail to arrive. Read the Webhook status column in the Alert log.
  • Checking the sender: an HTTPS receiver can check the client SSL certificate TradingView sends with the request, or accept only TradingView’s published IP addresses.
  • Alerts are copies: an alert runs on TradingView’s servers with a copy of the script and inputs from when it was created. Change an input or the code, and you delete the old alert and create a new one.

TradingView’s Terms of Use (sections 3 and 27, checked 2026-11-27) license alerts and webhooks for display only. They prohibit using them for automated trading, automatic order generation, order checks or algorithmic decisions, with no exception for demo accounts. So the receiver here only logs and sends you a message to read; it never forwards anything to an EA or a broker.

Allowed: notify you Prohibited, demo accounts included
Write a log Forward to an EA or a broker
Send a Telegram message that it arrived Automated trading, automatic orders
Compare with the Webhook status column in the Alert log Order checks, algorithmic decisions

What the receiver checks before it logs

The JSON has system_version, event_id, symbol, timeframe, the bar time, the time it was sent, action (only a label for the message), the label DEMO, and a receiver code. The receiver checks the code, the schema, the allowed symbols, the age and whether the event was already processed, logs, and answers within 3 seconds; Telegram goes after the answer. Start with simulated requests on your own machine. TradingView on the internet can’t reach your localhost; that needs a public HTTPS URL (port 443) set up as a separate job, and no account key ever goes in the body.

Gate Question If not
Input HTTP POST from a TradingView alert
1 Valid JSON? Reject, log the reason
2 The right receiver code in the message? Reject: missing or wrong code (403)
3 Every field present, label DEMO? Reject: schema
4 Symbol on the allowed list? Reject: unknown symbol
5 Signal not too old? Reject: stale timestamp
6 event_id not processed yet? Log a duplicate, send nothing more
Passed Log, answer within 3 seconds, then send to Telegram

Every rejected request has its reason in the log.

The receiver code isn’t an account password or API key. It’s a random string only this receiver knows, so a stranger who finds the URL can’t post fake alerts. It sits in your TradingView alert message, so if it leaks, change it and edit the alerts.

One event arriving more than once

event_id=demo-001 arrives twice, say because two alerts share the same condition, or you resent a test after the receiver answered slowly.

  • First time: valid, store the ID, ack within 3 seconds, then send one notification.
  • Second time: the ID is known; log one duplicate line and send nothing more.
  • Stale requests and unknown symbols are rejected with a reason.
  • The message says “signal received”. The webhook path has no orders, so it never says “trade filled”.
When Step What
Request arrives Receive the HTTP POST Valid JSON: application/json; otherwise text/plain
Within 3 seconds Check fast, log Code, schema, symbol, age, event_id
Before 3 seconds run out Answer (ack) Only means it was received and recorded
After the answer Send to Telegram “signal received”, never “trade filled”

Worked example: the same webhook three times

Build a stable event_id from the rule version, symbol, timeframe, bar time and direction. Never generate a new random number for each resend of the same event, or deduplication can’t work. Store processed IDs durably, in a file or SQLite. Kept only in memory, a restart forgets them and announces old events again.

The receiver, src/receiver.py. It uses Python’s standard library and src/notifier.py from the Telegram post, listens on 127.0.0.1 only, and never writes the receiver code to the log:

# src/receiver.py: receive TradingView webhook alerts, check them, record them once, answer at once, then tell Telegram.
# Notification only: nothing here reaches an EA, a broker or a demo account.
#   .venv\Scripts\python src\receiver.py      listens on 127.0.0.1:8765 for local tests
import hmac, json, os, queue, sqlite3, sys, threading, time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
import notifier  # noqa: E402  (src/notifier.py from the Telegram post)

ROOT = Path(__file__).resolve().parent.parent
ALLOWED = {"XAUUSD", "EURUSD", "BTCUSD"}
FIELDS = ("system_version", "event_id", "symbol", "timeframe", "bar_time", "sent_at", "action", "label", "code")
MAX_AGE = 120        # seconds from TradingView's {{timenow}} to arrival
MAX_BODY = 4096


class Store:
    """Processed event_ids in SQLite, so a restart doesn't announce old events again."""
    def __init__(self, path):
        Path(path).parent.mkdir(parents=True, exist_ok=True)
        self.db = sqlite3.connect(path, check_same_thread=False)
        self.lock = threading.Lock()
        self.db.execute("CREATE TABLE IF NOT EXISTS events (event_id TEXT PRIMARY KEY, received_at TEXT, symbol TEXT,"
                        " timeframe TEXT, bar_time TEXT, action TEXT, notified INTEGER DEFAULT 0)")

    def add(self, e, now):
        with self.lock:
            try:
                self.db.execute("INSERT INTO events VALUES (?,?,?,?,?,?,0)", (e["event_id"], now.isoformat(),
                                e["symbol"], e["timeframe"], e["bar_time"], e["action"]))
                self.db.commit()
                return True
            except sqlite3.IntegrityError:
                return False

    def mark(self, event_id, value):
        with self.lock:
            self.db.execute("UPDATE events SET notified=? WHERE event_id=?", (value, event_id))
            self.db.commit()


def parse_utc(text):
    return datetime.strptime(text, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)


def check(body, store, secret, now):
    """Returns (http_status, result, reason, event). Fast: no network in here."""
    try:
        e = json.loads(body)
    except ValueError:
        return 400, "rejected", "not JSON (TradingView sends text/plain when the message isn't valid JSON)", None
    if not isinstance(e, dict):
        return 400, "rejected", "schema: not a JSON object", None
    if not secret or not isinstance(e.get("code"), str) or not hmac.compare_digest(e["code"], secret):
        return 403, "rejected", "wrong or missing receiver code", None
    if any(not isinstance(e.get(k), str) or not e.get(k) for k in FIELDS):
        return 400, "rejected", "schema: every field must be a non-empty string", None
    if e["label"] != "DEMO":
        return 400, "rejected", "label is not DEMO", None
    if e["symbol"] not in ALLOWED:
        return 400, "rejected", f"symbol {e['symbol']} not allowed", None
    try:
        age = (now - parse_utc(e["sent_at"])).total_seconds()
        parse_utc(e["bar_time"])
    except ValueError:
        return 400, "rejected", "time format must be YYYY-MM-DDTHH:MM:SSZ", None
    if age > MAX_AGE or age < -30:
        return 400, "rejected", f"stale: sent {age:.0f} s ago", None
    if not store.add(e, now):
        return 200, "duplicate", "event_id already processed", e
    return 200, "accepted", "", e


def log(line):
    path = ROOT / "logs" / "webhook.log"
    path.parent.mkdir(exist_ok=True)
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(line) + "\n")
    print(json.dumps(line))


def telegram_worker(jobs, store, send=None):
    """Runs after the answer has gone back. One retry after 5 s, then the failure is logged; no loop."""
    while True:
        e = jobs.get()
        text = "\n".join([f"DEMO | SIGNAL RECEIVED (webhook)",
                          f"event {e['event_id']} | rule {e['system_version']}",
                          f"{e['symbol']} {e['timeframe']} | bar {e['bar_time']} | {e['action']}",
                          "signal received: the webhook path places no orders"])
        ok = False
        for attempt in (1, 2):
            if send is not None:
                ok = send(text)
            elif os.environ.get("TELEGRAM_BOT_TOKEN") and os.environ.get("TELEGRAM_CHAT_ID"):
                res = notifier.call("sendMessage", {"chat_id": os.environ["TELEGRAM_CHAT_ID"], "text": text},
                                    os.environ["TELEGRAM_BOT_TOKEN"])
                ok = bool(res.get("ok"))
            else:
                print("telegram not configured; would send:\n" + text)
                ok = True
            if ok or attempt == 2:
                break
            time.sleep(5)
        store.mark(e["event_id"], 1 if ok else -1)
        log(dict(time=datetime.now(timezone.utc).isoformat(timespec="seconds"), result="telegram",
                 event_id=e["event_id"], ok=ok))


class Server(ThreadingHTTPServer):
    allow_reuse_address = os.name != "nt"     # on Windows, reuse lets two programs share a port silently


def make_handler(store, jobs, secret):
    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            t0 = time.perf_counter()
            now = datetime.now(timezone.utc)
            n = int(self.headers.get("Content-Length") or 0)
            if self.path != "/tv" or n > MAX_BODY:
                status, result, reason, e = 404 if self.path != "/tv" else 413, "rejected", "path or size", None
            else:
                status, result, reason, e = check(self.rfile.read(n), store, secret, now)
            self.send_response(status)
            self.send_header("Content-Type", "text/plain")
            self.end_headers()
            self.wfile.write(result.encode())
            log(dict(time=now.isoformat(timespec="seconds"), result=result, reason=reason,
                     event_id=e["event_id"] if e else None, ms=round((time.perf_counter() - t0) * 1000, 1)))
            if result == "accepted":
                jobs.put(e)                     # Telegram happens after the answer

        def log_message(self, *args):           # the default access log is replaced by log()
            pass
    return Handler


def serve(host="127.0.0.1", port=8765, db=ROOT / "data" / "webhook_events.sqlite", send=None):
    secret = os.environ.get("WEBHOOK_CODE", "")
    if len(secret) < 16:
        sys.exit("Set WEBHOOK_CODE (16+ random characters) first; it's checked in every alert message.")
    store, jobs = Store(db), queue.Queue()
    threading.Thread(target=telegram_worker, args=(jobs, store, send), daemon=True).start()
    server = Server((host, port), make_handler(store, jobs, secret))
    print(f"listening on http://{host}:{server.server_port}/tv")
    return server


if __name__ == "__main__":
    serve().serve_forever()

A script that posts made-up alerts to it, as TradingView would: the same alert three times, then an unknown symbol, a stale one, one with no code, one with the wrong code, and a plain-text body. src/send_test_webhook.py:

# src/send_test_webhook.py: post made-up alerts to the local receiver, as TradingView would. Local only.
#   .venv\Scripts\python src\send_test_webhook.py
import json, os, urllib.error, urllib.request
from datetime import datetime, timedelta, timezone

URL = "http://127.0.0.1:8765/tv"
local = urllib.request.build_opener(urllib.request.ProxyHandler({}))   # never through a proxy
now = datetime.now(timezone.utc).replace(microsecond=0)
bar = now.replace(minute=0, second=0) - timedelta(hours=1)
good = dict(system_version="ema-long-v1", symbol="XAUUSD", timeframe="60", bar_time=f"{bar:%Y-%m-%dT%H:%M:%SZ}",
            sent_at=f"{now:%Y-%m-%dT%H:%M:%SZ}", action="long-signal", label="DEMO", code=os.environ["WEBHOOK_CODE"])
good["event_id"] = f"{good['system_version']}-{good['symbol']}-{good['timeframe']}-{good['bar_time']}-long"

cases = [("first", good), ("second", good), ("third", good),
         ("unknown symbol", dict(good, symbol="GBPJPY", event_id="x1")),
         ("stale", dict(good, sent_at=f"{now - timedelta(minutes=10):%Y-%m-%dT%H:%M:%SZ}", event_id="x2")),
         ("no code", {k: v for k, v in good.items() if k != "code"}),
         ("wrong code", dict(good, code="not-the-code", event_id="x3"))]
for name, payload in cases:
    body, ctype = json.dumps(payload).encode(), "application/json"
    req = urllib.request.Request(URL, data=body, headers={"Content-Type": ctype})
    try:
        with local.open(req, timeout=5) as r:
            print(f"{name:>14}: {r.status} {r.read().decode()}")
    except urllib.error.HTTPError as err:
        print(f"{name:>14}: {err.code} {err.read().decode()}")
req = urllib.request.Request(URL, data=b"XAUUSD crossed up", headers={"Content-Type": "text/plain"})
try:
    local.open(req, timeout=5)
except urllib.error.HTTPError as err:
    print(f"{'plain text':>14}: {err.code} {err.read().decode()}")

Create the receiver code once and store it as the user environment variable WEBHOOK_CODE, through the same dialog as the Telegram token. In Windows PowerShell, from C:\trade-system-lab:

.venv\Scripts\python -c "import secrets; print(secrets.token_urlsafe(24))"

Open a new window and start the receiver; leave it running:

cd C:\trade-system-lab
.venv\Scripts\python src\receiver.py

In a second window:

cd C:\trade-system-lab
.venv\Scripts\python src\send_test_webhook.py

The second window prints:

         first: 200 accepted
        second: 200 duplicate
         third: 200 duplicate
unknown symbol: 400 rejected
         stale: 400 rejected
       no code: 403 rejected
    wrong code: 403 rejected
    plain text: 400 rejected

The receiver’s window, one JSON line per request (also in logs/webhook.log). Without Telegram variables it prints what it would send:

listening on http://127.0.0.1:8765/tv
{"time": "2026-12-04T02:22:43+00:00", "result": "accepted", "reason": "", "event_id": "ema-long-v1-XAUUSD-60-2026-12-04T01:00:00Z-long", "ms": 27.9}
telegram not configured; would send:
DEMO | SIGNAL RECEIVED (webhook)
event ema-long-v1-XAUUSD-60-2026-12-04T01:00:00Z-long | rule ema-long-v1
XAUUSD 60 | bar 2026-12-04T01:00:00Z | long-signal
signal received: the webhook path places no orders
{"time": "2026-12-04T02:22:43+00:00", "result": "telegram", "event_id": "ema-long-v1-XAUUSD-60-2026-12-04T01:00:00Z-long", "ok": true}
{"time": "2026-12-04T02:22:43+00:00", "result": "duplicate", "reason": "event_id already processed", "event_id": "ema-long-v1-XAUUSD-60-2026-12-04T01:00:00Z-long", "ms": 2.0}
{"time": "2026-12-04T02:22:43+00:00", "result": "duplicate", "reason": "event_id already processed", "event_id": "ema-long-v1-XAUUSD-60-2026-12-04T01:00:00Z-long", "ms": 1.9}
{"time": "2026-12-04T02:22:43+00:00", "result": "rejected", "reason": "symbol GBPJPY not allowed", "event_id": null, "ms": 1.3}
{"time": "2026-12-04T02:22:43+00:00", "result": "rejected", "reason": "stale: sent 601 s ago", "event_id": null, "ms": 1.6}
{"time": "2026-12-04T02:22:43+00:00", "result": "rejected", "reason": "wrong or missing receiver code", "event_id": null, "ms": 1.6}
{"time": "2026-12-04T02:22:43+00:00", "result": "rejected", "reason": "wrong or missing receiver code", "event_id": null, "ms": 1.3}
{"time": "2026-12-04T02:22:43+00:00", "result": "rejected", "reason": "not JSON (TradingView sends text/plain when the message isn't valid JSON)", "event_id": null, "ms": 1.4}

One record, one notification, two duplicates, and every rejection with its reason. Each answer took under 30 ms. Now stop the receiver (Ctrl+C), start it again, and send the same alerts:

         first: 200 duplicate
        second: 200 duplicate
         third: 200 duplicate
unknown symbol: 400 rejected
         stale: 400 rejected
       no code: 403 rejected
    wrong code: 403 rejected
    plain text: 400 rejected

The first alert is a duplicate now: the ID survived the restart in data/webhook_events.sqlite, so nothing is announced twice.

The tests, tests/test_receiver.py. The last one makes Telegram take 4 seconds and checks the answer still comes back in under 1:

# tests/test_receiver.py: duplicates, restarts, rejections, and a slow Telegram that mustn't delay the answer.
import json, threading, time, urllib.request
from datetime import datetime, timedelta, timezone

from src.receiver import Store, check, serve

CODE = "test-code-0123456789"
NOW = datetime(2026, 12, 3, 15, 0, 5, tzinfo=timezone.utc)
EVENT = dict(system_version="ema-long-v1", event_id="ema-long-v1-XAUUSD-60-2026-12-03T14:00:00Z-long",
             symbol="XAUUSD", timeframe="60", bar_time="2026-12-03T14:00:00Z", sent_at="2026-12-03T15:00:01Z",
             action="long-signal", label="DEMO", code=CODE)


def body(**change):
    return json.dumps(dict(EVENT, **change)).encode()


def test_same_event_three_times_gives_one_record(tmp_path):
    store = Store(tmp_path / "e.sqlite")
    results = [check(body(), store, CODE, NOW)[1] for _ in range(3)]
    assert results == ["accepted", "duplicate", "duplicate"]
    assert store.db.execute("SELECT COUNT(*) FROM events").fetchone()[0] == 1


def test_restart_still_knows_the_event(tmp_path):
    check(body(), Store(tmp_path / "e.sqlite"), CODE, NOW)
    assert check(body(), Store(tmp_path / "e.sqlite"), CODE, NOW)[1] == "duplicate"


def test_bad_requests_are_rejected_with_a_reason(tmp_path):
    store = Store(tmp_path / "e.sqlite")
    stale = (NOW - timedelta(minutes=10)).strftime("%Y-%m-%dT%H:%M:%SZ")
    cases = {b"XAUUSD crossed up": "not JSON", body(symbol="GBPJPY"): "not allowed",
             body(sent_at=stale): "stale", body(code="nope"): "receiver code",
             json.dumps({k: v for k, v in EVENT.items() if k != "code"}).encode(): "receiver code",
             body(timeframe=""): "schema"}
    for b, reason in cases.items():
        status, result, why, _ = check(b, store, CODE, NOW)
        assert result == "rejected" and reason in why and status >= 400
    assert store.db.execute("SELECT COUNT(*) FROM events").fetchone()[0] == 0


def test_slow_telegram_does_not_delay_the_answer(tmp_path, monkeypatch):
    monkeypatch.setenv("WEBHOOK_CODE", CODE)
    sent = []
    def slow_send(text):
        time.sleep(4)
        sent.append(text)
        return True
    server = serve(port=0, db=tmp_path / "e.sqlite", send=slow_send)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    req = urllib.request.Request(f"http://127.0.0.1:{server.server_port}/tv", data=body(sent_at=now),
                                 headers={"Content-Type": "application/json"})
    t0 = time.perf_counter()
    local = urllib.request.build_opener(urllib.request.ProxyHandler({}))
    with local.open(req, timeout=3) as r:
        assert r.read() == b"accepted"
    assert time.perf_counter() - t0 < 1 and sent == []
    server.shutdown()

Run .venv\Scripts\python -m pytest -q tests; you should see 4 passed.

If receiver.py stops with an error that the address is in use, another program already has port 8765; change the port in both scripts. On Windows, Python’s server would otherwise share the port silently and the other program would answer your requests, which is why Server turns address reuse off there.

In TradingView, once there’s a public URL

On the chart: Alerts → Create Alert → pick the condition → turn on Webhook URL → enter your HTTPS endpoint ending in /tv → paste the message → Create. The message, with TradingView’s placeholders ({{ticker}} the symbol, {{interval}} the timeframe, for example 60 for H1, {{time}} the bar’s time in UTC, {{timenow}} when the alert fired):

{"system_version": "ema-long-v1",
 "event_id": "ema-long-v1-{{ticker}}-{{interval}}-{{time}}-long",
 "symbol": "{{ticker}}", "timeframe": "{{interval}}",
 "bar_time": "{{time}}", "sent_at": "{{timenow}}",
 "action": "long-signal", "label": "DEMO", "code": "[YOUR WEBHOOK_CODE]"}

Check that {{ticker}} gives exactly the name in ALLOWED on your data feed. Then compare the receiver’s log with the Webhook status column in the Alert log. HTTP 200 only means the receiver got the event and recorded it under your rules.

Try it: a notify-only HTTPS receiver

Draw and explain a small HTTPS webhook receiver for a beginner. The receiver only notifies: it accepts only the JSON schema [PASTE SCHEMA], checks a symbol allowlist, an expiry on the timestamp and event_id deduplication, writes a log with sensitive details masked, then sends a Telegram message that it arrived. TradingView's constraints (checked 2026-11-11): the request is an HTTP POST; the URL uses port 80 or 443 only; no IPv6; if the receiver takes more than 3 seconds the request is cancelled; if the message is valid JSON the content-type is application/json, otherwise text/plain. So the receiver must check, log and answer at once, and send to Telegram after answering. Don't call a broker API, don't forward anything to an EA or a demo account, don't accept commands from the chat, don't put secrets in the payload. Add tests for bad JSON, a text/plain body, a duplicate event, a stale timestamp, an unknown symbol, processing slower than 3 seconds, a Telegram failure and a Telegram retry. Give the steps to run it locally with fake payloads, and explain why localhost doesn't receive a public webhook without an HTTPS endpoint.

Fill the [brackets] with your own details. Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.

The order to work in:

  1. Check the conditions first: TradingView Essential or higher (Basic has no webhooks), 2FA on; the receiver has a public IPv4 URL on port 443 (HTTPS) or 80; a private localhost can’t receive webhooks from the internet.
  2. Build a test HTTPS receiver that accepts only one defined JSON schema; check, log and answer within 3 seconds, then send to Telegram.
  3. On the TradingView chart: Alerts → Create Alert → pick the condition → turn on Webhook URL → enter the endpoint → paste the JSON message → Create.
  4. Reject missing or wrong payloads, stale timestamps and unknown symbols; use event_id to spot duplicate webhooks; to verify the sender, check the client SSL certificate TradingView sends over HTTPS.
  5. Send a Telegram message on success or failure, and check the Webhook status column in the Alert log; never put a secret in the body.

Key takeaways

  • TradingView’s conditions (checked 2026-11-11): a paid plan from Essential, 2FA on, a URL on port 80 or 443, no IPv6.
  • Build event_id from the rule version, symbol, timeframe, bar time and direction; the same alert sent three times gives one notification and two logged duplicates.
  • Keep tokens and passwords out of the JSON; verify the sender through TradingView’s client SSL certificate or the IP addresses it publishes.

Comments