AI DOERS
Book a Call
← All insightsAI Excellence

How to Build a 24/7 Trading Agent Inside Claude Code

The build comes down to Claude Code routines as the scheduler and Opus 4.7 for judgment, wired to the Alpaca API for trades and a file-based memory the agent reads and writes on every scheduled wake-up. The same pattern powers any autonomous business agent.

How to Build a 24/7 Trading Agent Inside Claude Code
Illustration: AI DOERS Studio

Write Your Operating Rules Into Files Before Writing Any Action Logic

The agent wakes up each morning with no memory of yesterday. Every scheduled routine fires stateless, carrying no knowledge of the previous run, no record of what it decided last time, and no awareness of whether its last action produced the intended result. That constraint is not a limitation to work around. It is the design insight that shapes every other decision in building a robust autonomous agent.

Because the agent starts blank on every run, the rules it operates by cannot live inside the agent itself. They have to live in files the agent reads at the start of every session. This is the first principle that separates a reliable scheduled agent from a fragile one: write your operating rules into a structured file before you write a single line of action logic.

The source built this principle into a trading agent running inside Claude Code with Opus 4.7 as the model, wired to the Alpaca API for trade execution and Perplexity for real-time research. But the pattern is not specific to trading. Any recurring business process that reads a current state, makes a bounded decision within defined limits, acts through an API, and should log its reasoning is a candidate for this same architecture.

For a restaurant, the operating rules file contains par levels by ingredient, supplier names with minimum order quantities, and the maximum spend the agent is authorized to commit per ordering cycle. For a service business, it might contain response-time targets for different inquiry types, escalation thresholds that require human review, and the categories of action the agent is permitted to take without approval. Writing these down before the first automated action runs means the agent reads them on every wake-up and operates consistently within them, even six months later when the original parameters are no longer fresh in anyone's mind.

The file-first approach also makes the system auditable. If an agent takes an unexpected action, the question is always: what did the rules file say? If the rules file said to act in that situation, the rules file needs revision. If it did not say to act in that situation, the action logic has a gap. Either way, the file is the clear reference point. An agent whose operating rules live only in the prompt cannot be audited the same way because the prompt changes between sessions.

How it works (short)

Set the Guardrails Before the First Automated Action Runs

The second principle the source makes explicit is that guardrails come before action logic in the build sequence. The trading agent in the source defined hard limits before any trading code was written: a maximum percentage of the portfolio to commit per position, a daily loss limit that would halt the session entirely, a cap on new positions per week to prevent overtrading, and a categorical exclusion of instrument types the strategy was not designed to handle.

These limits matter most precisely in the situations the original design did not anticipate. Action logic performs correctly for the scenarios it was designed for. Guardrails catch the scenarios it was not. An agent with a daily loss cap will stop rather than continue a failing strategy into catastrophic territory. An agent with a per-order spend cap will not commit beyond that cap even if the action logic concludes a very large order is justified by current conditions.

The same principle applies directly to non-trading applications. A restaurant ordering agent needs a daily spend cap that reflects actual cash flow, not just average order sizes. It needs a rule preventing it from ordering an ingredient already confirmed in transit, because it cannot know about conversations that happened outside its file-based memory. It needs a rule requiring human approval for any single order above a threshold the owner sets. A customer follow-up agent needs a rule preventing it from contacting the same person more than once within a defined window. A price-monitoring agent needs a threshold below which it takes no action, to avoid generating noise from normal market fluctuation.

The order of operations matters: guardrails first, action logic second. An agent built the other way, with sophisticated action logic and guardrails added as an afterthought, will behave correctly in all the scenarios you tested and unpredictably in the ones you did not. The guardrails are the protection against the situations you did not anticipate, and those are precisely the situations most likely to produce the worst outcomes.

For any autonomous agent in a production-adjacent context, the first full run should treat the guardrails as a paper-trading equivalent. Let the agent complete the full cycle: read files, make decisions, log intended actions. But have it report rather than act. Review the intended actions. Confirm they are what you expected. Then enable the agent to act rather than report. This review phase surfaces design gaps before they produce real consequences, and it costs only the time needed to read the output.

Hours per week spent on manual reordering

Build the Memory So Each Wake-Up Starts Informed, Not Blank

The stateless constraint that governs every scheduled run makes the memory architecture the most consequential design decision in the entire build. A stateless agent that reads only static configuration files knows the rules but does not know what happened yesterday, what it tried last week, or what it learned from the run that produced an unexpected result.

Building genuine learning into a stateless agent means the agent writes structured observations back to a lessons file at the end of every run, and every subsequent run reads that file before taking any action. In the source, the trading agent accumulated observations across sessions: this strategy underperformed in high-volatility conditions, this position size aligned well with the account's actual risk tolerance, this category of news produced predictable price movements worth anticipating. None of those observations lived in the model. All of them lived in the file, read fresh on every new session.

The lessons file is the mechanism that lets the agent improve over time without any change to the underlying model. The model is identical on run 1 and run 50. The lessons file is different because the agent has written to it 49 times. That accumulated context changes how the agent interprets its current situation, even though the model has no persistent memory between sessions.

Context budget is a real constraint in this design. Each routine session has a defined token window, and loading all project files on every run wastes context budget on information that will not affect the current run's decisions. The morning inventory check does not need the full six-month lessons archive. It needs the par levels file, the supplier list, the current stock snapshot, and the most recent seven days of lessons. Loading selectively keeps the majority of the context window available for the actual reasoning the current run requires.

The concrete benefit shows up in the numbers. A restaurant manager recovering 30 minutes of morning inventory and ordering work per operating day across 300 operating days per year recovers 150 hours of time annually. At a fully-loaded cost of $25 per hour for the manager's time, that is $3,750 per year in recovered capacity. The agent enabling this costs well under $100 per year in model API tokens. That is a 37-to-1 return on the operating cost, before accounting for the one-time setup investment.

Use Remote Routines If the Job Has to Run While Your Computer Is Off

Local routines in Claude Code only fire while the desktop application is open and the computer is active. If the job needs to run while you are away from your machine, overnight, on weekends, or during any period you are not actively working, local routines miss their schedule silently. The agent does not error or alert. It simply does not run, and the next morning there is no new output and no indication of what was missed.

Remote routines run from a GitHub repository in the cloud and fire on their schedule regardless of whether the local desktop is open. For any agent designed to operate without human presence, remote routines are not an advanced option. They are the correct architecture for the core use case.

The tradeoff is that remote routines require the agent's memory files to live in the repository and be committed back after every run. On every session, the agent reads files from the repository at session start. At session end, it must commit and push updated files back to the repository. A remote agent that completes its work but does not commit the updated memory files has made the current session's learning invisible to all future runs. The next session reads the same files it read today and starts from an identical state, as if the intervening run never happened.

Secrets handling is the other constraint that remote routines make non-negotiable. API keys, database credentials, and any other sensitive values must live in the cloud environment variables, not in any file the agent can push to the repository. The source is specific about this: name each key exactly as it appears in the environment or the agent will report it missing and fail the run without further explanation. A key named slightly differently in the prompt than it appears in the environment is a common setup error that produces a confusing failure mode.

Always Have the Agent Commit Its Files Back or the Next Run Starts Blind

This principle is the operational extension of the previous one, and it deserves its own section because the failure mode is so common and so difficult to diagnose after the fact.

Consider the restaurant ordering agent. The morning run reads current stock levels, compares them against par levels, identifies shortfalls, and drafts a supplier order within the daily spend cap. The agent logs the drafted order in the day's journal file and notes a discrepancy: expected usage was off because weekend brunch always consumes eggs faster than the weekday par level assumes. Tomorrow's run needs that discrepancy note to adjust its comparison correctly. If the journal file is not committed and pushed back to the repository, tomorrow's run reads a stale journal and misses the note, potentially drafting the same undersized order the agent would have flagged if it remembered what happened today.

The fix is treating the commit step as part of the action definition, not as cleanup after the action is complete. In the routine instructions, the commit step should appear explicitly: after all decisions are made, all orders are drafted, and all journal entries are written, commit the updated memory files and push to the repository before closing the session. Frame it as a required last step, not optional housekeeping.

An agent that runs correctly four days out of five because memory files are not being committed reliably delivers most of the theoretical value but creates confusion about what happened on the days it started blind. Getting the commit step right from the first session means getting the full value reliably, which is the difference between a system the business can depend on and a system the business has to monitor constantly to make sure it is working as expected.

Migrate Strategy, Not Mechanics, When You Change Platforms

The source built the trading agent's second version inside Claude Code after an earlier version ran in a different environment. The decision that made the migration successful was not retraining the strategy. The operating rules files, the trade log, the lessons file, and the strategy description were exported from the old environment and loaded directly into the new one. The agent started in the new environment reading its accumulated lessons as if it had always been there.

This is the correct migration philosophy for any autonomous agent built on file-based memory. The value is in the files, not in the mechanics of the platform. A restaurant agent that has refined its par-level comparisons over six months of learning the operation's actual usage patterns holds that learning in its lessons file. Moving to a different scheduling platform should preserve every file the agent has produced and read, even if the code that runs the agent is completely rewritten.

File format decisions made early in the build have lasting consequences. If the lessons file is in plain text or structured markdown that a human can read and edit, it can be carried across platforms and manually refined during migrations. If it is in a format that only the original system can parse, the lessons are effectively locked to that platform. Plain text and structured markdown are almost always the right choice for agent memory files, because they are portable, human-readable, and can be loaded into any context window without format translation.

The same migration logic applies when strategy needs to evolve. If the restaurant ordering agent learns over three months that one supplier consistently delivers late on Fridays, that lesson belongs in the lessons file as a written observation the agent reads on every run, not as a hardcoded conditional in the action logic. Written in the file, the lesson survives a platform migration, a prompt rewrite, or a change in which model the agent runs on. Written in the action logic, it requires a code change every time the strategy needs to adapt to new information. The agent's discipline lives in its files. Protecting those files, keeping them committed, keeping them human-readable, and migrating them intact when platforms change is how you protect the investment in the strategy the agent has learned to execute.

Do it with an expert
You can build this yourself, or have it set up right the first time.

That is exactly what we do at AI DOERS. Book a private 30-minute call with Madhuranjan Kumar and we will map the fastest path to it for your specific business.

Book your call →
Madhuranjan Kumar

Madhuranjan Kumar

Founder, AI DOERS · Performance Marketing

Madhuranjan Kumar brings 20 years of performance-marketing experience and has managed over $200 million in Facebook ad spend for brands across the United States and beyond. His expertise spans the full modern marketing stack: Meta, Google Ads, TikTok, email automation, CRM, and the websites that hold it together. At AI DOERS he turns that track record into lead-generation systems for businesses across every industry.

← Back to all insights
How to Build a 24/7 Trading Agent Inside Claude Code | AI Doers