-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
226 lines (189 loc) · 7.44 KB
/
Copy pathmain.py
File metadata and controls
226 lines (189 loc) · 7.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""
examples/trading_agent/main.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
AgentX autonomous trading agent — simulation mode.
The agent:
1. Fetches mock OHLCV data for SOL/USDC, BTC/USDC, ETH/USDC
2. Computes basic technical indicators (RSI, EMA crossover)
3. Asks the LLM to propose a trade decision
4. Logs the decision (no real funds in simulation mode)
Run: python examples/trading_agent/main.py [--live]
"""
import os
import sys
import argparse
import json
from datetime import datetime
from dotenv import load_dotenv
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
# Adjust sys.path so we can import agentx from source if not installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "..", "AgentX-Core", "src"))
from agentx import Agent, Tool
load_dotenv()
console = Console()
# ---------------------------------------------------------------------------
# Mock market data
# ---------------------------------------------------------------------------
MOCK_PRICES = {
"SOL/USDC": {
"price": 145.20,
"change_24h": +3.7,
"volume_24h": 892_000_000,
"high_24h": 147.80,
"low_24h": 139.50,
"rsi_14": 58.4,
"ema_fast": 143.10,
"ema_slow": 138.90,
},
"BTC/USDC": {
"price": 67_420.0,
"change_24h": +1.2,
"volume_24h": 28_400_000_000,
"high_24h": 68_100.0,
"low_24h": 66_200.0,
"rsi_14": 52.1,
"ema_fast": 67_100.0,
"ema_slow": 65_800.0,
},
"ETH/USDC": {
"price": 3_520.0,
"change_24h": +2.1,
"volume_24h": 14_200_000_000,
"high_24h": 3_580.0,
"low_24h": 3_440.0,
"rsi_14": 61.7,
"ema_fast": 3_510.0,
"ema_slow": 3_380.0,
},
}
# ---------------------------------------------------------------------------
# Agent tools
# ---------------------------------------------------------------------------
def get_market_data(pair: str) -> str:
"""
Fetch current market data for a trading pair.
Available pairs: SOL/USDC, BTC/USDC, ETH/USDC
"""
data = MOCK_PRICES.get(pair.upper())
if not data:
return f"Unknown pair: {pair}. Available: {list(MOCK_PRICES.keys())}"
return json.dumps(data, indent=2)
def get_portfolio_balance() -> str:
"""Return current simulated portfolio balances in USDC and tokens."""
portfolio = {
"USDC": 10_000.00,
"SOL": 12.5,
"BTC": 0.05,
"ETH": 1.2,
"total_value_usdc": 10_000 + (12.5 * 145.20) + (0.05 * 67_420) + (1.2 * 3_520),
}
return json.dumps(portfolio, indent=2)
def place_simulated_order(pair: str, side: str, amount_usdc: float, reason: str) -> str:
"""
Place a simulated trade order (no real funds).
side: 'BUY' or 'SELL'
amount_usdc: position size in USDC
reason: rationale for this trade
"""
pair = pair.upper()
side = side.upper()
if pair not in MOCK_PRICES:
return f"Error: unknown pair {pair}"
if side not in ("BUY", "SELL"):
return f"Error: side must be BUY or SELL"
if amount_usdc <= 0 or amount_usdc > 10_000:
return f"Error: amount must be between 0 and 10,000 USDC"
price = MOCK_PRICES[pair]["price"]
token = pair.split("/")[0]
token_amount = amount_usdc / price
order = {
"status": "SIMULATED_FILL",
"pair": pair,
"side": side,
"amount_usdc": amount_usdc,
"price": price,
f"amount_{token.lower()}": round(token_amount, 6),
"fee_usdc": round(amount_usdc * 0.001, 4),
"timestamp": datetime.utcnow().isoformat(),
"reason": reason,
}
return json.dumps(order, indent=2)
def get_news_sentiment(token: str) -> str:
"""Fetch mock news sentiment score for a given token."""
sentiments = {
"SOL": {"score": 0.72, "label": "Bullish", "top_headline": "Solana TVL hits new ATH amid DeFi surge"},
"BTC": {"score": 0.55, "label": "Neutral", "top_headline": "Bitcoin consolidates near $67K after ETF inflows"},
"ETH": {"score": 0.63, "label": "Bullish", "top_headline": "Ethereum gas fees drop 40% after Dencun upgrade"},
}
data = sentiments.get(token.upper(), {"score": 0.5, "label": "Unknown", "top_headline": "No data"})
return json.dumps(data, indent=2)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def build_agent() -> Agent:
tools = [
Tool(get_market_data, name="get_market_data",
description="Get OHLCV and technical indicators for a trading pair"),
Tool(get_portfolio_balance, name="get_portfolio_balance",
description="Get current simulated portfolio balances"),
Tool(place_simulated_order, name="place_order",
description="Place a simulated trade order (no real funds)"),
Tool(get_news_sentiment, name="get_news_sentiment",
description="Get current news sentiment score for a token"),
]
system_prompt = """You are AgentX TradingBot, an autonomous DeFi trading agent.
Your goal is to analyze market conditions and make intelligent, risk-managed trade decisions.
Rules:
- Never risk more than 20% of the portfolio in a single trade
- Always consider RSI: RSI > 70 = overbought (avoid buying), RSI < 30 = oversold (consider buying)
- Always consider EMA crossover: fast EMA > slow EMA = bullish trend
- Factor in news sentiment before deciding
- After analysis, place exactly ONE trade (or decide to hold)
- End with FINAL ANSWER: summarizing your decision and rationale
Available trading pairs: SOL/USDC, BTC/USDC, ETH/USDC"""
return Agent(
name="trading-bot-v1",
model=os.getenv("AGENTX_MODEL", "gpt-4o"),
tools=tools,
system_prompt=system_prompt,
max_iterations=12,
verbose=True,
)
def display_result(result) -> None:
console.print()
console.print(Panel(
f"[bold green]{result.output}[/bold green]",
title="[bold]Trading Agent Decision[/bold]",
border_style="green",
))
table = Table(title="Execution Summary")
table.add_column("Metric", style="cyan")
table.add_column("Value", style="yellow")
table.add_row("Success", str(result.success))
table.add_row("Iterations", str(result.iterations))
table.add_row("Tool calls", str(len(result.tool_calls)))
for tc in result.tool_calls:
table.add_row(f" └─ {tc['tool']}", str(tc.get("args", {}))[:60])
console.print(table)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="AgentX Trading Agent")
parser.add_argument("--live", action="store_true", help="Enable live trading (NOT IMPLEMENTED)")
args = parser.parse_args()
if args.live:
console.print("[bold red]WARNING: Live trading not yet implemented. Running in simulation mode.[/bold red]")
console.print(Panel(
"[bold cyan]AgentX Trading Agent[/bold cyan]\n"
"Analyzing market conditions and making a trade decision...",
border_style="cyan",
))
agent = build_agent()
task = (
"Analyze the current market for SOL/USDC, BTC/USDC, and ETH/USDC. "
"Check news sentiment for all three tokens. Review my portfolio balance. "
"Identify the best trade opportunity with the strongest risk/reward ratio. "
"Place a simulated order for your top pick."
)
result = agent.run(task)
display_result(result)