<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mansura Akter Susama</title>
    <description>The latest articles on DEV Community by Mansura Akter Susama (@writersusama).</description>
    <link>https://dev.to/writersusama</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4251054%2Fcff22285-4d00-4eb6-afb6-87e09b057c53.png</url>
      <title>DEV Community: Mansura Akter Susama</title>
      <link>https://dev.to/writersusama</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/writersusama"/>
    <language>en</language>
    <item>
      <title>Your TradingView Webhook Has 3 Seconds: Parsing Messy Alerts Without Losing Trades</title>
      <dc:creator>Mansura Akter Susama</dc:creator>
      <pubDate>Thu, 19 Nov 2026 08:45:22 +0000</pubDate>
      <link>https://dev.to/writersusama/your-tradingview-webhook-has-3-seconds-parsing-messy-alerts-without-losing-trades-2mno</link>
      <guid>https://dev.to/writersusama/your-tradingview-webhook-has-3-seconds-parsing-messy-alerts-without-losing-trades-2mno</guid>
      <description>&lt;p&gt;You wire a TradingView alert to your server. It works in testing. Then, on a busy market open, an alert never turns into an order.&lt;/p&gt;

&lt;p&gt;No error in your logs. No crash. The trade just never happened.&lt;/p&gt;

&lt;p&gt;In most cases, the cause is not your strategy. It is your receiver. TradingView gives your endpoint a very short window, and anything slow inside that window, like a broker call or an LLM request, can quietly cost you the alert.&lt;/p&gt;

&lt;p&gt;This guide walks through a receiver design that stays fast, handles duplicates, and can still read messy, human-written alert messages. The examples use Python and FastAPI, but the pattern works in any stack.&lt;/p&gt;

&lt;h2&gt;
  
  
  The TradingView webhook rules you must design around
&lt;/h2&gt;

&lt;p&gt;TradingView's help center lists a few hard limits. Every design choice below comes from these:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;3-second timeout: if your server takes longer than three seconds to process a request, &lt;a href="https://www.tradingview.com/support/solutions/43000529348-how-to-configure-webhook-alerts/" rel="noopener noreferrer"&gt;TradingView &lt;/a&gt;cancels it.&lt;/li&gt;
&lt;li&gt;Ports 80 and 443 only: requests to any other port are rejected, and IPv6 is not supported for webhooks yet.&lt;/li&gt;
&lt;li&gt;Content type follows the message: a message that is valid JSON is sent as application/json. Anything else goes out as text/plain.&lt;/li&gt;
&lt;li&gt;2FA is required: webhook alerts only work when two-factor authentication is on for the account.&lt;/li&gt;
&lt;li&gt;Retries on server errors: if your server answers with a 5xx status, TradingView sends the same alert again after 5 seconds, up to 3 more times. That means one trigger can arrive 4 times.&lt;/li&gt;
&lt;li&gt;Known source IPs: TradingView publishes four outbound IPv4 addresses you can allowlist: 52.89.214.238, 34.212.75.30, 54.218.53.128 and 52.32.178.7.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two of these rules work against each other. The timeout pushes you to respond fast. The retry rule means a slow or failing response can create duplicate orders. So the receiver needs to do very little, and do it safely.&lt;/p&gt;

&lt;p&gt;The pattern: acknowledge first, think later&lt;/p&gt;

&lt;p&gt;The fix is simple to say: your webhook handler should only check, record and queue. Everything slow happens after you have already returned 200 OK.&lt;/p&gt;

&lt;p&gt;python&lt;/p&gt;

&lt;h2&gt;
  
  
  receiver.py
&lt;/h2&gt;

&lt;p&gt;import hashlib&lt;br&gt;
import os&lt;/p&gt;

&lt;p&gt;from fastapi import BackgroundTasks, FastAPI, HTTPException, Request&lt;/p&gt;

&lt;p&gt;from worker import process_alert&lt;/p&gt;

&lt;p&gt;app = FastAPI()&lt;br&gt;
SECRET = os.environ["TV_SECRET"]&lt;br&gt;
seen: set[str] = set()  # use Redis or a database table in production&lt;/p&gt;

&lt;p&gt;@app.post("/tv-webhook")&lt;br&gt;
async def tv_webhook(request: Request, background: BackgroundTasks):&lt;br&gt;
    raw = (await request.body()).decode("utf-8", errors="replace")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# 1. Cheap auth: TradingView cannot send custom headers,
#    so the shared secret lives inside the alert message.
if SECRET not in raw:
    raise HTTPException(status_code=401)  # 4xx = no retry storm

# 2. Idempotency: the same payload never runs twice.
key = hashlib.sha256(raw.encode()).hexdigest()
if key in seen:
    return {"status": "duplicate"}
seen.add(key)

# 3. Queue the slow work and answer immediately.
background.add_task(process_alert, raw)
return {"status": "queued"}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;A few notes on this handler:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Put {{timenow}} in every alert message. Two genuine signals on different bars then produce different hashes, while TradingView retries of the same trigger still match.&lt;/li&gt;
&lt;li&gt;Return 4xx for bad input, not 5xx. A 5xx invites retries. A rejected secret should fail once, quietly.&lt;/li&gt;
&lt;li&gt;BackgroundTasks is fine for a demo. In production, push to a real queue (Redis, SQS, a database job table) so a restart does not drop work.&lt;/li&gt;
&lt;li&gt;Keep the secret out of logs. TradingView itself warns against putting credentials in the webhook body, so use a random token, never a broker password.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The parsing ladder: JSON, then regex, then an LLM
&lt;/h2&gt;

&lt;p&gt;The receiver is now fast. The next problem is the message itself.&lt;/p&gt;

&lt;p&gt;In a perfect world, every alert is clean JSON. In reality, traders paste in indicator text, copy messages from Telegram, or use alerts from community scripts they cannot edit. You end up with inputs like these:&lt;/p&gt;



&lt;p&gt;text&lt;br&gt;
{"side": "buy", "symbol": "EURUSD", "sl": 1.0790, "tp": 1.0880, "t": "{{timenow}}"}&lt;br&gt;
BUY XAUUSD now, SL 2398 TP 2420&lt;br&gt;
Long signal fired on GBPUSD (RSI cross), consider entry, stop below 1.2650&lt;/p&gt;



&lt;p&gt;Instead of forcing one format, use a ladder. Try the cheapest, most reliable method first, and only fall through when it fails.&lt;/p&gt;

&lt;p&gt;python&lt;/p&gt;

&lt;h2&gt;
  
  
  worker.py
&lt;/h2&gt;

&lt;p&gt;import json&lt;br&gt;
import re&lt;br&gt;
from typing import Literal, Optional&lt;/p&gt;

&lt;p&gt;from pydantic import BaseModel, ValidationError&lt;/p&gt;

&lt;p&gt;class Order(BaseModel):&lt;br&gt;
    side: Literal["buy", "sell", "close"]&lt;br&gt;
    symbol: str&lt;br&gt;
    sl: Optional[float] = None&lt;br&gt;
    tp: Optional[float] = None&lt;/p&gt;

&lt;p&gt;PATTERN = re.compile(r"\b(?Pbuy|sell|close)\b\s+(?P[A-Z]{3,10})\b", re.I)&lt;br&gt;
FIELDS = ("side", "symbol", "sl", "tp")&lt;/p&gt;

&lt;p&gt;def parse_alert(raw: str) -&amp;gt; Optional[Order]:&lt;br&gt;
    # Rung 1: structured JSON&lt;br&gt;
    try:&lt;br&gt;
        data = json.loads(raw)&lt;br&gt;
        return Order(**{k: data[k] for k in FIELDS if data.get(k) is not None})&lt;br&gt;
    except (json.JSONDecodeError, ValidationError, AttributeError, TypeError):&lt;br&gt;
        pass&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Rung 2: a strict regex for the common "BUY SYMBOL" shape
match = PATTERN.search(raw)
if match:
    return Order(side=match["side"].lower(), symbol=match["symbol"].upper())

# Rung 3: LLM fallback for free text
return llm_parse(raw)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Rung 1 handles alerts you control. Rung 2 catches the classic one-line signal format. Rung 3 only runs for the leftovers, which keeps your LLM bill and your error surface small.&lt;/p&gt;

&lt;p&gt;Note that rung 2 ignores stop loss and take profit on purpose. If you need those from free text, it is safer to let rung 3 extract them and validate the result than to grow a fragile regex.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using an LLM without letting it invent trades
&lt;/h2&gt;

&lt;p&gt;LLMs are good at reading messy text. They are also good at sounding confident about things that are not there. For order data, that is the dangerous part.&lt;/p&gt;

&lt;p&gt;Four guardrails make the LLM rung safe enough to use:&lt;/p&gt;

&lt;p&gt;python&lt;br&gt;
LLM_PROMPT = """Extract one trade instruction from the alert below.&lt;br&gt;
Reply with JSON only, in this exact shape:&lt;br&gt;
{"side": "buy" | "sell" | "close", "symbol": string, "sl": number | null, "tp": number | null}&lt;br&gt;
If the alert is not a clear trade instruction, reply with {"side": null}.&lt;br&gt;
Never guess a price that is not written in the alert.&lt;/p&gt;

&lt;p&gt;Alert:&lt;br&gt;
"""&lt;/p&gt;

&lt;p&gt;def llm_parse(raw: str) -&amp;gt; Optional[Order]:&lt;br&gt;
    reply = call_llm(LLM_PROMPT + raw)  # any provider, temperature 0&lt;br&gt;
    try:&lt;br&gt;
        order = Order(**json.loads(reply))&lt;br&gt;
    except (json.JSONDecodeError, ValidationError, TypeError):&lt;br&gt;
        return None&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Grounding check: the symbol must literally appear in the alert.
if order.symbol.upper() not in raw.upper():
    return None
return order
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A schema, not a vibe. Pydantic rejects anything that does not match the Order model, including a missing side or a made-up action like "hedge".&lt;br&gt;
An explicit "no trade" answer. Giving the model a valid way to say "this is not a signal" cuts down on forced, invented orders.&lt;br&gt;
A grounding check. If the symbol is not in the original text, the output is discarded. You can extend the same idea to prices.&lt;br&gt;
It runs after the 200 OK. Because parsing happens in the worker, a slow model response never touches TradingView's 3-second window.&lt;/p&gt;

&lt;p&gt;That third rung turns the example message "Long signal fired on GBPUSD (RSI cross), consider entry, stop below 1.2650" into a buy on GBPUSD with a stop at 1.2650. And if the model ever returns something odd, the order simply does not happen.&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Before you point this at a live account&lt;br&gt;
*&lt;/em&gt;&lt;br&gt;
Webhook automation removes the delay between a signal and an order. It does not remove market risk. A bug, a bad alert or a fast market can still lose money quickly, so test on a demo account first.&lt;/p&gt;

&lt;p&gt;A short checklist before going live:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Allowlist symbols and cap position size in the worker, not in the alert message.&lt;/li&gt;
&lt;li&gt;Log every raw payload with its parse result, so you can replay and debug any trade.&lt;/li&gt;
&lt;li&gt;Watch the Webhook status column in TradingView's alert log for failed deliveries.&lt;/li&gt;
&lt;li&gt;Add a kill switch, such as an environment flag that makes the worker log orders without sending them.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Build it or use a hosted option
&lt;/h2&gt;

&lt;p&gt;If you enjoy running infrastructure, the pattern above is a solid base. You still own uptime, queues, retries, broker connections and monitoring.&lt;/p&gt;

&lt;p&gt;If you would rather skip the server work, hosted bridges now handle this end to end. For example, a cloud &lt;a href="https://trade2sync.com/products/tradingview-webhook" rel="noopener noreferrer"&gt;TradingView webhook&lt;/a&gt; can accept alerts in plain text or JSON and route them to MetaTrader and other platforms without a VPS. Whichever route you pick, the same principles apply: respond fast, dedupe everything, and never let a parser guess.&lt;br&gt;
_&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Disclosure: I work with trade2sync on content. The code in this post is independent and works with any broker or bridge.&lt;br&gt;
_&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>ai</category>
      <category>webhook</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
