fbpx
Tickerly Trading bot service logo

BLOG

How to Prevent Duplicate Orders in a TradingView Trading Bot

by

To prevent duplicate orders in a trading bot, start where duplicates are born: one alert per strategy and connection, signals that fire once, and exits that can only reduce a position. If you run your own webhook receiver, add two more layers: record a unique key for each alert in durable storage before you call the exchange, and send the exchange its own client order ID so a retried request is rejected instead of filled twice. Together, those layers cover almost every double fill, whether it comes from a webhook retry, a double-fired alert or a race between two requests.

This guide is written for traders who run TradingView strategies through webhooks. It explains where duplicates come from, what each layer of defense does, how to test it, and which parts still apply when a managed platform such as Tickerly runs the receiver for you.

Tickerly
Automate TradingView Strategy Execution
Tickerly turns TradingView strategies into trading bots, helping active traders automate execution across crypto, forex, and stock exchanges.

Visit Tickerly

TL;DR

  • Duplicates happen. TradingView can resend a webhook, a slow receiver can make a single alert look like several requests, and a forgotten second alert sends every signal twice.
  • Stop them at the source. One alert per strategy and connection, signals that fire once, and exits that can only reduce a position. This layer applies on any platform, Tickerly included.
  • In your own receiver, dedupe before the broker call. Write an idempotency key to a database or cache with a unique constraint first, then place the order.
  • Use the exchange as a backstop. If your own code places the orders, a client order ID makes the exchange reject a repeat of the same order.
  • Test on purpose. Send the same payload several times in a row, and slow your receiver down, before any live capital is at risk.
  • Check your setup. Whatever tool you use, confirm how it handles repeats before you trust it with size. Tickerly places an order for each valid alert it receives, so on Tickerly the prevention lives in your alert setup.

Table of Contents

Why duplicate orders happen in the first place

A webhook is an HTTP message, not a guaranteed trade. Between your Pine Script alert and the exchange there are at least three hops, and each can repeat or delay a message.

TradingView retries failed deliveries

According to TradingView’s webhook resubmission documentation, if the receiving application answers with an HTTP status between 500 and 599 (except 504), the notification is sent again after about 5 seconds. A single alert can therefore produce up to four delivery attempts in total. The same page notes that a receiver that takes longer than 3 seconds to respond risks being treated as timed out.

Webhook retry timing and delivery limits

Here is the trap. Your server may have accepted the first request and placed the order, then crashed or stalled before replying. From TradingView’s side the delivery failed, so it sends the alert again. Without protection, your bot buys twice.

Alerts that fire more than once

Not every duplicate comes from the network. Common causes on the strategy side include:

  • Two alerts created for the same strategy, for example after copying a chart layout.
  • An indicator or alert() condition set to fire every time it is true rather than once per bar close, or an extra indicator alert on the same condition as the strategy’s own order-fill alert.
  • Strategy logic that flips from long to short on the same bar and sends both an exit and an entry.
  • Repainting or intrabar conditions that toggle several times before the bar settles.

These produce messages that look different to the network but represent one trading intent, which is why they are best fixed in the alert setup. A receiver’s dedupe logic would need to understand intent, not just bytes.

Race conditions under load

If two identical requests arrive within milliseconds, a naive check (“have I seen this before?”) can pass for both because neither has written its record yet. Both then call the exchange. This is the classic check-then-act race, and it appears most often during volatile moments, exactly when many alerts fire together.

The three-layer defense

If you build the whole pipeline yourself, no single control is enough. Think of the layers as independent nets: if one fails, the next catches the order.

Layer What it does What it catches
Alert design One alert per strategy, one firing per bar close Duplicate signals at the source
Idempotency key at the receiver Rejects a repeat of the same trading intent Webhook retries, double alerts
Client order ID at the exchange Exchange refuses a repeated order Race conditions, bugs in your own dedupe

Layer 1 is yours on any platform. Layers 2 and 3 are code you write when you host your own receiver and place orders through the exchange API, and they come with that receiver’s hosting, uptime, security and maintenance. On Tickerly, the receiver and the exchange call are Tickerly’s. The alert has no ID field and Tickerly places an order for each valid alert it receives, so Layer 1 is the layer a Tickerly user controls. The backstop is built into the alert: with prev_position, closing orders go out reduce-only, so a repeated exit can only flatten a position, never open one in the other direction.

Layer 1: design your alerts to be repeatable

Start where the signal is born.

  1. Keep one alert per strategy per chart. Audit your alert list for duplicates before you go live.
  2. Prefer bar-close confirmation. Alerts that trigger once per bar close are far easier to dedupe than alerts that fire on every tick.
  3. Put the bar time in the message if your receiver dedupes. Use TradingView placeholders such as the ticker, interval and bar time inside the JSON so each legitimate signal carries a distinct identity. A Tickerly alert doesn’t need them; fields it doesn’t use are ignored.
  4. State the position, not only the action. A message that says “target position: long 1” is safer to repeat than one that says “buy 1”, because processing it twice leaves you in the same place. Tickerly’s alert does part of this with prev_position: it marks closing orders, which go out reduce-only, so a repeated exit can only flatten your position. A repeated entry is still a second entry, which is why the first two points matter.

That last point is worth emphasizing. An order that describes a desired end state is naturally idempotent. An order that describes a delta is not.

Layer 2: an idempotency key at the receiver

Idempotency means that handling the same request twice has the same effect as handling it once. If you run your own receiver, the standard approach is to derive a key from the alert, store it, and refuse anything you have already stored.

Build the key from trading intent

A TradingView webhook strategy template aimed at exactly this problem describes keying on fields such as the ticker, interval, bar time and action. Hashing those together gives a stable key that is identical for a retry and different for the next bar.

A few practical rules:

  • Do not hash the whole message blindly if it contains dynamic fields such as a send-time stamp. Two copies of the same alert would then hash differently and slip through.
  • Include a strategy identifier so two strategies trading the same symbol do not block each other.
  • Include the action and, if you use it, the intended position phase, so a legitimate exit and re-entry on the same bar are not collapsed into one.

An example key might combine strategy name, symbol, timeframe, bar open time and action, joined and hashed with SHA-256. The exact format matters less than being deterministic.

Insert first, trade second

Order of operations is the whole game. The template above makes the point that the record must be written before the broker call. If you place the order and then record the key, a retry arriving while the first call is still in flight finds nothing and trades again.

A safe sequence:

  1. Receive the webhook and validate it (token or signature, valid JSON, known symbol).
  2. Attempt to insert the idempotency key into a store with a unique constraint.
  3. If the insert fails because the key exists, return a success response and stop. Do not trade.
  4. If the insert succeeds, place the order.
  5. Update the record with the result (order ID, fill status, error).
  6. Respond quickly.

Use a single atomic insert rather than a read followed by a write. A webhook security guide on DEV Community recommends strict database-level unique constraints so each event is processed exactly once, and an atomic check-and-insert is what closes the race window described earlier. A database with a unique index or a Redis SET with the not-exists option both fit.

Answer fast, even when you ignore a duplicate

Returning an error for a duplicate invites another retry. Acknowledge it with a 200 response and log it as rejected. Likewise, do the slow work (exchange calls, logging) after you acknowledge, or keep it well under the 3-second window TradingView describes, so you do not manufacture the very retries you are guarding against.

Add replay protection if the sender supports it

TradingView alerts do not carry a signed timestamp the way some payment providers’ webhooks do, so you typically add your own secret token in the message body. For senders that do sign requests, the same DEV Community guide covers HMAC verification and rejecting requests older than about five minutes. That stops an attacker from replaying a captured valid request, which is a different threat from an accidental retry but produces the same result: a second order.

On Tickerly there is no token to add. The alert carries no credentials, only the ticker, the order and a private pointer that identifies your connection. Keep the pointer private, give your API keys no withdrawal rights, and whitelist Tickerly’s IP address, 217.160.238.76, on the exchange.

Layer 3: client order IDs at the exchange

Even well-written receivers have bugs, restarts and edge cases. When your own code places the orders, a client order ID lets the exchange enforce uniqueness for you.

Most serious venues accept a client-assigned identifier on order placement. Binance’s spot trading endpoints document a client order ID parameter, and Kraken’s client order identifier guide explains that you tag orders with your own text or UUID and that Kraken verifies uniqueness across your open orders. The parameter names differ (newClientOrderId, cl_ord_id, cloid), and the exact uniqueness rules differ too, so read your exchange’s documentation for how long an ID stays reserved and what error a repeat returns.

To use it well:

  • Derive the ID from the idempotency key, not from a random value. A random ID per attempt defeats the purpose, because a retry would get a new ID and sail through.
  • Respect length and character limits. Hash, then truncate to what the venue allows.
  • Handle the rejection gracefully. A duplicate-ID error on a retry means the first order went through. Query the order status by that ID rather than treating it as a failure and trying again with a new one.

This layer is your insurance against the one scenario the receiver cannot see by itself: you placed the order, the connection dropped before you got the answer, and you do not know whether it landed. Resending with the same client order ID is safe. Resending with a fresh one is not.

Reconcile positions, not just messages

Deduplication tells you what you intended. Reconciliation tells you what actually happened. Run a periodic check that compares your bot’s expected position with the exchange or broker position, and alert you on any mismatch. On Tickerly that check is yours to make, because Tickerly doesn’t compare your strategy’s position with the exchange’s: look at the alert log and the exchange position, and if they drift, send a close all alert to flatten the symbol (not available on Alpaca or MetaTrader) and restart the strategy flat.

Expected and exchange positions compared for mismatches

For futures and leveraged products the cost of drift is larger, which is why a maximum position size belongs in your strategy, where every order passes through it. Our guides on managing risk in trading bots and futures trading bots cover maximum position sizes and kill switches. If you trade a funded account, a double fill can breach a rule in a single bar, so read the prop firm trading bot rules before you connect anything.

A test plan before you go live

If you built your own receiver, attack its duplicate guard before you trust it, because a guard you have never attacked is a guess. Run these tests on a paper account or exchange testnet.

  1. Same payload, five times, quickly. Exactly one order should result. Four should appear in your log as rejected duplicates.
  2. Same payload, one second apart. Same expectation.
  3. Slow receiver. Add an artificial delay of more than three seconds and a forced 500 response after placing the order. Confirm the retry does not trade again.
  4. Crash mid-flight. Kill the process after the key insert and before the broker call, then restart. Decide deliberately whether that intent is lost or replayed, and make sure your logs tell you which.
  5. Two strategies, one symbol. Confirm that two legitimate signals on the same bar are not blocked by each other’s keys.
  6. Same bar, flip. Send an exit followed by an entry on the same bar and verify both execute.
  7. Exchange-side check. Submit two requests with the same client order ID and confirm the exchange rejects the second.

Keep the results. When something odd happens at 3 a.m., a record of how the system behaved under test saves hours.

On Tickerly you test the alert setup instead, on a demo connection: any connection with “test” in its name routes to the exchange’s demo account, where the exchange has one. Run the strategy for a session and check that the alert log shows one alert per strategy order. Use Send manual alert to send the same exit twice and confirm the second can’t open a position in the other direction. If two strategies share a symbol, confirm they stay apart, with hedge mode or a separate sub-account connection for each.

Common mistakes

  • Checking the key after placing the order. This reopens the race.
  • Using a random UUID as the dedupe key. It is unique per request, so it dedupes nothing.
  • Keys that never expire, or expire too soon. Keep them longer than the longest plausible retry window, and clear them eventually so storage does not grow without bound.
  • Returning errors for ignored duplicates. This triggers more retries.
  • Trusting the alert list. A forgotten second alert on an old chart layout is a frequent culprit. Audit it.
  • Skipping reconciliation. Dedupe can be perfect and you can still diverge because of a partial fill or a manual trade.

Our perspective: what we see in automated trading

We built Tickerly around one idea: your TradingView strategy should reach the exchange fast, without you maintaining a server. Orders go out within a fraction of a second of the alert, setup is no-code, direct exchange connections need no VPS, and plans run from 20 active strategies on Level 2 to unlimited from Level 3. That matters for duplicates in a way people do not expect.

Self-hosted bots fail on duplicates for mundane reasons: a small server that responds slowly, a script that restarts, a database nobody tested. Every extra piece you run is another place for the 3-second window to be missed. When you remove the server from your own stack, those pieces are no longer yours to build, host and keep running. It does not remove the need for sound alert design. Tickerly places an order for each valid alert it receives and sends closing orders reduce-only, so we still tell traders the same things: one alert per strategy, bar-close confirmation, a defined position size, and a habit of checking your positions against the exchange.

Where your strategy logic can send repeated or conflicting signals, we would rather you find it in a paper test than in live capital. Our guide on going from TradingView alert to live order walks through the setup, and the automated trading FAQ answers common questions. If you build your own receiver instead, everything in this article applies in full.

Speed and safety are not opposites. A fast bot that double-fills is a faster way to lose money, and a careful bot that is late misses the move. Aim for both, and measure both.

— Jay

Skip the server, keep the control

If you would rather not host and harden a webhook receiver, Tickerly connects your TradingView alerts to supported exchanges and brokers with no coding, and with no VPS for direct exchange connections. MetaTrader 4 and 5 are supported too, through the Tickerly TV Connector in your own terminal, which has to stay running. Plans are priced by asset class, strategy count and alert limits: Level 2 is 19 USD per month, Level 3 is 29 USD per month, Level 4, which adds MetaTrader, is 39 USD per month, Level 4 Ultra raises the limit to 2,500 alerts a day, and there is a 30-day free trial. Compare them on the Tickerly plans page, then run the Tickerly checks above on a demo connection before you scale.

FAQ

What is the most reliable way to stop duplicate orders from TradingView alerts?

It depends on who runs the receiver. If you do, combine an idempotency key stored before the broker call with a client order ID on the exchange: the key stops repeats at your receiver, and the client order ID stops them at the exchange if your own check fails. Neither one alone covers every case. On a platform such as Tickerly, which places an order for each valid alert it receives, stop duplicates at the source: one alert per strategy and connection, the strategy’s order-fill alerts, once-per-bar-close for indicator alerts, and prev_position in the alert so exits go out reduce-only.

Can TradingView send the same webhook more than once?

Yes. TradingView states that it resends a webhook after about five seconds when the receiver returns certain 5xx errors, and a receiver slower than three seconds may be treated as timed out. Your receiver must therefore expect the same alert to arrive more than once.

Should I use a timestamp or a hash as the dedupe key?

Use a hash of stable trading-intent fields such as strategy, symbol, interval, bar time and action. A timestamp alone can differ between copies of the same alert, and hashing a full message that contains dynamic fields has the same problem.

Do I still need to deduplicate if my bot is hosted by a platform?

The platform runs the receiver, but duplicate signals that start in your strategy or alert setup still reach it. Tickerly, for example, places an order for each valid alert it receives and sends closing orders reduce-only, so a repeated exit can only flatten a position while a repeated entry is still an entry. Design alerts carefully, keep one alert per strategy and connection, check positions against your exchange, and confirm the behavior on a demo account before trading live size.

Sources

This article was produced with Al assistance and reviewed for accuracy. It is provided for general information only and is not professional or financial advice.

Tags :

Latest Post