How to automate trading agents with webhooks step by step
Learn how webhooks let trading agents react to market events automatically. This step-by-step guide covers setup, safety controls, and non-custodial automation.
- 01Webhooks let trading agents react to market events as they occur instead of polling continuously, which reduces latency and API usage.
- 02Every webhook endpoint must verify request signatures and use idempotency keys to prevent forged events and duplicate trades.
- 03Hard limits like budget caps, position limits, and scoped API keys are essential because automation can magnify mistakes faster than a human can intervene.
- 04A webhook handler should acknowledge receipt quickly, process events through a queue, and ignore stale or out-of-order payloads.
- 05Always test webhook handlers in paper trading mode and validate safety controls before connecting a live trading key.
Webhooks let a trading agent receive event-driven updates from markets and data sources instead of polling for changes. A webhook sends a structured payload to an endpoint you control whenever a relevant event occurs, such as a price threshold being met or a position changing status. This architecture reduces latency, cuts unnecessary API calls, and lets an agent react to conditions as they arise rather than on a fixed schedule. Setting up automation requires a secure endpoint, clear event mapping, and hard safety limits that prevent a single webhook from causing catastrophic losses.
What are webhooks and why do trading agents need them?
Polling means your agent repeatedly asks the API for the latest price, order status, or position data. At one request per second, that is 86,400 requests per day. Most of those return identical data because nothing changed. Webhooks invert this flow. When a price moves past a threshold you set, or when an order fills, the system pushes that fact to your agent. Your agent only wakes up when something actionable happens.
For a trading agent that operates across multiple market types, this efficiency matters. A single agent might track stocks, crypto spot, perpetual futures, options, and prediction markets. Polling each venue on its own schedule creates complexity. Webhooks through a unified API normalize these events into one schema. Your handler receives one format whether the underlying market is a stock or a perp.
Latency is another factor. A polling loop might check every five seconds due to rate limits. In fast markets, five seconds is enough for a price to gap, a liquidation to occur, or a signal to decay. Webhooks arrive as the event happens, though they still travel over the internet and are subject to network delays. They do not guarantee profit. Trading can lose money, including everything, and faster reaction time can just as easily accelerate losses as gains.
How do you set up a webhook endpoint for a trading agent?
You need a server or serverless function that accepts HTTPS POST requests. It must be reachable from the public internet, which means you cannot use localhost during production. For local development, a tunneling proxy can forward requests to your machine. In production, use a host with a valid TLS certificate.
The endpoint should verify each request before acting. Verification typically uses a signature header and a shared secret. You compute the expected signature from the payload and your secret, then compare it to the header. If they do not match, drop the request and log the attempt. This prevents an attacker from forging events that trigger unwanted trades.
Once verified, parse the payload and extract the fields relevant to your strategy. Common fields include event type, market identifier, symbol, price, timestamp, and a unique event ID. The unique ID is critical for idempotency. Store it temporarily so that if the same event is delivered twice due to a retry, you do not trade twice.
The exact request schema is in the docs; the shape looks like this:
curl -X POST https://your-agent.example.com/webhook \
-H "Content-Type: application/json" \
-H "X-Webhook-Secret: YOUR_KEY" \
-d '{
"event_id": "evt_unique_123",
"event_type": "price_threshold",
"market_type": "perpetual",
"symbol": "EXAMPLE-USD",
"price": "123.45",
"direction": "above",
"timestamp": "2026-08-16T12:34:56Z"
}'Your handler should return a 2xx status code quickly. If the handler takes too long, the sender may assume failure and retry, which can cause duplicate processing. Acknowledge receipt immediately, then do the heavy work of decision making and order placement in a background queue or thread.
What events should a trading agent listen for?
Not every event deserves a trade. A well-designed agent subscribes to a small set of high-signal events and ignores noise. The specific events depend on your strategy, but most agents start with a common subset.
- ·Price thresholds are the most common. You set a level, and the webhook fires when the last traded price crosses it. Be explicit about whether you want the bid, ask, or last price, because the three can diverge. A threshold on the last price might fire while the spread makes entry unprofitable.
- ·Order lifecycle events tell you when an order fills, partially fills, or is rejected. These are essential for state management. If your agent thinks it is flat but the webhook says a limit order filled, the agent must update its internal record before sending a new order. Otherwise it might double its intended exposure.
- ·Position updates report size, average entry price, and unrealized profit or loss. You can use these to trigger risk reduction. For example, if a position update shows unrealized losses exceeding a preset percentage, a webhook handler might send a reduce-only order. This is safer than relying on the agent to poll for profit and loss.
- ·For perpetual futures and options venues, margin and collateral events matter. A webhook that fires when margin utilization crosses eighty percent gives the agent time to add collateral or reduce size before an automatic liquidation. This is a safety event, not a profit event.
- ·External signals are also valid. You might have a separate analytics system that detects patterns in order book data. When that system finds a pattern, it sends a webhook to your agent. The agent does not need to read the order book itself.
- ·Finally, some agents listen for scheduled maintenance or funding rate events. A funding rate webhook might trigger a position flip if the cost of carry becomes too high.
External analytics systems can offload complex work. How an AI agent reads an order book covers the complexity of that task, and delegating it to a dedicated service can simplify your agent.
How do you keep automated webhooks safe?
Automation magnifies mistakes. A bug in a webhook handler can place orders faster than a human can intervene. The first layer of defense is the API safety model itself. How the safety model for trading agents differs from trading bots explains why agents need stricter boundaries than traditional bots. Apply those boundaries here.
Use scoped API keys. The key your webhook handler uses to place orders should have no withdrawal permissions and should be restricted to specific markets and order types. If the handler is compromised, the attacker can only trade within those bounds.
Set budget caps and position limits before you enable webhooks. A budget cap is a daily or weekly maximum loss. Once reached, the API rejects further orders from that key regardless of how many webhooks fire. Position limits prevent a single event from creating an oversized bet. These are enforced by the infrastructure, not by your code, so a bug in the handler cannot override them.
Verify webhook signatures on every request. Without this, an attacker who discovers your endpoint URL can send crafted payloads. Use a constant-time comparison function when checking signatures to prevent timing attacks. Implement idempotency at the application level. Even if the signature is valid, network retries can deliver the same event multiple times. Check the event ID against a short-term cache or database. If you have seen it in the last hour, ignore it. An hour is usually enough to cover retry windows.
Include a kill switch. You should be able to revoke the API key and flatten all positions within seconds. Test this before going live. The kill switch is your last resort when a webhook handler enters an unexpected loop or receives corrupted data. Remember that Felix is non-custodial by construction. Your funds sit in a wallet you control. The agent can spend within limits but can never withdraw to itself or steal. Withdrawal addresses are owner-approved only. A practical checklist for non-custodial AI trading walks through the setup.
How do you handle webhook failures and out-of-order delivery?
Webhooks are not guaranteed to arrive in order, and they are not guaranteed to arrive exactly once. The sender may retry if your handler returns an error or times out. This means you must design for at least once delivery and unordered arrival.
Always check the event timestamp against your last recorded action. If a webhook arrives late and its timestamp is older than your most recent trade, discard it. The market state has already moved on. Acting on stale information can cause you to enter a position that no longer fits your strategy.
Use a queue between receipt and execution. Your webhook handler should write the event to a queue and return a success code immediately. A separate worker process reads from the queue and makes trading decisions. This decouples the webhooks timing from your trading logic and prevents race conditions when two events arrive close together.
Handle duplicates with idempotency keys, as mentioned earlier. Store them in a persistent store, not just in memory, so that a restart of your handler does not erase the record. Have a dead letter path. If a webhook payload is malformed or references an unknown symbol, route it to a dead letter queue rather than crashing or guessing. Review these periodically to catch integration errors.
Monitor for silent failures. If you stop receiving webhooks, your agent might be flying blind. Set up a heartbeat or health check that alerts you when no webhook has arrived in an unexpectedly long window. This is especially important for events that should fire regularly, such as position updates.
How do you test webhooks before live trading?
Never connect a live trading key to a new webhook handler without thorough testing. The consequences of a parsing error or a logic bug are real financial losses. Trading can lose money, including everything.
- 01Start with paper trading. The Felix API offers a paper trading mode where orders execute against simulated markets. Point your webhook handler at a paper trading key and replay realistic events. Confirm that the handler places the expected orders, respects position limits, and stops when the budget cap is reached.
- 02Use a local development tunnel to capture real webhook payloads during development. Save these payloads to a file. You can then replay them against your local handler hundreds of times to verify idempotency, signature validation, and decision logic. This is faster and safer than waiting for live markets to generate events.
- 03Test your safety controls explicitly. Send a webhook that should trigger a trade exceeding your position limit. Confirm the API rejects it. Send a duplicate event with the same ID. Confirm the handler ignores it. Trigger the kill switch mid-execution and confirm the key is revoked and positions are flattened.
- 04Review logs carefully. Every webhook receipt should be traceable to a specific order request, and every order should be traceable back to the webhook that caused it. If you cannot draw this line, your system is not auditable.
How to evaluate paper trading for an AI agent before live markets provides a broader framework for this validation.
Frequently asked questions
Yes, you need a publicly reachable HTTPS endpoint. A serverless function or a small cloud instance works well. Local development requires a tunneling proxy, but production must use a stable host with a valid TLS certificate.
You can, but it is safer to separate them. Each strategy should have its own scoped key and endpoint. This limits the blast radius if one strategy misbehaves and makes debugging easier.
Missed webhooks may queue briefly, but they are not held indefinitely. If your handler is down for too long, events are lost. Design your agent to recover gracefully, perhaps by polling for critical state once it comes back online.
Use idempotency. Store the event ID from each webhook and check it before acting. Also enforce API-level idempotency keys on order requests so that even if your handler errs, the venue rejects the duplicate.
Usually yes, because they push data as events occur rather than on a fixed interval. However, they still travel over the internet and can be delayed. They reduce latency but do not eliminate it, and speed does not guarantee profit.
No. Withdrawal addresses are owner-approved only, and the agent cannot withdraw funds to itself. This is a non-custodial safety feature. Webhooks can trigger trades within scoped limits, but they cannot move funds out of your wallet.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Newcomers often treat scoped API keys like strong passwords. In practice, they are programmable contracts that limit what an agent can do, regardless of whether the agent is buggy, compromised, or hallucinating.
Stock trading agents can lose money faster than manual traders when limits are missing. Enforcing hard boundaries at the infrastructure level keeps agent behavior inside owner-defined guardrails.