Agentic tradingCryptoDevelopersRisk management

How to build a crypto trading agent step by step

A developer guide to building an AI agent for crypto trading with non-custodial APIs, scoped keys, and hard safety limits before live deployment.

By the Felix team10 min read
Key takeaways
  • 01An agentic trading API abstracts venue complexity so developers can send normalized US dollar orders without managing venue-specific contracts or connectors.
  • 02Non-custodial infrastructure keeps owner funds in a controlled wallet while scoped keys let agents trade within hard limits they cannot override.
  • 03Prompts and strategy logic should separate decision-making from position sizing, with API-level caps enforcing the actual boundaries.
  • 04Paper trading must mirror live behavior closely before owner authorization, and live deployment should start with a small, losable budget.
  • 05Continuous monitoring, a kill switch, and periodic reviews are required operational practices, not optional extras, for autonomous crypto trading.

Developers building AI agents for crypto trading need a clear path from idea to execution. The process involves choosing an API that abstracts venue complexity, defining the agent's decision logic, and wrapping it in hard safety limits before any real money is deployed. This walkthrough covers each step in order, from setup through live trading, with an emphasis on risk controls that protect owner funds. By the end, you should understand how to connect an agent to markets, constrain its behavior, and operate it with the same rigor you apply to any production system.

What does an agent need before it trades crypto?

Before writing code, define the agent's scope. Decide whether it will trade spot crypto, perpetual futures, or both, because each product type has different margin and collateral rules. Spot trades require available balance, while perpetual futures involve leverage and funding rates that can erode a position over time. Choose a non-custodial API so the owner retains wallet control while the agent receives only scoped spending authority. The API should normalize order sizing in plain US dollars so the agent does not need to handle venue-specific contract decimals, lot sizes, or notional math.

Next, set up the data and technical stack. The agent needs clean, timely market data to make decisions. If the API provides normalized prices and order books, the agent can consume a single format rather than building separate parsers for each venue. Developers should also choose a programming language and framework that fits the strategy latency. Python is common for quantitative work, while TypeScript may integrate better into existing web services. The critical requirement is that the agent can decide and act within a timeframe relevant to its strategy, whether that is minutes or days.

Document the agent's intended behavior before testing. Write down the strategy thesis, the expected holding period, the target markets, and the conditions under which the agent should stop trading. This documentation becomes the baseline against which you measure live performance. It also helps the owner configure appropriate safety limits, because the owner and the developer must agree on the maximum risk tolerance before the agent receives a key. Paper trading must be available for testing every logic branch without risking capital. Only after the agent behaves predictably in simulation should the owner authorize a live key.

How do you connect the agent to markets?

Connection architecture matters for reliability. An agentic trading API sits between the agent and the underlying crypto venues, translating the agent's intent into venue-specific instructions. The developer does not need to manage venue APIs, websocket feeds, order type mappings, or retry logic directly. The agent sends a standardized request, and the infrastructure handles routing, signing, and execution. This abstraction layer is what makes it practical for an AI agent to trade multiple instruments without understanding the operational details of each venue.

For developers using MCP, the agent discovers trading tools through the MCP server. It calls functions to check balances, place orders, or read positions, just like it would call any other tool. The model receives schema definitions for each tool and decides when to invoke them based on the conversation context. For standalone services, the REST API offers the same capabilities over HTTPS. In both cases, authentication uses a scoped key that carries explicit permissions. The exact request schema is in the docs; the shape looks like this:

curl -X POST https://api.felix.trade/v1/order \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "market": "BTC",
    "side": "buy",
    "usd_amount": 100.00,
    "type": "market"
  }'

This example is purely illustrative. The agent never holds withdrawal rights. The key can spend within a budget but cannot move funds to an external address. That permission model is enforced by the infrastructure, not by the agent's own code. Developers should still validate inputs before sending them, but the safety net exists at the API level so that a single bug does not lead to catastrophic loss. The agent must also handle errors gracefully. Network issues, rate limits, and venue downtime are normal in crypto markets. A robust agent retries transient errors conservatively and halts on persistent failures, using clear API error codes to branch its logic.

How should the agent decide what to trade?

Decision logic can range from simple rules to model-driven signals. The developer's job is to express that logic in a format the agent can execute consistently. A rule-based agent might check a moving average crossover and submit a trade when conditions align. A more complex agent might ingest on-chain data, funding rate differentials, or sentiment feeds, then rank opportunities by expected risk-adjusted return. Whatever the source, the agent must translate its conclusion into a concrete order structure: market, side, and US dollar size. Ambiguity at this stage leads to errors at execution.

Prompt design deserves attention. If the agent is LLM-driven, the prompt should include the current portfolio state, recent price action, and a strict set of disallowed actions. The prompt must also repeat the safety context on every turn so the model does not forget its constraints. How to design prompts for a trading agent covers this in detail. The key principle is that the prompt is a control surface, not just a request for ideas. Every prompt should state the maximum position size, the allowed markets, and the conditions under which the agent must stop trading.

State management is equally important. The agent needs to know its current positions before making new decisions. If the agent believes it is flat but the API shows an open position, the next trade could double exposure unintentionally. Query the API for positions before every decision, or maintain a local state that is reconciled against the API after every action. The latter is faster but requires careful handling of network failures. Developers should also avoid letting the agent invent position sizes dynamically unless those sizes are bounded by hardcoded limits in the API layer. The agent can suggest a direction, but the infrastructure should cap the notional exposure. This separation of strategy and risk enforcement prevents a confused model or a bug from allocating too much capital to one trade. If the agent uses quantitative signals, backtest the logic on historical data, but treat backtests as sanity checks rather than profit guarantees. Past patterns do not predict future results.

How do you keep the agent within safe limits?

Safety is not an afterthought. It is the foundation that makes autonomous trading viable. Felix uses a non-custodial model where owner funds remain in a wallet the owner controls. The agent receives a scoped key with budget caps, position limits, and an approved set of markets. Even if the agent is compromised or hallucinates a trade, it cannot exceed these boundaries. The owner should set the limits, not the developer. The developer implements the strategy, but the owner configures the maximum risk parameters. This separation of duties prevents conflicts of interest and ensures the owner understands the worst-case loss. How to control risk when an AI agent trades through MCP explains the mechanics.

  • ·Spend caps define the maximum US dollars the agent can deploy in a given period.
  • ·Drawdown limits can trigger automatic flattening if the portfolio loses a preset amount.
  • ·Position limits restrict concentration in any single token or contract.
  • ·Exit plans, such as stop orders or time-based exits, can be attached to every entry so the agent does not need to monitor trades continuously.
  • ·A panic or kill switch revokes the key and flattens all positions immediately if the owner intervenes.

These controls are infrastructure-level, not suggestions. The agent may request a trade, but the API evaluates it against the owner-configured rules before submission to a venue. If the request violates a limit, it is rejected. The agent receives the error and must adjust. This loop keeps the owner in control while allowing the agent to act autonomously within its lane. How position sizing protects owner funds from agent error describes why sizing is the most important variable to constrain.

What does going live actually look like?

Transitioning from paper to live trading is a deliberate event, not a configuration toggle. The owner generates a live key, sets its specific budget and permissions, and authorizes it explicitly. The developer then swaps the paper key for the live key in the agent's environment. The agent's logic should remain identical; only the execution environment changes. Do not change the strategy at the same time you go live, because you will not know whether anomalies are caused by market reality or by the new logic.

Start with a small budget that you can afford to lose entirely. Trading can lose money, including everything, and crypto markets are volatile. Observe the agent's first few trades closely. Verify that order sizes match the intended US dollar amounts, that positions appear as expected, and that the agent respects the deny list and caps. Do not increase the budget until the agent has demonstrated stable behavior across different market conditions, including sharp moves. It is normal for an agent to perform differently in live trading than in paper mode due to slippage, latency, and partial fills. Account for these frictions in your sizing and exit rules.

It is useful to maintain a shadow paper instance running alongside the live agent for a short period. Compare the signals and intended actions between the two environments. Discrepancies reveal timing issues, data feed differences, or state management bugs. Fix those in code before scaling up. One advantage of an agent is that it removes emotional decision-making from trading. However, the owner must resist the urge to override the agent constantly. Interventions should be reserved for safety breaches or fundamental strategy flaws, not for normal drawdowns. If the owner overrides the agent every time a trade loses money, the agent cannot execute its edge over time. Trust the safety controls and let the agent operate within them.

How do you monitor and shut down an agent?

Continuous monitoring is essential because markets change and models degrade. The developer should build or use a dashboard that tracks open positions, recent fills, remaining budget, and current drawdown. Alerts should fire when the agent approaches a limit or when a kill switch is triggered. The owner must be able to review logs without needing to parse venue-specific formats. Good telemetry includes not just what the agent did, but what it considered and rejected, because rejected orders reveal how safety controls are functioning.

Store logs in a durable, queryable system. Include timestamps, market conditions, agent reasoning, API responses, and any errors. These logs are essential for post-trade analysis and dispute resolution. Even in a non-custodial setup, a clear audit trail protects both the developer and the owner. Review logs regularly to detect drift in the agent's behavior or subtle changes in market structure that the strategy no longer handles well.

The kill switch is the final safeguard. If the agent enters an unexpected loop, chases losses, or encounters a market event it cannot handle, the owner flattens all positions and revokes the key. This is a one-click or one-call operation. After shutdown, the developer reviews the trade history to determine whether the issue was a market anomaly, a logic bug, or a prompt failure. Only then should the agent be restarted, usually with adjusted parameters or additional constraints. Never restart immediately out of frustration without understanding the root cause.

Long-term maintenance includes refreshing API keys on a schedule, updating prompts to reflect new market structures, and re-evaluating the risk settings as the portfolio grows. Autonomous trading is not a deploy-and-forget system. It requires the same operational discipline as any production service. Schedule regular reviews of the agent's performance against its documented baseline, and be willing to reduce scope or budget if the edge you assumed disappears.

Frequently asked questions

Does the agent need its own crypto wallet?

No. The owner controls the wallet. The agent receives a scoped key that can trade but cannot withdraw funds or change owner-approved withdrawal addresses.

Can I test my agent without risking real money?

Yes. Paper trading lets the agent execute against live market data without using real capital. Test every strategy branch and error path before authorizing a live key.

What happens if the agent tries to exceed its budget?

The API rejects the order. The agent receives an error response and must adjust its request. The infrastructure enforces the limit, so the agent cannot override it.

How much coding knowledge do I need to build this?

You need enough skill to integrate an API or MCP tools and to express your strategy in code or structured prompts. You do not need to write low-level venue connectors or manage private key cryptography.

Is crypto trading with an agent guaranteed to profit?

No. Trading can lose money, including the full budget you allocate. The safety controls limit losses to the scoped amount, but they do not prevent losses within that scope.

Can I use the same agent for stocks and crypto?

Yes. The Felix API unifies stocks, crypto, perps, options, and prediction markets under one key and one interface. You can expand the agent's scope by adjusting its key permissions and prompts.

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.