Fix TradingView Webhook Duplicates & Out-of-Order
You set up a perfect crossover strategy. Pine Script (TradingView's charting language) shows the signal triggered, the webhook (an HTTP callback from TradingView to your server) fires off — and then your broker receives two identical opening orders. Or worse: you set an entry first, then a stop-loss later, but the stop-loss executes first, flipping your position direction in an instant.
This isn't a bug in your code, and it isn't the broker failing. These are the two most common — and most dangerous — pitfalls of TradingView webhooks: duplicate alerts and out-of-order delivery. They look identical — one alert becomes two orders — but the root causes are completely different, and so are the fixes. Mix them up, and you won't be able to fix it.
First, diagnose: which problem are you facing?
Before touching anything, check TradingView's Alerts log first. This single step can save you half an hour of useless debugging.
| Alerts Log Count | Diagnosis | Next Step |
|---|---|---|
| Only one entry | The alert itself only triggered once | Type 3: delivery retry caused duplicates |
| Two or more entries | The alert triggered multiple times | Type 1: the alert itself fired multiple times |
| Only one entry, but the broker received multiple orders | The alert triggered normally but the order duplicated | Type 2: out-of-order delivery |
These three causes can appear simultaneously. One article solves all three.
Type 1: the alert itself triggered multiple times
The most obvious duplication — you see two or more log entries for the same condition in the Alerts log, each sending out a webhook. Your receiver is not wrong; it faithfully executed every instruction it received. The problem lies with TradingView.
There are three common causes:
| Cause | Symptom | Fix |
|---|---|---|
| You set two alerts for the same condition | Two alert log entries have the same timestamp or differ by no more than one second | Open Alerts → Manage, delete the duplicate. Also check across charts — setting the same strategy on both 1H and 4H will trigger simultaneously. |
| Frequency set to Once Per Bar | Two alerts appear within the same candlestick bar, especially common during high price volatility | Change it to Once Per Bar Close |
| The Pine Script alert() is not wrapped in if barstate.isconfirmed | The strategy's alert fires repeatedly on the same unconfirmed candlestick bar | Wrap alert() in if barstate.isconfirmed |
Verified as of 2026-10-20. Source: TradingView Help Center, \"Differences between alert frequencies\".
Once Per Bar vs Once Per Bar Close: similar names, very different behavior
This is one of the most confusing settings on TradingView. The Frequency dropdown in the UI has four options:
| UI Option | Trigger Timing | Can Duplicate? |
|---|---|---|
| Once only | When the condition is first met (only once for the entire chart lifecycle) | No |
| Once per bar | Within each candlestick bar, triggers whenever the condition is met; price fluctuations before the bar closes may cause the condition to flip true/false repeatedly | Yes — possibly multiple times within the same bar |
| Once per bar close | Triggers only after the bar closes and the condition is confirmed | No — at most once per bar |
| Once per minute or every time | Checks the condition every minute and triggers whenever it's met | Yes — will keep triggering as long as the condition persists over several minutes |
Verified as of 2026-10-20. Source: TradingView Help Center, \"Differences between alert frequencies\".
For automated order placement, Once Per Bar Close is the safe default. Once Per Bar allows duplicate triggers within the same bar — if the price first drops below your entry price, bounces back, then drops again, you will receive two webhooks.
But be aware: the Pine Script alert() function has its own frequency constants (alert.freq_once_per_bar_close, etc.), which are different from the literal names in the UI dropdown. If you use alert() instead of alertcondition(), frequency control is written in the code, not controlled by UI settings.
Pine Script: eliminate mid-bar duplicates with barstate.isconfirmed
If your strategy uses the alert() function (instead of alertcondition()), changing the UI Frequency alone is not enough. You also need an extra layer of protection inside Pine Script:
//@version=6
strategy("My Strategy", overlay=true)
emaFast = ta.ema(close, 12)
emaSlow = ta.ema(close, 26)
crossUp = ta.crossover(emaFast, emaSlow)
// ❌ Wrong: without isconfirmed, mid-bar price fluctuations cause repeated alerts
alert(strategy.position_size == 0 and crossUp ?
"LICENSE,buy,MNQU26,size_lots=1" : na, alert.freq_once_per_bar_close)
// ✅ Correct: only emit signal after bar closes
if barstate.isconfirmed and crossUp and strategy.position_size == 0
alert("LICENSE,buy,MNQU26,size_lots=1", alert.freq_once_per_bar_close)barstate.isconfirmed means the current candlestick bar has closed and price is no longer moving. Adding this line ensures that even if mid-bar prices repeatedly cross the moving average, the alert only fires once after the bar closes.
Type 2: delivery retry caused duplicates
The Alerts log shows only one entry, but your broker received more than two orders. This means the alert triggered only once, but the webhook was delivered multiple times. TradingView's retry mechanism is to blame.
TradingView's official documentation states this clearly (\"Webhook resubmission\"):
If your receiver returns an HTTP status code between 500 and 599 (excluding 504), TradingView will resend after 5 seconds. It retries up to three times, so one alert can become four webhooks.
The dangerous scenario: your receiver processes the order but the response times out. TradingView sees the timeout and resends, but your broker already received the first order — resulting in the same signal becoming two orders.
TradingView's webhook has a three-second timeout. If the remote server does not return a 2xx status code within three seconds, the connection is terminated. These three seconds are your entire budget:
| Step | Suggested Time | Notes |
|---|---|---|
| Validate secret / HMAC | < 10 ms | Use hmac.compare_digest for constant-time comparison |
| Parse JSON | < 5 ms | Only extract the fields you need, don't deep-copy the entire object |
| Write processed record (idempotency key) | < 100 ms | Write the fence first, then place the order — this sequence is critical |
| Return 200 OK | < 2.5 s | Leave buffer for network latency |
| (Asynchronous) actual order placement | Unlimited | Execute after the 200 response |
Verified as of 2026-10-20.
The key point: you cannot respond to TradingView by waiting for broker confirmation. The broker's API may take anywhere from 500 ms to several seconds, which already exceeds TradingView's three-second limit.
The correct approach is ACK fast, deliver later — quickly respond with 200 OK, write the order to a queue, then process the actual order placement in the background. This way, even if the broker takes two seconds to confirm, it won't trigger TradingView's retry.
Type 3: make duplicates harmless with idempotency key
No matter which duplication cause you face, the ultimate solution is the same: idempotency. In computer science, an idempotent operation means \"doing it once or multiple times produces the same result.\" For webhooks, this means receiving three identical signals and executing the order placement only once.
The id field in TradingView payloads
Every TradingView webhook payload includes an id field. This is your idempotency key:
{
"id": "abc123def456",
"alertId": "789012",
"alertName": "EMA Crossover Long",
"time": "2026-10-20T08:00:00.000Z",
"timeUtc": "2026-10-20T08:00:00.000Z",
"exchange": "BINANCE",
"symbol": "BTCUSDT",
"interval": "5",
"chartTime": "2026-10-20T08:00:00.000Z",
"chartTimeUtc": "2026-10-20T08:00:00.000Z",
"isSynchronization": false,
"payload": { "action": "BUY" }
}Processing flow:
| Step | Description |
|---|---|
| Receive payload → extract the id field | This field is a unique identifier automatically generated by TradingView |
| Query database: has this id been processed? | Use id as a unique index query |
| If exists → return 200 OK, skip processing | Let TradingView clear the retry queue, but do not actually execute |
| If not exists → write to database, return 200 OK, asynchronously place order | Write the fence first, then place the order |
Critical detail: the check and write must be an atomic operation. When two identical webhooks arrive simultaneously, there will be a race condition between the \"check\" and \"write\" steps — both see that the id does not exist, and both assume they are first.
The solution is to let the database's unique constraint handle the conflict: if the id already exists during insert, it fails. Catching the error means it was a duplicate; just return 200 OK.
If you cannot change TradingView's alert message
Intermediary services like PineConnector and PineHook have their own deduplication mechanisms. PineHook automatically compresses identical payloads within 12 seconds, but this window is very short — if your strategy needs to do scale-in (batch entries) within a single bar, its own dedup will block you.
PineHook provides the id= parameter as a solution. It is a dedicated deduplication nonce: it is factored into dedup checks but does not get sent to the broker or appear in the Signal Log. Generate different id values using timenow or math.random(), and each trigger of the same strategy becomes independent:
// Pine Script: give each alert a unique id
nonce = str.tostring(timenow) + "-" + str.tostring(math.random(0, 999999))
alert("LICENSE,buy,MNQU26,size_lots=4,id=" + nonce, alert.freq_once_per_bar_close)If you are using TradingView's alert dialog message box (not Pine Script), there is no math.random(). You can combine two changing placeholders: id={{timenow}}-{{close}}. timenow is precise to the second and close is the price; combining both avoids collisions within the same second.
Type 4: out-of-order delivery
You set two alerts simultaneously: one for entry, one for stop-loss. The entry triggers first, then the stop-loss triggers — but the stop-loss webhook arrives at your server before the entry. Your bot executes the stop-loss first (which fails when you have no position), and only then receives the entry signal. It looks like \"the stop-loss ran first\".
Out-of-order causes are more complex than duplicates:
| Cause | Explanation | Scope of Impact |
|---|---|---|
| TradingView server busy | During market open or on the hour, TradingView's alert processing queues up; different alerts may dequeue at different times | Order between different alerts on the same chart |
| Network routing differences | Multiple webhooks take different network paths with varying latency | Webhook receivers across exchanges and regions |
| Inconsistent receiver processing speed | One payload parses faster than another (e.g., different payload sizes or different code branches) | When a single receiver processes multiple payloads concurrently |
| Retry interleaving | A's retry arrives after B, but A's first attempt actually arrived earlier | Retries of the same alert mixed with new alerts |
Verified as of 2026-10-20.
Solve out-of-order with timestamp buffer
An idempotency key solves duplicates, but cannot solve out-of-order. To guarantee ordering, you need a timestamp buffer:
const buffer = []
const BUFFER_MS = 3000 // 3 second buffer
app.post('/webhook', (req, res) => {
// 1. Respond with 200 OK immediately (do not block TradingView)
res.status(200).send('OK')
// 2. Push into buffer with the trigger time from TradingView
buffer.push({
id: req.body.id,
chartTimeUtc: req.body.chartTimeUtc,
payload: req.body.payload
})
})
// 3. Periodically process the buffer
setInterval(async () => {
if (buffer.length === 0) return
// 4. Sort by TradingView's trigger time (not receive time)
buffer.sort((a, b) =>
new Date(a.chartTimeUtc) - new Date(b.chartTimeUtc)
)
// 5. Process in order
for (const item of buffer) {
await processAlert(item)
}
buffer.length = 0
}, BUFFER_MS)The key: the time field used for sorting must be chartTimeUtc (the candlestick bar time on TradingView), not the time the server received the webhook. The former represents the true order of signal occurrence; the latter is affected by network latency.
How big should the buffer window be? 3 seconds is a reasonable starting point — enough to let TradingView's retries be deduplicated by the idempotency key within the same batch, without adding too much delay to actual trades. If your strategy is time-sensitive (e.g., scalping), you can reduce it to 1 second; if you monitor multiple symbols simultaneously, you can extend it to 5 seconds.
Debugging flowchart: from symptoms to root cause
When your bot produces abnormal orders, troubleshoot in this order:
| Check Step | Result | Next Step |
|---|---|---|
| TradingView Alerts log | Only one trigger entry | Proceed to next step |
| TradingView Alerts log | Multiple trigger entries | Cause 1: the alert itself fired multiple times. Check Frequency settings and duplicate alerts, go to the "Once Per Bar Close" section |
| Does the receiver have an idempotency key? | Yes | Proceed to next step |
| Does the receiver have an idempotency key? | No | Add an idempotency key first. This is the ultimate fix for all duplication issues, go to the "Type 3" section |
| Webhook response time | Response < 1 second | Proceed to next step |
| Webhook response time | Response > 2 seconds or timeout | Your receiver is too slow. Switch to ACK fast, deliver later, go to the "delivery retry" section |
| Order time vs trigger time | Order execution order = chartTimeUtc order | No out-of-order issue; duplicates handled by idempotency key |
| Order time vs trigger time | Order execution order ≠ chartTimeUtc order | Out-of-order delivery. Add a timestamp buffer, go to the "Type 4" section |
Prevention checklist: make problems nonexistent before they happen
Duplicates and out-of-order delivery are not occasional bugs; they are inevitable consequences of TradingView webhooks' at-least-once delivery model. To make automated trading reliable, you must build these mechanisms into your design from the start.
| Setting | Recommended Value |
|---|---|
| Frequency | Once Per Bar Close |
| Pine Script | if barstate.isconfirmed |
| Webhook response | < 200 OK within 1 second |
| Deduplication | idempotency key (payload.id) |
| Order guarantee | chartTimeUtc sort buffer |
| Order placement method | Asynchronous queue |
Frequently Asked Questions
Q: Can TradingView's free plan use webhooks?A: No. Webhooks require a Paid plan (Essential or above). Free and Basic plans have no alert functionality at all. This is a TradingView official restriction, not a technical issue.
Q: Does setting multiple alerts trigger a self-limit?A: Yes. TradingView limits strategy alerts: if an alert triggers more than 15 times within 3 minutes, it automatically pauses that alert. On rapidly oscillating candlesticks, frequent crossovers can hit this limit.
Q: How long should you keep the idempotency key? When can you clear it?A: Keep it for at least 24 hours. TradingView's retry window is 5 seconds × 3 retries = 15 seconds, but accounting for network anomalies or server restarts, keeping 24 hours covers all known scenarios.
Q: I monitor multiple symbols (BTC, ETH, SOL) simultaneously — will webhooks be out of order?A: Yes. Alerts for different symbols may trigger hundreds of milliseconds apart, and combined with different network routes, arrival order does not necessarily equal trigger order. A timestamp buffer is especially important for multi-symbol strategies.
Q: Can TradingView webhooks specify a port?A: No. TradingView only accepts ports 80 and 443. If your receiver is not on one of these ports, you need a reverse proxy (nginx, Caddy, etc.) to forward traffic.
Get started
Set up your webhook endpoint on TVSBot and automatically handle duplicates and out-of-order issues
Get started for free- TradingView Webhook Not Responding? Complete Debugging Flowchart from Alert Settings to Exchange Rejections
- How Severe Is TradingView Webhook Delay? Official Specs, Common Causes, and What You Can Fix
- How to Determine Position Size for TradingView Webhook Automated Trading? Capital Ratio vs Fixed Quantity Tradeoffs
- Why Your TradingView Auto-Orders Have the Wrong Size — qty_type=usdt vs margin_usdt Explained
- Which Exchanges Actually Support TradingView Webhook Signals? An Honest 2026 List