Join the Hanzo beta and get 20% off any paid plan

How to Build an AI Trading Bot That Doesn't Blow Up Your Portfolio

Most DIY trading bots fail because people automate order execution before they automate research and risk checks. Here is how to split the job across specialized AI agents, deterministic risk code, and read-only broker APIs with Hanzo.

On this page

Most people build their first trading bot backwards.

They spend a weekend wiring a brokerage API to a moving-average crossover, hook up a language model to "read the news," flip it onto a live account, and watch fees, slippage, and a single bad week chew through their balance. Then they decide automated trading is a scam and go back to checking tickers on their phone at midnight.

The mistake isn't using automation. The mistake is automating the scariest part first (placing live trades) while leaving the highest-leverage work (reading filings, tracking portfolio drift, checking concentration risk, and testing ideas honestly) completely manual.

If you invert the order—starting with read-only research and portfolio monitoring, enforcing risk rules in plain deterministic code, and only touching order execution after months of paper trading—an AI trading stack starts to look a lot more like a real institutional desk and a lot less like a casino script.

Here is how to build one with Hanzo, what belongs inside an AI agent versus hard-coded guardrails, and the exact prompts to get a working version running today.

Try It Now · Opens Prefilled in Hanzo App

Start with a read-only portfolio audit (no broker keys required)

Click any button below to open Hanzo with the prompt already loaded. Paste a CSV or summary of your holdings, or start designing a paper-trading strategy from scratch.


Why a Single "Trading Bot" Prompt Usually Fails

Traditional bots are rigid: buy when the 50-day crosses the 200-day, sell at a fixed stop. They do what they're told, right up until the market regime changes and the rule stops working.

Throwing one giant LLM prompt at the whole problem breaks in the opposite direction. Ask a single model to read earnings headlines, evaluate a chart, decide position size, check risk, and place an order, and you get an opaque black box that is remarkably good at talking itself into bad trades.

The fix is the same separation of duties real funds use: split the workflow into narrow roles, and draw a hard line between judgment (where LLMs shine) and enforcement (where only deterministic code belongs).

The 6-role split that actually holds up

  1. Market Analyst (LLM + web/data tools): Reads 10-Ks, earnings transcripts, macro releases, and price anomalies for your watchlist, then writes a one-page brief on what actually changed—not a wall of recycled headlines.
  2. Quant Researcher (LLM + code execution): Turns loose hypotheses into runnable backtests. Compares strategies on Sharpe, max drawdown, turnover, fees, and out-of-sample stability rather than cherry-picked peak returns.
  3. Portfolio Manager (LLM + read-only positions): Watches your actual weights against your target allocation, spots creeping single-sector or single-stock concentration, and drafts rebalance candidates when drift crosses your threshold.
  4. Risk Gate (deterministic code—never just an LLM): Runs before any order ever reaches a broker. Checks hard position caps, daily loss limits, cash buffers, allowed symbols, and market hours. If a rule trips, the order is rejected. No prompt can persuade an if statement.
  5. Execution Layer (broker API + human approval): Formats approved tickets and routes them to a paper or live broker API. You decide what requires an explicit click to approve and what—if anything—can run unattended inside tight caps.
  6. Post-Trade Reviewer (scheduled report): Compares fills against expected prices, tallies commissions and slippage, benchmarks performance against simply holding an index, and surfaces which rules are quietly bleeding money.
A dark-mode engineering and trading workstation with clean monochrome market trend charts, allocation bars, and dark code panes under warm ambient lighting.
Splitting research, backtesting, portfolio drift, and deterministic risk checks into separate components makes every decision inspectable—and easy to turn off.

Start With Portfolio Automation, Not Day Trading

If you hold positions for months or years rather than minutes, you don't need sub-second order routing. You need consistency.

Most individual investors know they should review concentration risk, track what they're paying in fees, notice when one winning position quietly swells to 35% of their net worth, and read quarterly filings before earnings week. Almost nobody does it every week because it takes hours of spreadsheet drudgery.

Connect a read-only brokerage feed or export your positions, and an agent can answer the questions that actually protect your capital:

  • Which three holdings account for most of my portfolio's volatility right now?
  • How far has each position drifted from my target weights, and what is the cheapest rebalance path?
  • Where do I have hidden overlap (for example, holding an index ETF plus five of its top ten components)?
  • Which upcoming earnings calls or macro announcements affect what I actually own?
  • How much did commissions, spreads, and turnover cost me over the last 90 days?

Schedule that as a weekday morning brief or a Sunday rebalance memo, and you've already captured 80% of the practical value of an AI trading system with zero risk of a runaway order.

An investor seated in a quiet dark-mode architectural interior at dawn reviewing a minimalist morning portfolio briefing on a laptop with a black espresso cup.
A read-only morning briefing—tracking drift, catalysts, and realized fees—gives you most of the edge of automation before a single automated order is ever enabled.

Mapping the Stack to Hanzo

Building a custom trading workflow used to mean gluing together model providers, cron servers, secret managers, charting frontends, and glue scripts across five different accounts. Inside Hanzo, each layer maps cleanly to one tool:

What you needHanzo toolPractical role in the system
Ad-hoc research & thesis stress-testingHanzo ChatSummarize filings, interrogate strategy assumptions, and draft rules
Reusable specialist personasHanzo AgentSave dedicated Market Analyst, Quant, and Portfolio Reviewer instructions
Market data & broker tool connectionsHanzo MCPExpose read-only portfolio endpoints, price feeds, or paper-trading APIs as typed tools
Multi-step pipelinesHanzo FlowChain Data Fetch → Research → Drift Check → Risk Gate → Approval Notification
Scheduled 24/7 briefings & alertsHanzo BotRun recurring market checks, crypto alerts, and weekly performance reviews automatically
Custom UIs & backtest runnersHanzo DevScaffold and deploy your own portfolio dashboard, risk engine, and backtest scripts

You don't need to wire up all six on day one. Most people start with a single prompt in Hanzo Chat, turn the parts they reuse every week into a Hanzo Agent, and only bring in Hanzo Dev or Hanzo Bot once they know what signals they actually care about.


Connecting Real Market Data and Broker APIs

An agent without live data is just guessing from stale training weights. With Model Context Protocol (MCP) tool integrations, you can give your agents tightly scoped access to external market-data and brokerage APIs—without ever pasting API keys into chat prompts.

Two popular starting points for developers:

  • Alpaca: Clean REST and MCP tooling for equities and crypto market data, positions, and order execution—plus a built-in paper-trading account so you can test the entire pipeline with simulated money first.
  • Interactive Brokers: Deep multi-asset market data, portfolio reporting, and API execution with AI integration tooling for eligible accounts.

(Neither brokerage is pre-wired inside Hanzo out of the box—you connect your own authorized credentials and control the exact scopes, starting read-only.)


A Practical 5-Step Build Plan (That Won't Burn You)

If you want to build something real this week instead of endlessly tweaking prompts, follow this order:

1. Pick one narrow job

Don't build "an AI hedge fund." Pick one concrete output: a daily risk brief on ten stocks, a weekly crypto rebalance check, or a Python backtester for one specific mean-reversion rule.

2. Write the architecture and rules before touching an API

Define the exact data flow up front:

Market Data / Positions
  → Research & Signal Agent (LLM)
    → Deterministic Risk Engine (Code: caps, max loss, allowlist)
      → Human Approval Gate
        → Broker API (Paper first)
          → Post-Trade Attribution Log
Blueprint Prompt · Hanzo Chat

Generate your agent specs and deterministic risk rules

"Design a modular trading workflow with separate Market Analyst, Quant, Portfolio Manager, deterministic Risk Gate (in Python/TypeScript code), and Human-Approved Execution layers..."

3. Connect read-only data first

Wire up a read-only brokerage key or CSV export. Run your research and portfolio-drift prompts for two weeks. Fix every noisy alert and vague summary until the output is something you actually read every morning.

4. Backtest with brutal honesty

When you test a trading rule on historical data, assume worse fills than you hope for. Include commissions, realistic bid-ask spread, slippage, and a holdout period the strategy never saw during tuning. If a strategy only looks good with zero fees and perfect fills, it isn't a strategy.

5. Paper trade, then automate in tiny increments

Run the full loop on a paper account with every proposed trade logged alongside the reason it was generated and the risk checks it passed. If you eventually move to live execution, keep hard position limits, a daily loss circuit breaker, and an independent kill switch in deterministic code—never inside a prompt.


What AI Can and Cannot Do in Markets

It is worth being blunt about the limits: no language model can reliably predict tomorrow's prices, and no custom bot guarantees profits. Markets are noisy, adversarial, and happy to punish overfitted strategies—including ones built by billion-dollar quant shops.

What a well-engineered agentic stack does give you is process discipline. It reads the filings you didn't have time to open, flags the concentration risk you didn't notice creeping up, runs the backtest with fees included instead of letting you trade on a hunch, and keeps a clean audit trail of every decision you made and why.

You can start experimenting on a free Hanzo account—just keep in mind that external market-data feeds, brokerage APIs, hosting, and higher model usage carry their own costs as you scale.

Build Your Own · Free in Hanzo App

Ready to build your first portfolio or trading agent?

Open Hanzo Chat to architect your workflow step by step, or jump straight into Hanzo Dev to scaffold a paper-trading bot and custom dashboard.

Disclaimer: This article is for informational and educational purposes only and is not financial or investment advice. Trading stocks, options, and cryptocurrencies carries substantial risk of loss. Automated systems can lose money rapidly; always maintain independent deterministic risk limits, regulatory compliance, and human oversight.

Comments

Sign in with your Hanzo ID to comment.

Loading comments…

Read more