DEV Community

HoldAlarms
HoldAlarms

Posted on Edited on

Connecting an AI trading agent to TradingView alerts without losing signals

Disclosure: I work on HoldAlarms (formerly HookWatch), a hosted TradingView webhook reliability layer. Everything below works without it, and the code is MIT on GitHub.

A lot of people are wiring LLM agents to TradingView right now: an alert fires, the agent reads the alert plus context, decides what to do next, and only then talks to a downstream system. The first version usually looks like this:

@app.post("/webhook")
async def webhook(req: Request):
    payload = await req.json()
    decision = await agent.decide(payload)   # 3-15 seconds
    if decision.execute:
        # slow downstream work (broker / sheet / Discord) — do this AFTER 200
        handle_downstream(...)
    return {"ok": True}
Enter fullscreen mode Exit fullscreen mode

It works in testing, then alerts start failing delivery in production. Here's why, and the boring pattern that fixes it.

TradingView gives you about 3 seconds

From TradingView's own docs: "If a remote server takes longer than three seconds to process a request, the request will be cancelled" (How to configure webhook alerts). Also: ports 80/443 only, no IPv6, no custom headers, and the body is text/plain unless your alert message is valid JSON.

TradingView resubmits only when the receiver answers 500–599 except 504, waiting 5 seconds, up to 3 resends (Webhook resubmission). An LLM call alone usually takes longer than three seconds, so the handler above can be cancelled mid-flight. Check the alert log's Webhook status, and keep your own request log — a cancelled or non-5xx failure is not covered by that resubmission rule.

Split the handler from the agent

The webhook handler should do four cheap things and return:

  1. Verify a secret carried in the JSON body (TradingView can't send auth headers).
  2. De-duplicate on an alert_id you build in the alert message, e.g. {{ticker}}-{{interval}}-{{timenow}}.
  3. Timestamp and enqueue the alert.
  4. Return 200 within milliseconds.

The agent runs in a separate consumer:

@app.post("/webhook")
async def webhook(request: Request):
    alert = json.loads(await request.body())
    if not hmac.compare_digest(str(alert.pop("secret", "")), SECRET):
        return Response("forbidden", status_code=403)
    alert_id = alert.get("alert_id")
    if not alert_id or alert_id in seen:
        return Response("ok", status_code=200)   # duplicates get 200 too
    seen[alert_id] = time.time()
    alert["_received_at"] = time.time()
    try:
        alerts.put_nowait(alert)
    except asyncio.QueueFull:
        return Response("busy", status_code=503)
    return Response("queued", status_code=200)


async def consumer():
    while True:
        alert = await alerts.get()
        decision = await agent_decide(alert)       # slow is fine here
        if risk_gate(alert, decision):
            handle_downstream(alert, decision)
Enter fullscreen mode Exit fullscreen mode

Full runnable versions (FastAPI, Express, and the agent one): github.com/hookwatch-ops/tradingview-webhook-examples

Put a deterministic risk gate after the agent

The agent proposes; plain code decides whether anything reaches the broker. At minimum:

  • Max alert age. If the queue backed up and an alert is a couple of minutes old, acting on it is probably wrong. Drop it.
  • Position and size limits the model can't talk its way around.
  • Structured output only. Parse the agent's answer into a fixed schema; anything else is a skip.

The part a fast handler doesn't fix: downtime

Fast ACK solves the 3-second problem. It doesn't help if your process is restarting, your VPS reboots, or you're deploying a new agent prompt at the moment the alert fires. TradingView doesn't queue alerts for you. HoldAlarms cannot recover an alert TradingView never sent.

The fix is to make ingress separate from the bot:

  • a tiny always-on receiver (or serverless function) that only writes to a durable queue: Redis Streams, SQS, Postgres
  • durable dedupe: Redis SET alert_id 1 NX EX 86400 or a unique index
  • retries with backoff from the queue to the agent, and a dead-letter queue for alerts that keep failing, so you can inspect them
  • an alert to yourself when no alerts arrive during hours you expect them

Then your agent can crash, restart and redeploy without depending on an in-memory process staying up.

If you don't want to run that part

That ingress layer is what HoldAlarms (formerly HookWatch) does as a service: you point the TradingView alert at your HoldAlarms URL, it answers TradingView right away, queues the alert, delivers it to your receiver, and retries failed deliveries. Retries finish within about 3 minutes, or up to about 6 if your server asks for longer waits with Retry-After. Alerts that still fail go to a dead-letter queue. It isn't an alerts feed and isn't a broker, and it doesn't make alerts faster; it only covers delivery after TradingView has sent the webhook. It cannot recover an alert the platform never sent. There's a free trial (300 alerts or 7 days, no card) if you want to try it in front of your agent.

Either way, keep the secret check and the idempotency in your own receiver.

Checklist

  • [ ] Handler returns 200 in well under 3 s, never calls the LLM
  • [ ] Secret in the JSON body, constant-time compare
  • [ ] alert_id in every alert message, de-duplicated durably
  • [ ] Agent runs from a queue, with a max-alert-age check
  • [ ] Deterministic risk gate between agent and broker
  • [ ] Ingress survives bot restarts (your own queue or a hosted layer)
  • [ ] You look at failures (DLQ / logs), not just successes

Not financial advice. Paper-trade any agent before giving it real money.

Top comments (1)

Collapse
 
stratcorealpha profile image
Arnold Holm •

One loss case is still in the sample: the seen marker is set before put_nowait. If the queue is full, the first attempt returns503, but a retry gets200 and is never queued. I would commit the dedupe marker and durable enqueue together. Test queue-full, then retry the same ID: one stored signal, not zero.