100-Day Trade Challenge: trade on our AI predictions, up to 2 trade ideas a day. Free · educational · unregulated & risky Create free account
Cryptos: 21,740 Exchanges: 1,506 Market Cap: $2.87T 2.52% 24h Vol: $100.68B Dominance: BTC: 58.3% ETH: 11.4% Fear & Greed: 74/100 USD/INR: ₹95.83
Trading

How Crypto Trading Bots Place Trades: API vs Webhook

A bot reads prices, checks risk, signs an order with your API key and sends it to the exchange. See each step, a 200-rupee risk example and what fails.

How Crypto Trading Bots Place Trades: API vs Webhook
Photo: Markus Spiske markusspiske, CC0, via Wikimedia Commons

A crypto trading bot places a trade by sending a signed order request to the exchange's API. It reads market data, applies fixed rules to find a signal, works out the position size from the stop-loss, signs the order with your API key and secret, and waits for the exchange to confirm it. A webhook, such as a TradingView alert, can deliver the signal, but the order itself always goes through the exchange API.

Key takeaways

  • Every bot follows the same chain: data, signal, risk and size, signed order, confirmation, stop-loss on the exchange, monitoring and logs.
  • The secret never travels with the order. The bot uses it to compute a signature from the request and a timestamp, and the exchange checks that signature.
  • Size comes from the stop: risking ₹200 with a 2% stop gives a ₹10,000 position.
  • The stop-loss should sit on the exchange as a real order, so it still works if the bot crashes.
  • Automation repeats mistakes as fast as good trades, and most retail bots lose money after fees.

The bot pipeline in eight steps

StepWhat the bot doesTypical tool
1. Market dataPulls candles and the order book, listens to live pricesREST API and websockets
2. SignalApplies fixed rules to closed candlesStrategy code, or a TradingView alert sent by webhook
3. Risk and sizeChecks limits and works out the quantity from the stopA risk module in the bot
4. Signed orderBuilds the order and signs it with the secretHMAC-SHA256, or Ed25519 on some exchanges
5. ConfirmationReads the order ID, status and fill priceAPI response, private websocket updates
6. ProtectionPlaces the stop-loss and take-profit on the exchangeStop-market or stop-limit orders, reduce-only
7. Monitoring and exitWatches the position, trails or closes itWebsocket updates, scheduled checks
8. LogsRecords every request, response, fill and feeFiles or a database, plus alerts to your phone

Step 1: market data from REST and websockets

A REST call is a one-off question: the bot asks for the last 200 one-hour candles of BTC and gets an answer. A websocket is a connection that stays open, so the exchange pushes every new trade or price change as it happens. Most bots use REST for history and websockets for live prices and updates on their own orders. Exchanges can have separate addresses for different regions: Delta Exchange India, for example, uses api.india.delta.exchange for India accounts, and its docs warn that the global address cannot be used for them.

Two habits prevent many bad trades. First, base signals on closed candles, not the candle still forming, or a signal can appear and vanish within the same hour. Second, detect silent disconnections: if no data has arrived for a set time, the bot should reconnect and stop opening trades until prices are fresh again.

Steps 2 and 3: signal first, then risk and size

The strategy turns data into a yes or no, for example "the 20-period average closed above the 50-period average on the four-hour chart, so go long". Our beginner's guide to crypto algo trading covers how to build and test such rules. What separates a careful bot from a reckless one is the next step: the risk check and risk-first position sizing. The bot sizes the trade backwards from the stop-loss, never from how strong the signal looks:

InputExample
Most you accept to lose on this trade₹200
Entry price₹500 per unit
Stop-loss₹490, which is 2% below entry
Loss per unit if the stop is hit₹10
Quantity₹200 divided by ₹10 = 20 units
Position value20 × ₹500 = ₹10,000
Margin at 4x leverage (futures)₹2,500

The formula is position size = money at risk divided by stop distance. A 2% stop with ₹200 at risk gives a ₹10,000 position; a 4% stop halves it to ₹5,000. Leverage changes only the margin you lock up, not the loss at the stop. Real losses end up slightly above ₹200 because of fees, funding and slippage, and a sudden gap can skip past the stop. Before sending the order, the bot should also check the exchange's minimum order size and quantity steps, the free margin, the number of open positions, a daily loss limit, and that the liquidation price sits well beyond the stop.

Our free 100-Day Trade Challenge uses the same rules-then-size logic: each AI-generated trade idea is sized so one stop-loss costs about ₹200 on the default ₹2,220 wallet. The difference is that members place every trade themselves on their own exchange, and there is no guarantee of profit.

Step 4: how the order request is signed

The API key says who you are; the secret proves the request really came from you. The secret itself is never sent. Instead, the bot runs the request contents and a timestamp through HMAC-SHA256, a one-way function, using the secret as the key. The result, called the signature, travels with the request. The exchange holds its own copy of the secret, repeats the calculation and accepts the order only if both signatures match and the timestamp is fresh. If anyone changes a single character on the way, such as the quantity, the signature no longer matches.

ExchangeWhere the key goesWhat is signedTime rule
CoinDCXHeader X-AUTH-APIKEY; signature in X-AUTH-SIGNATUREThe JSON body, which includes a timestamp in millisecondsThe timestamp must be current
Delta Exchange IndiaHeaders api-key, signature and timestampMethod, timestamp, path, query string and bodyA signature is valid for only 5 seconds
BinanceHeader X-MBX-APIKEY; signature parameterThe parameter stringrecvWindow defaults to 5,000 ms, maximum 60,000 ms

Not every exchange uses HMAC. CoinSwitch PRO signs with Ed25519 key pairs, Binance's developer docs recommend Ed25519 keys over HMAC, and Mudrex's current API sends the secret in a header over HTTPS without any signature, which makes keeping it private even more important. The timestamp does the job of a nonce, a "number used once": a captured request cannot be replayed later because its time has passed. That is also why a computer clock that drifts by a few seconds leads to rejected orders, so bots keep their clocks synced. Key creation is covered step by step in our guides on how to create a CoinDCX API key and on API keys on every Indian exchange.

Here is what an order request contains, using the field names from Delta Exchange India's API docs as an example. Other exchanges use different names for the same ideas.

FieldExample valueWhat it does
product_symbolBTCUSDThe contract to trade
sidebuyDirection of the order
order_typelimit_order or market_orderA limit order waits for your price; a market order fills now
size10Number of contracts
limit_price59000Your price for a limit order
stop_order_typestop_loss_orderTurns the order into a trigger order
stop_price56000The trigger price
reduce_onlytrueThe order can only reduce or close a position, never open a new one
time_in_forcegtc or iocStay open until filled or cancelled, or cancel any unfilled part at once
client_order_idmy_signal_345212Your own ID, unique across your open orders (up to 32 characters), which helps catch duplicates

Rate limits

Exchanges cap how many requests you can send. CoinDCX's docs list a general limit of 16 requests a second and 960 a minute. Delta Exchange India uses a quota of 20,000 per five-minute window, with heavier endpoints costing more, and 500 operations a second per product. Limits change, so read the current docs. A bot that ignores rate-limit errors and retries in a tight loop can get blocked for a while, at exactly the moment it needs to close a trade.

Steps 5 to 7: confirmation, stop-loss and exit

The exchange replies with an order ID and a status such as open, partly filled, filled, cancelled or rejected. A market order usually fills at once; a limit order may fill in parts or not at all. The bot must read the actual filled quantity and average price rather than assume the order went through as planned. The basics are in our guide to limit vs market orders.

Order typeWhat it doesHow a bot uses it
MarketFills now at the best available pricesFast entries and emergency exits, with slippage risk
LimitFills only at your price or betterEntries and take-profits; it may not fill
Stop-marketWhen price hits the trigger, a market order is sent (CoinDCX futures lists it as stop_market)A stop-loss that fills in a fast market, at some slippage
Stop-limitWhen price hits the trigger, a limit order is placedControls the price, but may not fill if the market gaps
Take-profitA trigger order on the profit sideLocks in all or part of a gain
Reduce-onlyCan only shrink or close a positionStops an exit order from flipping you into a new trade

As soon as the entry fills, the bot should place the stop-loss as a real order on the exchange. A stop that lives only inside the bot's code works only while the bot is running and connected. If your laptop sleeps, the server reboots or your internet drops, an exchange-side stop still triggers. Some exchanges go further: Delta's API accepts bracket stop-loss and take-profit prices with the entry order, and offers a deadman switch that automatically cancels orders if your bot stops sending regular heartbeat signals.

Monitoring then runs until the exit: moving the stop if the rules say so, closing at the target or a time limit, and checking that the position on the exchange matches what the bot thinks it holds.

Step 8: logs and reconciliation

Log every signal, request, response, fill, fee and error with a timestamp. Logs are how you find bugs, check whether live results match the backtest and prepare tax records. In India every trade is a taxable transfer. Crypto gains are taxed at a flat 30% plus 4% cess, losses cannot be set off against other income, and on Indian exchanges 1% TDS is deducted on each qualifying spot sale, so a bot that sells 50 times a day creates 50 TDS entries. Our guide to 1% TDS on crypto explains how that money comes back. The tax treatment of futures is not settled; see crypto futures legal and tax rules.

Where webhooks fit: API vs webhook

A webhook is inbound: another service calls your bot when something happens. The API is outbound: your bot calls the exchange. In a TradingView set-up, TradingView decides the signal (step 2) and sends it by webhook, but your receiver still has to do steps 3 to 8 through the exchange API. Our guide on what a webhook is in crypto trading covers the set-up, placeholders and security. Exchanges with a built-in webhook bot, such as Delta Exchange India, do the receiver's job for you.

What can go wrong

ProblemWhat happensDefence
Exchange outage or maintenanceOrders are rejected and data freezesStops held on the exchange; pause new entries while the API returns errors
Partial fillOnly part of the order fillsSize the stop to the filled quantity; cancel the rest after a time limit
SlippageThe fill is worse than expected in a fast marketLimit orders, a maximum-slippage check, no thin coins; see slippage explained
Duplicated orderA timeout makes the bot retry, and both orders fillClient order IDs; check open orders and positions before any retry
BugWrong side, an extra zero in the quantity, a stop on the wrong side of priceHard caps on size, testnet runs, reading the code twice
Clock driftEvery signed request is rejectedKeep the clock synced; alert yourself on authentication errors
Rate limitA temporary blockBack off and queue requests
Leaked keyTrades you did not make appear on your accountDelete the key first, then check open orders and positions

Keys, security and honest expectations

A bot's API key needs trading permission and nothing more:

  • Never enable withdrawal permission on a bot key.
  • Bind the key to your server's fixed IP address where the exchange allows it. Delta Exchange India requires this for trading keys.
  • Store the secret like a password, in an environment variable or a secrets manager, never in code you share.
  • Delete keys you no longer use, and replace a key at once if you suspect a leak.
  • Never paste a secret into Telegram, WhatsApp, a Google Form or a website you do not trust.

Anyone who promises guaranteed returns from a bot in exchange for your API key is showing a classic scam sign. Read whether it is safe to give an API key to a trading bot before connecting any service, and use only exchanges registered with FIU-IND.

Finally, a bot is not a money machine. It follows rules faithfully, including bad ones, and it automates mistakes as quickly as good trades. Most retail bots lose money after fees, funding and slippage, and backtests overstate what live trading delivers; our guide on how to backtest a crypto trading strategy shows why. Test on a testnet or in paper mode first, then go live with the smallest size the exchange allows.

FAQ

How do crypto trading bots work?

A bot reads price data, applies fixed rules to decide when to trade, sizes the position from its stop-loss and sends a signed order to the exchange through its API. It then places a stop-loss on the exchange and manages the exit.

Do trading bots need my API key?

Yes. Any bot that places orders on your account needs an API key with trading permission; never give it withdrawal permission, and bind it to fixed IP addresses where the exchange allows.

What is the difference between API trading and webhook trading?

In API trading your program sends orders to the exchange directly. In webhook trading an alert service such as TradingView sends a signal to a receiver, which then places the order through the exchange API.

Can a trading bot place a stop-loss automatically?

Yes. A well-built bot places a stop order on the exchange right after entry, ideally reduce-only, so it still works if the bot or your internet goes down.

Why does the exchange reject my bot's orders?

The usual causes are a wrong signature, a computer clock that is a few seconds off, a request from an IP address not bound to the key, a missing trading permission or an order below the minimum size. The exchange's error message normally names the problem.

Can a crypto trading bot guarantee profit?

No. A bot only follows rules, most retail bots lose money after fees and slippage, and anyone promising guaranteed returns is a red flag.


This article is AI-assisted, educational and general in nature. It is not financial advice and never a guarantee of profit. Every trade is at your own risk on your own exchange. See our risk disclosure and editorial policy.

Put it into practice

Run the 100-trade challenge: cap every loss, log every trade, and find out honestly whether you have an edge.