Agentic tradingAutomationDevelopersBeginners

How webhooks let trading agents react to events automatically

Webhooks push market events to your trading agent instantly so it can act without constant polling. Learn how they work, how to handle them safely, and how to test before risking real money.

By the Felix team10 min read
Key takeaways
  • 01A webhook pushes market events to your agent instantly, removing the delay and waste of polling APIs every few seconds.
  • 02Your webhook handler should verify signatures, check for duplicate event IDs, and enforce budget caps before it ever calls an order API.
  • 03Felix normalizes webhooks across stocks, crypto, perps, options, and prediction markets into one schema so your agent can listen to a single format.
  • 04Paper trading lets you test webhook logic and hard limits with realistic events before you authorize a live key and risk real money.
  • 05Trading can lose money, including everything, so event speed is never a substitute for guardrails, kill switches, and owner-controlled spend limits.

A webhook is a message that a server sends to your system automatically when something happens, rather than your system asking repeatedly. For a trading agent, this means the agent can be notified of price moves, filled orders, or account changes the moment they occur, then decide whether to trade. This eliminates the delay and waste of constantly polling an API for updates. Because markets move quickly, reducing that delay often matters more than the strategy itself.

What is a webhook and how does it differ from polling?

Polling means your agent sends an HTTP request every few seconds to ask if anything changed. It is simple to understand but inefficient. If you poll once per second, you make 3,600 requests per hour even when nothing happens. Most of those responses will be empty or identical to the previous one. This wastes compute, burns through API rate limits, and still leaves a blind spot between checks.

A webhook reverses the direction. Instead of your agent asking the platform if a price changed, the platform tells your agent when it does. You register a URL, and the platform sends an HTTP POST to that URL the instant an event occurs. Your agent receives the payload, validates it, and acts. This is called an event-driven or push architecture.

Webhooks also help when your agent lives in an environment that sleeps between tasks, such as a serverless function or a local script triggered by an AI code editor. Polling requires the process to stay awake, which costs money and adds complexity. Webhooks let the process stay idle until there is actual work to do. For beginners, this means you can run an agent on a modest laptop or a low-cost cloud function instead of maintaining a dedicated server.

Why do trading agents need event-driven automation?

Trading agents make decisions based on market state. The state includes prices, order book depth, open positions, and account balances. In a polling model, the agent sees a snapshot, thinks, and maybe acts. By the time it acts, the snapshot is already stale. In fast markets, that stale data can lead to bad prices or missed fills.

Event-driven automation narrows the gap between observation and action. When an order fills, the agent learns immediately and can place the next leg of a strategy. When a price crosses a threshold, the agent can open or close a position before the move continues. When a margin ratio changes, the agent can reduce size before an automatic liquidation.

There is also a practical cost issue. Many venues limit how often you can poll. If you exceed the limit, your IP may be throttled or banned. Webhooks usually sit outside the request limit because they are pushes initiated by the venue, not pulls initiated by you. This keeps your access stable and your agent responsive.

Finally, event-driven design simplifies your code. A polling loop needs error handling for network timeouts, backoffs for rate limits, and logic to detect what changed between two identical responses. A webhook handler simply processes one event at a time. The logic is easier to test, easier to audit, and easier to guard with safety checks.

What events can trigger a trading agent?

A trading agent can react to many event types. The exact set depends on the venue and the asset class, but the common categories are similar across stocks, crypto, perps, options, and prediction markets.

Price thresholds are the most common trigger. You configure a webhook to fire when an asset crosses a specific price. Your agent receives the event, checks its strategy rules, and decides whether to enter or exit. This is often used for breakout or mean-reversion strategies.

Order fill events tell the agent that a resting order executed. This is critical for strategies that chain orders together. Suppose a buy order fills. The agent might immediately place a take-profit order and a stop-loss. Knowing the fill price instantly lets the agent size the follow-up orders correctly.

Account and margin events warn about changes in buying power or collateral. In leveraged products, a sudden drop in margin can precede liquidation. A webhook can alert the agent to reduce position size or add collateral before the venue does it automatically.

External signal events come from outside the market. A news feed, an on-chain metric, or a social sentiment score can push a webhook to your agent. The agent treats this as an input, not a price input, and may adjust its bias or pause trading until the signal clears.

Portfolio drift events are useful for rebalancing. If an asset allocation moves outside a target band, a webhook can notify the agent to trade back to the target weights. This keeps long-term allocations in check without the agent watching prices every second.

How does Felix route webhooks safely?

Felix sits between your agent and the trading venues. When a venue emits an event, Felix normalizes it into a single schema and forwards it to your registered webhook URL. This means your agent can listen to one format even if it trades across five market types.

Without normalization, your agent would need a separate parser for each venue's JSON format. One venue might use snake_case, another might use camelCase, and a third might wrap events in nested arrays. Felix flattens these differences so your handler does not need to know which venue produced the event.

Safety is built into the routing layer. Felix does not give the agent unlimited power. The agent operates under scoped API keys with budget caps, position limits, and an owner-approved withdrawal list. The webhook can wake the agent, but the agent can only spend what the owner already allowed. It cannot withdraw funds to itself, and it cannot exceed the hard limits set at key creation.

If a webhook arrives that would cause the agent to breach its limits, Felix blocks the order before it reaches the venue. This is not a suggestion. It is a hard stop enforced by the infrastructure. The owner also retains a panic switch that flattens positions and revokes the key. Even if a webhook stream is noisy or malicious, the owner can cut the connection instantly.

Because Felix is non-custodial, your funds remain in a wallet you control. The webhook is just a notification layer. It does not move money on its own. The actual settlement still requires your authorization boundaries. This design is covered in more detail in how to build a practical security checklist for AI trading agents.

How do you build a simple webhook handler?

You need a public URL where Felix can send HTTP POST requests. This can be a cloud function, a small server, or a tunnel during local development. The URL does not need to be a fancy domain. A static IP with a path, or a serverless endpoint, is sufficient. What matters is that it is reachable from the internet and serves over HTTPS.

Your handler receives the payload, verifies it, and decides what to do. The exact request schema is in the docs; the shape looks like this.

def handle_event(payload, headers, YOUR_SECRET):
    # verify the webhook signature using your shared secret
    if not verify_signature(headers, payload, YOUR_SECRET):
        return "unauthorized", 401

    # avoid processing the same event twice
    if already_seen(payload["event_id"]):
        return "duplicate", 200

    # enforce the owner-configured spend cap
    if not within_spend_cap(payload["usd_amount"]):
        return "blocked", 403

    # forward to the Felix order API if all checks pass
    return "accepted", 200

This handler does three things that every webhook path should do. It verifies the signature so a random HTTP request cannot trigger trades. It checks for duplicate event IDs so a retried webhook does not create two orders. It enforces the spend cap so a sudden price spike does not blow the budget. These patterns are the same whether you use Claude, Cursor, or a plain Python script triggered by the run trading agent from an AI code editor checklist.

What safety checks belong in every webhook path?

Every webhook handler should verify authenticity first. Felix signs webhooks with a secret key that only you and Felix know. Your handler must validate that signature before reading the payload. If the signature is wrong, the handler should return an error and do nothing else.

Next, check idempotency. Networks are unreliable. Felix may retry a webhook if the first attempt times out. Your handler should track event IDs and ignore duplicates. Trading the same signal twice can double your position or reverse it unintentionally.

Then, validate the payload against your guardrails. Does the proposed order size fit inside the daily budget cap? Does the resulting position stay within the position limit? Does the asset match the whitelist you configured? If any answer is no, the handler should log the event and exit without calling the trading API.

You should also include a circuit breaker. If webhooks arrive faster than your agent can safely process them, or if multiple errors occur in a row, the handler should pause and alert you. This prevents a feedback loop where a bug triggers a storm of orders. Building these controls from scratch is discussed in how to build risk controls for an AI trading agent from scratch.

Finally, log everything. Store the timestamp, the raw payload, the signature result, the guardrail decision, and any order ID returned. This creates an audit trail that you can review without relying on the venue's own records. If something goes wrong, logs let you replay the event and fix the logic without guessing.

How do you test webhook automation before risking real money?

You should never point a live webhook at a handler that has not been tested. Felix provides paper trading so you can send real-looking events to your agent without touching real capital. The agent receives the same payload format, makes the same decisions, and places the same logical orders, but the orders execute against simulated markets.

Start with a small set of events. Send one price threshold webhook and confirm the handler places the expected paper order. Send the same webhook again and confirm the idempotency check blocks the duplicate. Trigger a margin alert and confirm the handler reduces the simulated position.

Once the logic is stable, add hard limits. Set a budget cap that is intentionally low and try to trigger an order that exceeds it. The system should refuse the order. This confirms that your webhook handler and the Felix infrastructure agree on the boundary. Only after these tests pass should you authorize a live key.

When you switch to live, start with a very small budget cap and a narrow whitelist of symbols. Let the agent run for a day or two with real money but minimal exposure. This confirms that the live venue latency and the paper venue latency are similar enough for your strategy. The full process for doing this with hard limits is outlined in how to paper trade an AI agent with hard limits it cannot cross.

Remember that paper trading proves your plumbing, not your profitability. A strategy can pass every paper test and still lose money in live markets because of slippage, liquidity gaps, or model error. Trading can lose money, including everything, so treat passing tests as a prerequisite, not a guarantee.

Frequently asked questions

Do I need a dedicated server to receive webhooks?

No. You can use a serverless function, a tunneling service for local development, or a lightweight VPS. The only requirement is a public HTTPS URL that Felix can reach. During development, tunnels let you test handlers on your own machine before deploying to the cloud.

Can a webhook trigger an order instantly?

Yes, but your handler should still run safety checks first. A webhook delivers the event instantly, yet the agent should verify the signature, check idempotency, and confirm budget caps before calling the order API. Speed matters, but safety comes first.

What happens if my webhook handler is offline?

Felix retries failed deliveries with a backoff. If your handler is down for an extended period, events may queue briefly, but they are not held indefinitely. Critical events like margin alerts should also have fallback logic, such as a kill switch, because a delayed response can be costly.

How do I know a webhook is really from Felix?

Every webhook is signed with a secret key you configure. Your handler must validate the signature using that secret. If validation fails, discard the payload. Never trust a webhook based on the sender IP alone, because IP addresses can be spoofed or changed.

Can I use webhooks with an AI code editor like Claude or Cursor?

Yes. If your agent runs inside an AI editor, you can still receive webhooks by routing them to a small local handler that forwards the event to the editor via MCP, or by using a cloud relay that the editor polls. The same handler logic applies whether the agent is a local script or a persistent server.

Give your agent a key.

One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.

Keep reading

Not a brokerage, exchange, or investment adviser. Not investment advice. Trading involves risk, including total loss.