anuragbb commited on
Commit
fc81fa3
Β·
verified Β·
1 Parent(s): 0a74cfc

Update knowledge-base/Projects/AutonomousTradingAgent.md

Browse files
knowledge-base/Projects/AutonomousTradingAgent.md CHANGED
@@ -1,127 +1,21 @@
1
- # Autonomous Trading Agents πŸ“ˆπŸ€–
2
 
3
- Autonomous Trading Agents is a multi-agent AI system where four independent traders β€” each inspired by a legendary investor β€” autonomously research financial news, make portfolio decisions, and execute real stock trades on a loop, every hour. Built with the OpenAI Agents SDK, Model Context Protocol (MCP), and Gemini 2.5 Flash.
4
 
5
- ## 🎯 What It Does
6
 
7
- Four AI agents run continuously and concurrently. Each one:
8
 
9
- 1. Reads its current portfolio (cash balance, holdings, past transactions)
10
- 2. Reads its investment strategy
11
- 3. Calls a **Researcher sub-agent** to search the web for relevant financial news
12
- 4. Analyzes market data and live stock prices
13
- 5. Makes buy/sell decisions aligned with its strategy
14
- 6. Executes trades against real Polygon.io stock prices
15
- 7. Sends a push notification summarizing activity
16
- 8. Logs everything to a SQLite database for real-time display in a Gradio dashboard
17
 
18
- All four traders run **concurrently** using Python asyncio. The loop repeats every hour (configurable).
19
 
20
- > **Note:** The trading is simulated but prices are real. Each trader starts with $10,000 in the simulation database β€” the money is not real.
21
 
22
- ## πŸ‘€ The Four Traders
23
 
24
- Each trader starts with a strategy inspired by their namesake, and has autonomy to **rewrite their own strategy** over time using a tool.
25
- The legendary investors and their strategies listed below:
26
 
27
- * **Warren** : Value investor. Seeks undervalued companies with strong fundamentals. Patient, long-term.
28
- * **George**: Macro trader. Looks for large-scale mispricings driven by economic/geopolitical events. Bold, contrarian.
29
- * **Ray** : Systematic, principles-based. Risk parity across asset classes. Watches macro cycles.
30
- * **Cathie**: Disruptive innovation. Focused on crypto ETFs. High volatility tolerance.
31
 
32
- Each trader starts with **$10,000**.
33
-
34
- ## πŸ—οΈ Architecture Overview
35
-
36
- Two completely separate processes share state through a single SQLite file:
37
-
38
- * **`trading_floor.py`** β€” the engine. Runs agents, executes trades, writes to DB.
39
- * **`app.py`** β€” the Gradio dashboard. Reads and displays data in real time.
40
-
41
-
42
- ## πŸ” Step-by-Step Execution Flow (per trader, per run)
43
-
44
- 1. `asyncio.gather()` starts all 4 traders at the same time
45
- 2. MCP server subprocesses start: accounts, market, push, fetch, Tavily, memory
46
- 3. Researcher sub-agent created with web search + memory tools; wrapped as a callable tool
47
- 4. Trader agent created with: Researcher tool + account/market/push tools
48
- 5. Current portfolio and strategy are read from SQLite
49
- 6. `Runner.run(agent, message, max_turns=30)` starts the agent loop:
50
- - LLM reads strategy + account state
51
- - Calls Researcher sub-agent β†’ searches Tavily, fetches web pages, stores findings in knowledge graph, returns summary
52
- - Checks live share prices via `lookup_share_price()`
53
- - Executes buy/sell trades via `buy_shares()` / `sell_shares()` β€” SQLite updated immediately
54
- - Sends push notification
55
- - Returns final 2–3 sentence appraisal
56
- 7. Loop repeats every N minutes (default: 60)
57
-
58
- ## πŸ”„ Trade / Rebalance Cycle
59
-
60
- Traders alternate between two modes on successive runs:
61
-
62
- * **Trade mode** β€” find new investment opportunities and execute new positions
63
- * **Rebalance mode** β€” review existing holdings, trim or exit positions that no longer fit the strategy
64
-
65
- This keeps each LLM run focused rather than trying to do everything at once.
66
-
67
- ## πŸ–₯️ Live Dashboard (`app.py`)
68
-
69
- A Gradio UI with four columns (one per trader), each showing:
70
-
71
- * **Portfolio value** β€” total value (cash + holdings at current prices) with P&L in green/red
72
- * **Portfolio chart** β€” Plotly line chart of portfolio value over time
73
- * **Live log** β€” color-coded agent activity, refreshed every 500ms:
74
- * White β€” trace events | Cyan β€” agent activity | Green β€” tool calls | Yellow β€” LLM generation | Red β€” buy/sell actions
75
- * **Holdings table** β€” current stock positions
76
- * **Transactions table** β€” full trade history with rationale
77
-
78
- The dashboard and engine are fully independent β€” you can restart either without affecting the other.
79
-
80
-
81
- ## βš™οΈ Tech Stack
82
-
83
- * **Agent Framework:** OpenAI Agents SDK
84
- * **LLM:** Gemini 2.5 Flash (via OpenAI-compatible endpoint)
85
- * **Tool Protocol:** MCP (Model Context Protocol) β€” stdio transport
86
- * **Market Data:** Polygon.io API (free = end-of-day prices; paid = 15-min delayed; realtime = live)
87
- * **Web Search:** Tavily MCP
88
- * **Web Fetch:** mcp-server-fetch
89
- * **Knowledge Graph:** mcp-memory-libsql (LibSQL / SQLite β€” persists across runs per trader)
90
- * **Push Notifications:** Pushover API
91
- * **Database:** SQLite (Python built-in sqlite3)
92
- * **UI:** Gradio + Plotly
93
- * **Data Modelling:** Pydantic
94
- * **Package Manager:** uv
95
- * **Runtime:** Python 3.12+
96
-
97
- ## πŸ”‘ Required API Keys
98
-
99
- | Service | Purpose | Free Tier? |
100
- |---|---|---|
101
- | Google AI Studio | Gemini 2.5 Flash (the LLM) | Yes |
102
- | Polygon.io | Stock price data | Yes (end-of-day) |
103
- | Tavily | Web search for the Researcher | Yes |
104
- | Pushover | Push notifications (optional) | One-time $5 |
105
-
106
- ## βš™οΈ Configuration (`.env`)
107
-
108
- | Variable | Default | Description |
109
- |---|---|---|
110
- | `RUN_EVERY_N_MINUTES` | 60 | How often the trader loop runs |
111
- | `RUN_EVEN_WHEN_MARKET_IS_CLOSED` | false | If false, skips runs when market is closed |
112
- | `POLYGON_PLAN` | free | `free` / `paid` / `realtime` |
113
-
114
- ## πŸš€ Running the Project
115
-
116
- ```bash
117
- # Terminal 1 β€” start the dashboard
118
- uv run app.py
119
-
120
- # Terminal 2 β€” start the trading engine
121
- uv run trading_floor.py
122
-
123
- # Reset all traders to $10,000 starting state
124
- uv run reset.py
125
- ```
126
-
127
- > Start the dashboard first so you can watch activity appear from the beginning.
 
1
+ # Autonomous Trading Agents
2
 
3
+ Autonomous Trading Agents is a multi-agent AI system where four independent AI traders β€” each modelled on a legendary investor β€” autonomously research financial news, make portfolio decisions, and execute real stock trades every hour. Built with the OpenAI Agents SDK, MCP (Model Context Protocol), and Gemini 2.5 Flash.
4
 
5
+ ## What It Does
6
 
7
+ Four agents run concurrently using Python asyncio. Each agent reads its current portfolio, calls a Researcher sub-agent to search the web for relevant financial news, checks live stock prices via Polygon.io, and executes buy or sell trades. Every decision and trade is logged to a SQLite database and displayed in a live Gradio dashboard.
8
 
9
+ The trading is simulated β€” each agent starts with $10,000 β€” but the stock prices are real, sourced from Polygon.io.
 
 
 
 
 
 
 
10
 
11
+ ## The Four Traders
12
 
13
+ Each agent has a distinct strategy inspired by its namesake investor. Warren follows value investing β€” patient, long-term, focused on fundamentals. George is a macro trader β€” bold and contrarian. Ray is systematic and risk-balanced across asset classes. Cathie focuses on disruptive innovation and crypto ETFs. Agents can also rewrite their own strategy over time using a dedicated tool.
14
 
15
+ ## What Makes It Interesting
16
 
17
+ The system uses a three-tier agent hierarchy β€” an orchestrator coordinates four trader agents, each of which spins up a Researcher sub-agent on demand. MCP servers handle tool access for web search, market data, memory persistence, and push notifications. A custom TracingProcessor hooks into the SDK's internal observability pipeline to surface real-time agent activity in the dashboard. Agents alternate between a trade mode (find new opportunities) and a rebalance mode (review existing holdings) on successive runs, keeping each LLM call focused.
 
18
 
19
+ ## Tech Stack
 
 
 
20
 
21
+ Python, OpenAI Agents SDK, Gemini 2.5 Flash, MCP, Polygon.io, Tavily, SQLite, LibSQL, Gradio, Plotly, Pydantic.