Build a Safer AI Trading Execution Bot
Set up a local, confirmation gated exchange connection with secure API controls, order verification, trade logging, and a reviewed learning system.
Download the complete trading bot setup guide
Build a Safer AI Trading Execution Bot
Connect an AI coding agent to an exchange, verify execution, and create a durable trade memory system.
What you will achieve
You will have a locally managed trading execution layer that can read exchange data, submit explicitly approved orders, and record each trade, its rationale, outcome, and lessons.
Who this is for
Traders and investors who want to automate execution without writing the integration from scratch. Basic familiarity with exchange accounts and trading risk is helpful.
Difficulty: Intermediate
Short tutorial
Connect an AI coding agent to an exchange, verify execution, and create a durable trade memory system.
Guide: Build a Safer AI Trading Execution Bot with Claude Code or Codex
Time: 45 to 90 minutes
What you will build
This tutorial creates the execution layer of an AI trading bot. Claude Code or Codex acts as the reasoning interface, an exchange supplied MCP server connects it to your account, and the exchange handles order execution.
You will also build a local memory system containing your strategy context, operating instructions, trade ledger, and reviewed lessons.
This is not a ready made profitable strategy. Begin with paper trading or an isolated subaccount, require confirmation before every live order, and test each component separately.
System architecture
| Component | Responsibility |
|---|---|
| Claude Code or Codex | Interprets instructions, reads local context, and calls available tools |
| Exchange MCP server | Relays requests and account data between the agent and exchange |
| Exchange account | Holds balances and executes orders |
| Local trading folder | Stores strategy context, instructions, ledger, and lessons |
| Telegram, optional | Provides remote access while the host machine remains online |
1. Prepare the account and local environment
You need:
- Claude Code with a suitable Claude subscription, or Codex with a suitable ChatGPT subscription
- Node installed on the computer, if required by the exchange MCP
- An exchange account with an official, native MCP integration
- Two factor authentication enabled
- A paper trading account or isolated subaccount for initial testing
- A terminal session with access to a local project folder
Use a subaccount if you already have discretionary positions. This prevents an experimental agent from interacting with your primary positions.
API security checklist
Create a system generated API key in the exchange API management area. Configure it as follows:
- Enable account reading and trading permissions
- Disable withdrawals
- Do not enable permissions the bot does not need
- Copy the secret immediately, since it may be displayed only once
- Store credentials locally, not in the strategy or memory documents
- Never commit credentials to version control
- Replace the key if it is exposed
2. Give the coding agent a controlled setup brief
Open Claude Code or Codex inside an empty local folder. Paste the following prompt. It deliberately asks the agent to stop at security sensitive steps and to use the current official MCP instructions rather than guessing configuration commands.
You are helping me create a local AI trading execution layer. The architecture is: 1. You are the local reasoning and instruction interface. 2. The exchange supplied MCP server is the connection layer. 3. My paper trading account or isolated subaccount is the execution layer. 4. Local Markdown files contain context, instructions, trade history, and reviewed lessons. Work in small, verifiable steps. Requirements: 1. Inspect this machine and determine whether the required Node environment is installed. Explain any missing dependency before installing it. 2. Create the local folder structure specified below. 3. Help me connect the official native MCP server for my selected exchange. Use the current configuration method available in the installed MCP package or its official setup material. Do not invent commands, package names, environment variable names, or endpoints. 4. Pause when I must create an API key or enter a secret. Do not ask me to paste secrets into a normal chat message. Help me store them in the local secret mechanism required by the MCP. 5. Ensure withdrawals are not required. The key should have only account reading and trading permissions. 6. Add secret files and local MCP configuration containing credentials to .gitignore where applicable. 7. After configuration, tell me whether the client must be restarted. 8. Test read access first by requesting a current BTC price. 9. Test authenticated read access by retrieving the connected account mode and balance. 10. Do not submit an order until I provide an exact instrument, side, order type, quantity or maximum notional value, and explicit confirmation. 11. Default to paper trading or an isolated subaccount. 12. After every submitted order, update the local ledger. After a trade closes, draft a learning entry for my review. 13. Never turn one losing trade into a permanent strategy rule. Record observations and require my approval before changing strategy instructions. 14. If a step fails, diagnose the actual error, show the likely cause, and propose the smallest fix. Do not repeatedly retry an order when its status is uncertain. First, inspect the environment and create the folder structure. Then stop and show me what you created.
3. Create the trading memory system
Use this structure:
trading-bot/ ├── context.md ├── instructions.md ├── memory.md ├── strategy.md ├── ledger.md ├── learnings.md ├── reflections.md └── .gitignore
Credentials should not appear in these Markdown files.
context.md
This gives the agent personal and financial context so it does not respond with generic assumptions.
## Account purpose Account type: [paper trading or isolated subaccount] Primary assets: [assets] Trading horizon: [intraday, swing, or long term] ## Objectives Primary objective: [objective] What I am testing: [experiment] What success means: [measurable definition] ## Risk context Maximum capital allocated to this experiment: [amount] Maximum acceptable loss per trade: [amount or percentage] Maximum total exposure: [amount or percentage] Assets or products that must never be traded: [list] ## Personal constraints Times I can review trades: [times] Situations in which the bot must not trade: [conditions] Other relevant positions or constraints: [details]
instructions.md
## Operating rules 1. Treat this system as an execution assistant, not an authority to invent trades. 2. Never place a live order without explicit confirmation. 3. Before requesting confirmation, restate the instrument, direction, order type, size, maximum notional value, thesis, and invalidation. 4. If any required field is missing or ambiguous, ask for clarification. 5. Use paper trading or the designated isolated subaccount unless told otherwise. 6. Never request, enable, or use withdrawal permission. 7. If order status is uncertain, query the exchange before retrying. 8. Log every order request and exchange response in ledger.md. 9. When a trade closes, draft a plain English review in learnings.md. 10. Do not modify strategy rules because of one trade. 11. Label possible patterns as observations until they recur and receive manual approval. 12. Never claim a strategy is profitable without relevant test results.
strategy.md
The transcript uses a moving average crossover only as an example, not a recommendation. Define your own tested rules with this template:
## Strategy name [Name] ## Status [Draft, back test, forward test, paper trading, or live] ## Instrument and timeframe Instrument: [symbol] Timeframe: [timeframe] ## Entry conditions All required conditions: 1. [condition] 2. [condition] 3. [condition] ## Invalidation The trade thesis is invalid when: [objective condition] ## Exit and profit management Stop condition: [condition] Profit condition: [condition] Time based exit, if any: [condition] ## Position constraints Maximum notional value: [amount] Maximum concurrent positions: [number] Additional restrictions: [restrictions] ## Testing evidence Back test period: [period] Forward test period: [period] Known limitations: [limitations]
ledger.md
## Trade ledger | Trade ID | Opened | Closed | Account | Instrument | Side | Order type | Size | Entry | Exit | Thesis | Invalidation | Status | Result | Exchange reference | |---|---|---|---|---|---|---|---:|---:|---:|---|---|---|---:|---|
learnings.md
## Reviewed learnings ### Trade [ID] Date closed: [date and time] Outcome: [profit, loss, or flat] Original thesis: [thesis] What happened: [factual description] What execution handled well: [details] What execution handled poorly: [details] Possible observation: [observation] Evidence from similar trades: [none or references] Proposed rule change: [none or proposal] Manual review status: [pending, accepted, or rejected]
reflections.md
## Personal trade reflections ### Trade [ID], before entry Why am I entering this trade? [answer] What evidence supports it? [answer] What would prove the idea wrong? [answer] Am I following the documented strategy or acting on impulse? [answer] ### Trade [ID], after exit Did I follow the original plan? [answer] Was the result caused by strategy, execution, or normal variance? [answer] What should I observe across future trades? [answer]
4. Connect and verify the exchange MCP
Follow the exact setup process supplied by the selected exchange MCP. The transcript does not provide a universal command, so do not substitute an unverified package or command.
The usual sequence is:
- Install or register the official MCP server.
- Add its configuration to Claude Code or Codex.
- Enter the API credentials through the required local secret mechanism.
- Restart the AI client so it loads the connection.
- Confirm public market data access.
- Confirm authenticated account reading.
- Confirm that the connected account is the intended paper account or subaccount.
Public data verification prompt
Do not place or modify any order. Use the exchange MCP to retrieve the current BTC market price. Report: 1. The exact symbol queried. 2. The returned price. 3. The exchange timestamp, if available. 4. The MCP tool that supplied the result. If the tool fails, diagnose the connection without attempting a trade.
Account verification prompt
Do not place or modify any order. Verify the authenticated exchange connection. Report: 1. The connected account or subaccount identifier, without exposing secrets. 2. Whether it is paper trading or live. 3. The balances visible to the API. 4. Whether trading permission is available. 5. Whether withdrawal permission is disabled, if the API can verify this. Stop if the connected account is not the intended test account.
Compare the returned balance with the exchange interface. Do not continue if it differs unexpectedly.
5. Test execution with a controlled order
Use paper trading first. If your exchange does not support it, use an isolated subaccount with only a small amount assigned to the experiment.
Start with an order preview:
Prepare an order preview only. Do not submit it. Account: [paper account or subaccount] Instrument: [exact symbol] Side: [buy or sell] Order type: [market or limit] Quantity: [quantity] Maximum notional value: [amount] Limit price, if applicable: [price] Thesis: [reason for the trade] Invalidation: [condition that proves the thesis wrong] Planned exit: [exit condition] Before asking for confirmation: 1. Verify the instrument and account. 2. Retrieve a current price. 3. Calculate the estimated notional value. 4. Explain any missing or ambiguous field. 5. Show the complete order payload in plain English. 6. Confirm that no withdrawal capability is involved. Wait for my explicit confirmation.
After checking the preview, use a separate confirmation message:
I confirm submission of the exact order previewed in your previous response. Submit it once. After submission: 1. Return the exchange order reference and status. 2. Query the exchange to verify that the order exists. 3. Do not retry automatically if the status is uncertain. 4. Add the order and its rationale to ledger.md.
Verify the result directly in the exchange interface. Check the instrument, side, size, price, and account.
6. Turn every closed trade into reviewed memory
Once a trade closes, use this prompt:
Review closed trade [trade ID] using the exchange record, ledger.md, strategy.md, and reflections.md. Update the ledger with the final exit and result. Then draft a learning entry containing: 1. The original thesis and invalidation. 2. Whether execution matched the instructions. 3. A factual explanation of what happened. 4. What went well. 5. What went poorly. 6. A possible observation for future review. 7. References to similar trades, if any. Do not create or modify a permanent strategy rule based on this trade alone. Mark any proposed change as pending manual review.
Review memory.md and learnings.md regularly. Remove unsupported statements, correct hallucinated details, and distinguish normal trading losses from genuine execution problems.
A loss does not automatically invalidate a strategy. Look for repeated observations across multiple trades before approving a new rule. Adding a rule after every loss can overengineer an otherwise coherent strategy.
7. Optional Telegram access
A Telegram bot can relay text or transcribed voice instructions to the trading session. Create the bot through Telegram's BotFather, obtain its token and your chat ID, then ask the coding agent to build the relay.
The host running Claude Code or Codex must remain online and able to access the local files. This could be a dedicated computer, an always on desktop, or another persistent host. Consider the additional security exposure before enabling remote execution.
Use this implementation prompt:
Add a Telegram interface to this existing trading execution project. Requirements: 1. Accept messages only from my configured Telegram chat ID. 2. Store the bot token using a local secret mechanism, never in Markdown files or source control. 3. Reject all unauthorized chat IDs and log the rejection without logging message secrets. 4. Treat Telegram messages as untrusted input. 5. Allow read only requests, such as balances, positions, and market prices. 6. For any order, return a complete preview and require a separate explicit confirmation message. 7. Do not allow withdrawals, API key changes, permission changes, or arbitrary terminal commands through Telegram. 8. Prevent duplicate order submission. 9. If an order status is uncertain, query the exchange rather than retrying. 10. Explain how to start, stop, and verify the relay. First, propose the architecture and security controls. Do not begin implementation until I approve the plan.
Test Telegram with market price and balance requests before exposing order execution. Keep the host patched, restrict physical and remote access, and stop the relay when it is not required.
Final readiness checklist
Before considering the execution layer operational, verify that:
- The MCP comes from the exchange's official integration
- The API key has trading and reading permissions only
- Withdrawals are disabled
- Two factor authentication is enabled
- Secrets are excluded from local memory files and source control
- The bot is connected to the intended paper account or isolated subaccount
- Market prices and balances match the exchange interface
- A test order appears correctly on the exchange
- Every order requires an explicit preview and confirmation
- The ledger records submitted and closed trades
- Learning entries require manual review
- One loss cannot automatically rewrite the strategy
- The agent checks exchange status before retrying an uncertain order
Once these checks pass, you have a reusable execution engine. You can attach a separately tested algorithmic strategy or use it for more controlled discretionary execution, while retaining a complete record of what was requested, what happened, and what was learned.