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.
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
| Step | What the bot does | Typical tool |
|---|---|---|
| 1. Market data | Pulls candles and the order book, listens to live prices | REST API and websockets |
| 2. Signal | Applies fixed rules to closed candles | Strategy code, or a TradingView alert sent by webhook |
| 3. Risk and size | Checks limits and works out the quantity from the stop | A risk module in the bot |
| 4. Signed order | Builds the order and signs it with the secret | HMAC-SHA256, or Ed25519 on some exchanges |
| 5. Confirmation | Reads the order ID, status and fill price | API response, private websocket updates |
| 6. Protection | Places the stop-loss and take-profit on the exchange | Stop-market or stop-limit orders, reduce-only |
| 7. Monitoring and exit | Watches the position, trails or closes it | Websocket updates, scheduled checks |
| 8. Logs | Records every request, response, fill and fee | Files 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:
| Input | Example |
|---|---|
| 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 value | 20 × ₹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.
| Exchange | Where the key goes | What is signed | Time rule |
|---|---|---|---|
| CoinDCX | Header X-AUTH-APIKEY; signature in X-AUTH-SIGNATURE | The JSON body, which includes a timestamp in milliseconds | The timestamp must be current |
| Delta Exchange India | Headers api-key, signature and timestamp | Method, timestamp, path, query string and body | A signature is valid for only 5 seconds |
| Binance | Header X-MBX-APIKEY; signature parameter | The parameter string | recvWindow 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.
| Field | Example value | What it does |
|---|---|---|
| product_symbol | BTCUSD | The contract to trade |
| side | buy | Direction of the order |
| order_type | limit_order or market_order | A limit order waits for your price; a market order fills now |
| size | 10 | Number of contracts |
| limit_price | 59000 | Your price for a limit order |
| stop_order_type | stop_loss_order | Turns the order into a trigger order |
| stop_price | 56000 | The trigger price |
| reduce_only | true | The order can only reduce or close a position, never open a new one |
| time_in_force | gtc or ioc | Stay open until filled or cancelled, or cancel any unfilled part at once |
| client_order_id | my_signal_345212 | Your 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 type | What it does | How a bot uses it |
|---|---|---|
| Market | Fills now at the best available prices | Fast entries and emergency exits, with slippage risk |
| Limit | Fills only at your price or better | Entries and take-profits; it may not fill |
| Stop-market | When 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-limit | When price hits the trigger, a limit order is placed | Controls the price, but may not fill if the market gaps |
| Take-profit | A trigger order on the profit side | Locks in all or part of a gain |
| Reduce-only | Can only shrink or close a position | Stops 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
| Problem | What happens | Defence |
|---|---|---|
| Exchange outage or maintenance | Orders are rejected and data freezes | Stops held on the exchange; pause new entries while the API returns errors |
| Partial fill | Only part of the order fills | Size the stop to the filled quantity; cancel the rest after a time limit |
| Slippage | The fill is worse than expected in a fast market | Limit orders, a maximum-slippage check, no thin coins; see slippage explained |
| Duplicated order | A timeout makes the bot retry, and both orders fill | Client order IDs; check open orders and positions before any retry |
| Bug | Wrong side, an extra zero in the quantity, a stop on the wrong side of price | Hard caps on size, testnet runs, reading the code twice |
| Clock drift | Every signed request is rejected | Keep the clock synced; alert yourself on authentication errors |
| Rate limit | A temporary block | Back off and queue requests |
| Leaked key | Trades you did not make appear on your account | Delete 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.