Build a Paper Trading Bot With Persistent Memory
Create a venue neutral execution prototype with precise crossover rules, paper order safeguards, backtesting prompts, a trade ledger, and an evidence based learnings file.
Download the complete paper trading bot blueprint
Build a Paper Trading Bot With Persistent Memory
Connect an AI agent to a trading venue, define a testable crossover strategy, and record every decision in a two file memory system.
What you will achieve
You will have a venue neutral blueprint for a paper trading bot that observes the market, evaluates a defined rule, records trades, and produces reviewable lessons without risking real capital.
Who this is for
Traders and technical beginners who want to prototype an AI assisted stock or crypto bot before considering live deployment.
Difficulty: Intermediate
Short tutorial
Connect an AI agent to a trading venue, define a testable crossover strategy, and record every decision in a two file memory system.
Guide: Build a Paper Trading Bot With Persistent Memory
Time: 45 to 60 minutes
What you will build
This tutorial turns a simple trading rule into a paper trading bot with four components:
- An LLM acts as the reasoning layer.
- An MCP server or API connection supplies market data and paper order execution.
- A strategy specification defines exactly when the bot may act.
- A ledger and learnings file preserve its history between runs.
The result is an execution prototype, not a guaranteed profitable strategy. Start with paper trading. A memory system can reduce repeated mistakes, but it does not ensure good decisions, prevent hallucinations, or make past performance predictive of future results.
Use the steps in order. Replace every value in angle brackets before running the prompts.
1. Choose the venue and connection
First decide whether the bot will trade stocks or crypto. Select a venue that provides paper trading and a supported MCP or API connection.
The source describes this architecture:
| Component | Role |
|---|---|
| LLM, such as Claude or GPT | Reads the strategy and memory, then evaluates decisions |
| MCP server or API bridge | Retrieves prices and sends paper orders to the venue |
| Paper trading account | Simulates execution without risking real funds |
| Memory files | Store trade history and plain language lessons |
Alpaca is identified in the source as one stock venue with paper trading and an MCP server. Several crypto exchanges may also provide MCP or API connectivity, but availability and setup can change. Confirm the current connection method directly inside your chosen venue.
Connection checklist
- Create a paper trading account.
- If the venue supports subaccounts, create a dedicated bot subaccount.
- Generate credentials for the paper environment only.
- Configure the supported MCP server or API bridge.
- Store credentials in the connection's secret or environment configuration. Do not write keys into prompts, strategy files, ledgers, or source control.
- Verify that the agent can retrieve a price and account balance.
- Keep real capital disconnected during development.
Ask your coding agent to guide the connection with this prompt:
Help me connect <LLM OR CODING AGENT> to the paper trading environment of <VENUE> using its supported <MCP OR API> connection. Requirements: 1. Use paper trading only. 2. Keep credentials out of prompts, logs, strategy files, and source control. 3. Explain each setup action before performing it. 4. First test read only access by retrieving one current market price and the paper account balance. 5. Do not place an order yet. 6. If required information is missing, stop and ask me for it. 7. Do not invent tool names, endpoints, or configuration values. Use only tools exposed by the configured connection. Return a short connection checklist and the result of each verification.
Do not continue until price and paper account queries succeed reliably.
2. Write the bot's objective and boundaries
A bot without an explicit objective cannot evaluate whether its behavior is useful. Create a short profile covering the market, time frame, risk boundary, and success criteria.
Save this as BOT_PROFILE.md:
# Bot profile ## Environment Mode: Paper trading only Venue: <VENUE> Asset class: <STOCKS OR CRYPTO> Allowed symbols: <SYMBOL LIST> Trading time frame: <TIME FRAME> Evaluation period: <START DATE TO END DATE> ## Objective Test whether a moving average crossover can produce consistent paper trading results after costs and execution assumptions. ## Risk boundaries Maximum position size: <VALUE OR PERCENT> Maximum open positions: <NUMBER> Maximum paper loss per trade: <VALUE OR PERCENT> Maximum paper loss per session: <VALUE OR PERCENT> ## Execution boundaries Only trade allowed symbols. Never trade if required market data is missing or stale. Never infer a crossover from incomplete data. Never place a live order. Record skipped signals as well as executed signals. ## Evaluation metrics Number of signals: Number of executed trades: Win rate: Average gain: Average loss: Total paper profit or loss: Maximum drawdown: Most common reason for skipping:
Risk controls must also be enforced by deterministic code or venue settings where possible. Do not rely solely on an LLM remembering prose instructions.
3. Define the crossover strategy precisely
The example strategy uses two moving averages:
- Buy when the fast moving average crosses above the slow moving average.
- Sell or exit when the fast moving average crosses below the slow moving average.
The source does not prescribe periods or a chart interval. Select them through backtesting rather than guessing, then record the chosen values.
Save this as STRATEGY.md:
# Moving average crossover strategy ## Instrument and data Symbol: <SYMBOL> Candle interval: <INTERVAL> Fast moving average period: <FAST PERIOD> Slow moving average period: <SLOW PERIOD> Moving average type: <TYPE> ## Entry rule A long entry signal exists only when: 1. On the previous completed candle, the fast average was less than or equal to the slow average. 2. On the latest completed candle, the fast average is greater than the slow average. 3. All required market data is available. 4. No position is already open for the symbol. 5. The trade passes every risk boundary in BOT_PROFILE.md. ## Exit rule Exit the long position only when: 1. On the previous completed candle, the fast average was greater than or equal to the slow average. 2. On the latest completed candle, the fast average is less than the slow average. ## No action rule Take no action when: 1. The averages have not crossed on completed candles. 2. Data is missing, stale, or inconsistent. 3. Position or loss limits would be exceeded. 4. The same signal has already been processed. ## Order behavior Environment: Paper trading only Order size: <SIZE> Order type: <ORDER TYPE SUPPORTED BY VENUE> ## Change control Do not rewrite this strategy automatically. Record proposed improvements in LEARNINGS.md for human review and backtesting.
Using completed candles and checking the previous state prevents the bot from repeatedly treating the same condition as a new crossover.
4. Backtest before connecting execution
If your environment exposes historical data through TradingView, your venue, or another configured data tool, have the agent test the exact written strategy. The source mentions a Claude and TradingView MCP workflow, but does not provide connection instructions, so use only tools actually available in your environment.
Backtest the exact rules in STRATEGY.md for <SYMBOL> from <START DATE> through <END DATE>. Requirements: 1. Use only completed candles. 2. State the data source, time zone, and available date range. 3. Include the declared execution assumptions and any available fee or slippage assumptions. 4. Do not alter the strategy during the test. 5. Report signal count, completed trades, win rate, average gain, average loss, total return, and maximum drawdown when the data supports them. 6. List missing data or assumptions that could materially change the result. 7. If the required data or tool is unavailable, say so and stop rather than fabricating results. Return the results in a table, followed by a concise limitations section.
A promising backtest is only a reason to continue testing. It is not proof that the strategy will perform in future market conditions.
5. Create the two file memory system
Trade ledger
Create `TRADE_LEDGER.csv` with this header:
trade_id,symbol,signal_time,decision_time,action,fast_value,slow_value,market_context,decision_reason,order_size,entry_price,exit_price,exit_time,paper_pnl,status,lesson_id
Record both trades and skipped decisions. This gives you evidence about what the bot saw, why it acted, and what happened afterward.
Use these status values consistently:
SKIPPED OPEN CLOSED_WIN CLOSED_LOSS CLOSED_FLAT ERROR
Learnings file
Create `LEARNINGS.md`:
# Learnings ## Approved constraints No additional constraints have been approved yet. ## Proposed lessons ### Lesson template Lesson ID: L<number> Related trade ID: <trade_id> Date: <date> Setup observed: <plain language description> Outcome: <paper result> Evidence: <what the ledger shows> Proposed lesson: <one concise lesson> Suggested confirmation or filter: <testable condition> Status: PROPOSED
A lesson should describe evidence, not turn one loss into a universal rule. For example:
### L001 Lesson ID: L001 Related trade ID: T001 Date: 2025-01-15 Setup observed: Fast average crossed above the slow average, then reversed on the next completed candle. Outcome: Paper loss. Evidence: One losing trade in TRADE_LEDGER.csv. Proposed lesson: Test whether an additional completed candle confirmation reduces rapid reversals. Suggested confirmation or filter: Require the fast average to remain above the slow average for one additional completed candle. Status: PROPOSED
Keep it proposed until you have backtested the change. Automatically refusing every setup that resembles one past loss can overfit the bot to limited history.
6. Build the observe, decide, execute loop
Give your coding agent the following implementation prompt. It is venue neutral because the source does not provide venue specific tool calls.
Build a paper trading bot using the tools currently available in this project. Read these files before every evaluation: 1. BOT_PROFILE.md 2. STRATEGY.md 3. TRADE_LEDGER.csv 4. LEARNINGS.md For each scheduled evaluation, perform this sequence: OBSERVE 1. Retrieve the required completed candles for the allowed symbol. 2. Validate that the data is complete and current for the configured interval. 3. Calculate the fast and slow moving averages defined in STRATEGY.md. DECIDE 4. Compare the previous completed candle with the latest completed candle. 5. Determine whether a new entry crossover, exit crossover, or no action condition exists. 6. Check account state, existing positions, position limits, and paper loss limits. 7. Read approved constraints in LEARNINGS.md. 8. Do not enforce lessons marked PROPOSED. 9. Produce a structured decision containing the data used, rule result, risk result, and final action. EXECUTE 10. If and only if every entry or exit condition passes, submit a paper order through the configured connection. 11. Never submit a live order. 12. If any required fact or tool is unavailable, skip execution and log the reason. RECORD 13. Append every executed or skipped decision to TRADE_LEDGER.csv. 14. Never overwrite earlier ledger rows. 15. When a trade closes, calculate its paper result and append one evidence based proposed lesson to LEARNINGS.md. 16. Never modify STRATEGY.md automatically. SAFETY 17. Make execution idempotent so the same signal cannot create duplicate orders. 18. Stop after any API, data validation, or order error. 19. Print a concise run summary with the signal, action, reason, and ledger row ID. Before writing code, inspect the available MCP or API tools. Ask me for any missing configuration. Do not invent unavailable functions or credentials.
The key loop is:
Read rules and memory
↓
Observe completed market data
↓
Validate data and risk limits
↓
Decide: enter, exit, or skip
↓
Place paper order when permitted
↓
Append decision to ledger
↓
On close, propose one lesson
↓
Repeat at the next interval7. Test failure cases before autonomous runs
Run each test in the paper environment and confirm the expected result.
| Test | Expected behavior |
|---|---|
| No crossover | Log SKIPPED, place no order |
| Entry crossover | Place one paper order and log it |
| Same signal evaluated twice | Do not create a duplicate order |
| Existing position | Follow the position rule, do not open a duplicate |
| Missing candle | Stop or skip, record the data problem |
| Position limit exceeded | Skip and record the risk rejection |
| Connection error | Stop, record ERROR, do not retry blindly |
| Exit crossover | Close the paper position and update the ledger |
| Closed trade | Add one proposed lesson |
Use this audit prompt after the tests:
Audit the paper trading bot against BOT_PROFILE.md and STRATEGY.md. Review the latest ledger entries and report: 1. Whether each action matched the written strategy. 2. Whether any duplicate signal created more than one order. 3. Whether every skipped decision contains a specific reason. 4. Whether paper orders were used exclusively. 5. Whether any lesson was enforced without approval and backtesting. 6. Any missing validation, unexplained behavior, or rule violation. Do not modify files or place orders. Return findings grouped as PASS, WARNING, or FAIL.
8. Operate the paper bot and review its memory
Run the bot long enough to observe different market conditions, rather than judging it from one or two trades. Review the ledger regularly for repeated losses, execution errors, missing context, and lessons supported by multiple examples.
For each proposed change:
- Turn the lesson into a precise rule.
- Backtest the original and revised strategies over the same data.
- Compare return, drawdown, trade count, and assumptions.
- Approve the change manually only if the evidence supports it.
- Record the approval under
Approved constraintsinLEARNINGS.md. - Continue paper testing after every change.
If the ledger grows too large for reliable file based review, the source suggests moving the same records into a cloud database such as Supabase, SuperMemory, or Firebase. Keep the two file version until scale creates a real need for that added complexity.
Final deployment gate
Do not connect real capital unless all of these are true:
- The strategy has been defined and backtested.
- The bot has completed sustained paper testing.
- Duplicate order protection has been verified.
- Missing data and connection failures stop execution safely.
- Every action is recorded with a reason.
- Strategy changes require review rather than automatic mutation.
- API credentials are isolated from prompts and logs.
- Any future live account uses only capital you can afford to lose.
The central principle is simple: automation improves consistency of execution, but it does not create an edge by itself. The strategy, risk boundaries, data quality, and review process still determine whether the system is useful.