How developers can use webhooks and automation to run trading agents
Webhooks let trading agents react to external signals, price thresholds, and account events through a single API that enforces scoped keys, budget caps, and built-in safety limits.
- 01Webhooks turn trading agents into event-driven systems that react to external signals instead of polling market data.
- 02The webhook handler must authenticate, validate, map, and check risk before converting a payload into a dollar-based order intent.
- 03Scoped keys, budget caps, position limits, and a panic switch bound the damage from a compromised handler or duplicate signal.
- 04Paper trading with synthetic webhooks lets developers test mapping logic and safety triggers before authorizing live keys.
- 05Stale signal rejection and idempotency keys prevent retries and delayed payloads from causing accidental trades.
Webhooks give trading agents a way to act on events that happen outside the order book. Instead of polling for price changes or waiting for a user to type a command, a developer can configure an HTTP endpoint that receives a payload and translates it into an order intent. The agent then sends that intent to a single API which normalizes sizing, checks safety limits, and routes it to the correct market. This turns external signals into executed trades without manual intervention.
What are webhooks and why do trading agents use them?
Trading agents traditionally rely on two information sources: market data feeds and direct user prompts. Both have latency and scalability problems. A price feed requires constant polling, which wastes compute and still misses gaps between requests. A user prompt requires a human to be present at the exact moment a condition is met. Neither model works well when a strategy needs to react instantly to a macroeconomic report, a cross-market arbitrage signal, or a risk alert generated by an external analytics platform.
A webhook is a user-defined HTTP callback. When an external system detects an event, it pushes a JSON payload to the developer's endpoint. For trading, that event might be a price threshold crossing, a volatility spike detected by an analytics service, a macroeconomic data release, or even an internal risk alert. The agent receives the payload, validates it, and decides whether to trade. The sender does not need to know anything about the agent's strategy; it only needs to know the endpoint URL and the shared secret used to sign the request.
The key benefit is that the agent becomes event-driven rather than polling-driven. It sleeps until something important happens, then wakes up, evaluates the signal against its strategy, and either acts or ignores it. This is particularly useful for strategies that depend on off-chain data, sentiment analysis, or cross-market indicators that are not available inside a single venue's API. Because the signal arrives as a discrete event, the agent can also timestamp and log every decision with a clear audit trail. This trail is useful later when reviewing why a trade occurred, especially if the strategy combines multiple webhook sources.
How do you route external signals into order intent?
The webhook handler sits between the signal and the trading API. Its job is to transform an arbitrary external payload into a structured order intent that the API understands. This translation layer is where most automation logic lives, so it deserves careful design. A poorly written handler might misinterpret a signal, ignore a safety check, or fail to account for an open position that already exists.
A typical handler performs four steps: authenticate the sender, validate the payload schema, map the signal to a dollar-based order size, and check pre-trade risk filters. Authentication prevents spoofed requests. Validation ensures the payload contains required fields like symbol, side, and confidence score. Mapping converts the signal's recommendation into a concrete dollar amount based on the agent's current budget. The pre-trade check queries the API for existing exposure and pending orders to avoid accidental doubling.
The single API accepts orders sized in plain US dollars. This means the webhook handler does not need to know venue-specific contract sizes, margin requirements, or lot increments. It simply specifies the desired exposure in dollars, and the API normalizes the rest. For example, a signal that says increase BTC exposure by five hundred dollars becomes an order object with a notional value of 500. The API then translates that into the correct quantity at the relevant perps venue or crypto exchange. The same logic applies to stocks, options, and prediction markets, so the handler code stays identical even when the strategy trades across multiple asset classes.
Developers should keep the handler stateless where possible. Store strategy state in a database or cache, not in memory, so that restarting the service does not erase pending signals or position context. A stateless handler also scales horizontally if signal volume spikes. If the strategy requires state, persist it externally and load it at the start of each request. This pattern makes the automation layer robust against crashes and deployments.
What safety controls keep automated agents from overtrading?
Automation without limits is dangerous. A webhook that fires too often, or a bug that sends duplicate payloads, can generate a cascade of unwanted orders. The Felix safety model applies controls at the API level, so even if the webhook handler is compromised, the agent cannot spend beyond its owner-defined boundaries. How a single API keeps AI trading agents safe across every market
The first line of defense is the scoped API key. A key created for a webhook handler can be restricted to specific markets, order types, and maximum dollar amounts per order. If the key is leaked, the attacker cannot withdraw funds or trade markets outside the scope. Scoped keys are separate from owner keys, so revoking one does not affect the others.
Budget caps enforce a hard ceiling on total notional exposure over a rolling window. Position limits prevent the agent from concentrating too heavily in a single asset. Exit plans, which can be configured as automated instructions attached to the key, flatten positions when drawdown thresholds are breached. Finally, a panic switch revokes the key instantly and cancels open orders. These controls work together so that a runaway loop or malicious payload hits a wall before it can do serious damage.
These controls are non-custodial by construction. The funds remain in the owner's wallet. The agent can spend within limits but cannot withdraw to an arbitrary address. Withdrawal addresses are owner-approved only. This means a compromised webhook handler might lose the capped budget, but it cannot drain the wallet. Trading can lose money, including everything, so these limits exist to bound that risk rather than eliminate it.
How should you structure a webhook handler for a single API?
The exact request schema is in the docs; the shape looks like this. The handler should verify the webhook signature using a shared secret or HMAC before parsing the body. After verification, it should fetch the agent's current budget and open positions from the API to ensure the new order will not violate caps. Only then should it POST the order intent. This sequence keeps the agent from trading on forged signals or stale data.
POST /orders
Authorization: Bearer YOUR_KEY
Idempotency-Key: webhook-uuid-789
{
"marketType": "perps",
"symbol": "ETH",
"side": "sell",
"notionalUsd": 250,
"timeInForce": "ioc"
}Idempotency is critical. A trading signal might be delivered twice due to retries. The handler should generate an idempotency key from the signal's unique identifier and include it in the API request. This prevents the same signal from creating two orders. The API uses this key to recognize duplicates and reject the second request, even if it arrives minutes later.
Logging should record the raw payload, the mapped intent, and the API response. If a signal is rejected because it breached a safety limit, the log should explain why. This audit trail helps developers debug strategy logic without exposing secret keys. Logs should also capture timing information so developers can measure latency from signal generation to order acceptance.
How do you test automation before committing real money?
Webhook automation should be tested in paper trading before live trading is enabled. Paper trading uses the same API shape and safety controls as live trading, but it executes against simulated market data. This lets developers verify that their handler maps signals correctly, that idempotency keys work, and that safety limits trigger as expected. How developers can backtest AI trading strategies before going live
A good testing sequence starts with synthetic webhooks. Send a payload from a local script to the handler and confirm the resulting order intent matches expectations. Inspect the logs to see that the handler parsed every field correctly and that the dollar-based size matched the strategy rules. Then run the handler against the paper trading API for several days with real signal feeds. Monitor logs for duplicate signals, unexpected rejections, and latency spikes.
Only after paper trading demonstrates stable behavior should the developer authorize a live key. The authorization step is explicit: the owner must approve the key for live trading, which is a separate permission from paper trading. This two-step process prevents an accidental switch from simulation to real money. Remember that trading can lose money, including everything, and paper results do not guarantee live performance.
What happens when a webhook fails or a signal goes stale?
Networks are unreliable. A webhook delivery might time out, or the handler might return an error. The sending system will usually retry, which means the handler must be prepared to receive the same signal multiple minutes after it was generated. A stale signal might reference a price that no longer exists. Without a freshness check, the agent could trade on outdated information and enter a position that the strategy no longer supports.
The handler should timestamp every incoming payload and define a maximum age. If a signal arrives more than a few minutes late, the handler should reject it. This prevents the agent from trading on outdated news. For time-sensitive strategies, this window might be seconds. For slower strategies, it might be minutes. The exact threshold belongs in the strategy configuration, not hard-coded, so it can be adjusted without redeploying the handler.
If the handler itself crashes, the agent stops trading. That is usually safer than continuing blindly. To reduce downtime, run the handler as a managed service with health checks. If the API cannot reach the handler, orders simply do not execute. The safety limits remain in place, and the owner's funds are untouched. A crash is a failure of automation, but it is not a breach of the safety model.
It is also worth defining a fallback state. If the agent misses a critical entry signal because the webhook failed, the strategy should not assume the position was opened. The next successful signal should re-evaluate the full market state rather than assuming a prior order filled. How to build your first automated exit plan without losing control This defensive posture prevents phantom positions and keeps the agent's internal model aligned with reality.
Frequently asked questions
Yes, once you authorize a scoped API key for live trading. The handler can send orders within the limits you set, but it cannot withdraw funds or change your safety controls. You retain full ownership of the wallet and can revoke the key at any time.
No. The API accepts orders in plain US dollars, so your handler only needs to specify the desired notional exposure. The API normalizes quantities and contract math for the relevant market type. This keeps your automation code simple even when you trade across stocks, crypto, perps, options, and prediction markets.
The handler should include an idempotency key derived from the signal's unique identifier. The API recognizes duplicate keys and rejects the second request. You should also log every payload so you can verify that duplicates were handled correctly.
Use the panic switch to revoke the API key instantly and cancel open orders. Because the model is non-custodial, the funds stay in your wallet and the agent cannot override the revocation. This is faster than trying to edit the handler code during an incident.
Paper trading proves that your handler maps signals correctly and respects safety limits. It does not guarantee live performance, because slippage, latency, and market impact differ in real markets. Always start live trading with a small budget and tight caps after paper testing succeeds.
Yes, but each source should feed into the same stateless handler or a shared state store. The handler must resolve conflicts, avoid double-counting signals, and respect the global budget cap. Adding more sources increases complexity, so test each one independently before combining them.
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.
You can connect an LLM to real markets through one API that normalizes five asset classes and enforces safety limits you control.