How an AI agent trades perpetual futures step by step
An AI agent trading perpetual futures evaluates margin, sizing, and funding through scoped keys and non-custodial controls before it sends any order.
- 01The agent trades perpetual futures through a non-custodial pipeline where the owner controls the wallet and the API enforces scoped permissions.
- 02Orders are sized in plain US dollars, and the API normalizes all venue-specific contract math, margin requirements, and funding rates.
- 03Hard limits on budget, position size, and drawdown are enforced server-side so the agent cannot override them.
- 04A kill switch can flatten positions and revoke the API key instantly, operating outside the agent's logic.
- 05Trading perpetual futures with leverage carries real risk of loss, including total loss of margin, and the architecture limits unauthorized actions but does not prevent market losses.
An AI agent trading perpetual futures follows a strict pipeline: it reads normalized market data, checks margin and funding requirements against owner-defined limits, sizes the order in US dollars, and routes it through a non-custodial key that cannot withdraw funds. Every step runs through scoped permissions, budget caps, and a kill switch that can flatten positions and revoke access instantly. The architecture is designed so the agent can open and manage leveraged exposure without ever controlling the underlying wallet, because leverage amplifies both opportunity and risk.
What does an AI agent need before it can trade perpetual futures?
Before the agent evaluates a single price, the owner establishes the boundary conditions. The owner creates a self-custodial wallet, deposits collateral, and connects it to the Felix API. This wallet remains under the owner’s exclusive control. The API never holds the private key, and the agent cannot withdraw funds to any address the owner has not explicitly pre-approved. This non-custodial structure is especially important for perpetual futures, where leveraged positions can grow large quickly and the cost of unauthorized access would be severe.
Next, the owner generates a scoped API key. This key is not a universal password. It carries explicit permissions, such as the right to place orders on a perps venue, paired with explicit prohibitions, such as the inability to withdraw funds, change account settings, or trade on other market types. The owner also attaches a budget cap, a maximum position limit, and sometimes a maximum drawdown threshold. These constraints are enforced server-side, so the agent cannot negotiate, reason, or prompt-engineer its way around them. How a single API keeps an AI trading agent safe inside a code editor
The agent itself is configured with a prompt and a set of tools. If the developer uses an MCP client, the agent receives structured tools for reading market data and placing orders. If the developer uses the REST API directly, the agent makes HTTP requests and parses JSON responses. In both cases, the agent only receives the scoped key. It never sees the wallet seed or the owner’s main credentials. The owner can start in paper trading mode to test the agent’s logic under simulated conditions, but live trading requires an explicit authorization step that swaps the paper key for a real-money key. This prevents an accidental switch from test to production and ensures the owner consciously accepts the risk of real collateral.
How does the agent evaluate margin and position sizing?
Perpetual futures are leveraged contracts. The agent does not need to post the full notional value of a position, but it must post enough collateral to satisfy the venue’s margin requirements. The Felix API normalizes margin math across venues, so the agent receives a clear, unified requirement: to open a position of a certain dollar size, a specific amount of collateral must be available and reserved.
The API typically exposes two margin figures to the agent. The initial margin is the collateral required to open a new position. The maintenance margin is the minimum collateral required to keep the position open. If the account balance drops below the maintenance margin due to adverse price movement, the position enters liquidation territory. The agent reads both figures and factors them into its sizing logic.
The agent sizes orders in plain US dollars. This is a deliberate abstraction. Instead of calculating contract sizes, tick values, notional adjustments, and minimum lot sizes for each venue, the agent states its intent in dollars. The API translates that intent into the correct number of contracts or units for the specific perps venue. This removes an entire category of sizing errors that arise when agents attempt venue-specific math inside their prompts or reasoning loops.
The agent still needs to respect the owner’s hard limits. Suppose the owner sets a maximum position size of five thousand dollars and a maximum account leverage of three times. The agent checks the proposed notional value against both limits before it sends an order. If the new trade would breach either limit, the API rejects the request and returns an error. The agent can then log the failure and wait for the next signal. How autonomous trading systems enforce hard limits the agent cannot cross
It is important to state plainly that perpetual futures can lose money rapidly, including more than the initial margin if the position is highly leveraged and the market moves quickly. The architecture does not prevent market losses. It prevents unauthorized actions. The owner should set limits that assume the position can go to zero, because leveraged trading can result in the complete loss of the allocated margin.
How does the agent place and manage an order?
When the agent decides to trade, it constructs an order intent. The exact request schema is in the docs; the shape looks like this:
{
"market": "perp",
"side": "buy",
"dollar_size": 1200,
"time_in_force": "gtc",
"api_key": "YOUR_KEY"
}The API receives the request, validates the key permissions, checks the budget cap, verifies that the wallet has sufficient margin for the requested dollar size, and confirms that the new position would not violate the owner’s leverage or position limits. If all checks pass, the API routes the order to the perps venue. The venue returns a fill or a resting order identifier, and the API normalizes the response into a standard format. The agent receives confirmation of the fill price, the dollar value, and the resulting position state.
The agent does not need to manage low-level connection logic, websocket heartbeats, or venue-specific authentication handshakes. The API handles retries, idempotency keys, and error normalization. If the venue is temporarily unreachable or returns a rate limit, the API surfaces a clear error code rather than an ambiguous timeout. The agent can then decide whether to retry, to wait, or to halt entirely.
After the order is live, the agent tracks the position through normalized position objects. These objects show the entry price, the current mark price, the unrealized profit or loss in dollars, the liquidation price, and the funding rate being applied. The agent uses this data to evaluate whether to hold, add, or reduce the position. Because the API presents all venues in the same shape, the agent can manage positions on different perps venues without rewriting its core logic. How trading APIs let AI agents trade across markets
What happens while the position is open?
A perpetual future does not expire, but it is not a passive holding. The position accrues funding payments at regular intervals, typically every few hours. If the agent holds a long position and the funding rate is positive, the agent pays a small percentage of the notional value to the short side. If the funding rate is negative, the agent receives payment. The API surfaces the current funding rate, the predicted funding rate, and the next funding time, so the agent can factor this carrying cost into its decision making.
The agent also monitors the mark price, which is the venue’s estimate of fair value used for margin calculations and unrealized profit and loss. The mark price can differ from the last traded price or the index price. If the mark price moves against the position, the unrealized loss grows and the available margin shrinks. If the margin balance drops below the maintenance margin requirement, the position approaches liquidation. The API sends streaming updates on margin health, and the owner can set alerts or automatic reductions well before liquidation becomes likely.
During this phase, the kill switch remains armed and active. If the owner triggers it, the API immediately sends flattening orders to close the position, cancels all open orders, and revokes the API key. The agent cannot override this command because the revocation happens at the API layer, below the agent’s reasoning. This is a critical architectural choice. Safety is enforced outside the agent’s logic, so a bug, a bad prompt, or a compromised model cannot disable the protections.
How does the agent close or reduce a position safely?
Closing a position is not conceptually different from opening one, but the risk profile changes. When the agent submits a reduce-only order, the API ensures that the order cannot accidentally flip the position to the opposite side unless the owner has explicitly allowed directional changes in the scoped permissions. A reduce-only sell on a long position can only decrease the long size, not create a new short.
The agent may also scale out gradually. Suppose the agent decides to reduce a position by half. It sends a dollar-sized reduce order. The API translates the dollar value into the correct number of contracts and submits the partial close. The released margin returns to the wallet and becomes available for new positions or owner withdrawals. The agent sees the updated position size and remaining margin in the next data cycle.
The owner should define exit conditions in advance. These can be time-based, price-based, or drawdown-based. The agent evaluates these conditions against the normalized position data. If the condition is met, the agent sends the exit order. Because the API enforces the same budget and permission checks on exit orders as on entry orders, the agent cannot accidentally exit into a larger position or trigger an unauthorized withdrawal. The funds remain in the owner-controlled wallet. How to build a trading agent that handles real money safely
What safety checks run continuously in the background?
Several enforcement layers operate continuously, independent of the agent’s reasoning cycle. The first layer is the scoped key. Every request is authenticated and checked against the key’s permissions. If the key is allowed to trade perps but not options or stocks, any request outside the scope is rejected immediately.
The second layer is the budget cap. The API tracks the total dollar value of orders and open positions attributed to the key. If the agent attempts to place an order that would exceed the cap, the request is rejected. This is a hard ceiling, not a warning or a suggestion.
The third layer is the drawdown and position limit. The owner can set a maximum single-position size and a maximum portfolio drawdown percentage. The API evaluates these against real-time position data. If a sudden price move pushes the account beyond the drawdown limit, the API can trigger a preconfigured exit plan or alert the owner, depending on the settings chosen during setup.
The fourth layer is the non-custodial architecture itself. The API can spend within limits, but it cannot move funds to an unapproved address. Even if the agent were compromised or the model were jailbroken, the attacker could only trade within the scoped permissions and budget. They could not drain the wallet or transfer funds elsewhere. This design is enforced by the wallet structure and smart contract logic, not by policy or trust.
Frequently asked questions
No. Scoped keys are created by the owner and enforced server-side. The agent cannot escalate its own privileges, modify withdrawal addresses, or remove the kill switch. It operates inside a boundary it cannot edit.
The API reflects updated margin requirements in the normalized data feed. If the new requirements exceed the available collateral, the agent receives an error on any new order. Existing positions may face liquidation risk, which is why continuous monitoring and pre-set exit plans are essential.
The agent receives funding rate data and can factor it into decisions, but the actual payment is handled by the venue and deducted from or credited to the wallet balance automatically. The agent does not need to send a separate transaction for funding.
Yes, but the owner should be aware that manual trades affect the same margin balance and position limits. The API sees the total account state, so manual and agent activity share the same budget cap and risk thresholds.
Paper trading uses simulated balances and venues. The agent logic and API routing are identical, but no real money moves. Live trading requires explicit owner activation of a real-money key, and all orders affect actual collateral and carry real risk of loss.
The kill switch revokes the API key and sends flattening orders immediately. The exact time to full closure depends on market conditions and venue latency, but the command itself is issued instantly and cannot be blocked or delayed by the agent.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
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.
Running more than one trading agent introduces collision and correlation risks that a single agent cannot create. Hard limits enforced outside the agent's reasoning loop are the only reliable way to bound those risks.