-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimulate.py
More file actions
222 lines (187 loc) · 8.63 KB
/
Copy pathsimulate.py
File metadata and controls
222 lines (187 loc) · 8.63 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
#!/usr/bin/env python3
"""
Multi-cycle simulation — runs N full agent cycles with real CMC data and
real AI decisions, but zero blockchain transactions.
Tracks portfolio state across cycles so you can see how the agent behaves
over time before going live.
Usage:
python3 simulate.py # 5 cycles (default)
python3 simulate.py --cycles 10
"""
import os, sys, json, time, argparse
os.environ["PAPER_TRADING"] = "true"
os.environ["NETWORK"] = "testnet"
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import box
console = Console()
parser = argparse.ArgumentParser()
parser.add_argument("--cycles", type=int, default=5)
args = parser.parse_args()
from agent.market import get_top_bsc_tokens, get_bnb_price, get_global_metrics, format_market_summary
from agent.brain import decide
from agent.trader import PancakeSwapTrader
from agent.risk import RiskManager
# ── clean state for simulation ────────────────────────────────────────────────
SIM_STATE_FILE = "sim_portfolio_state.json"
if os.path.exists(SIM_STATE_FILE):
os.remove(SIM_STATE_FILE)
# Patch RiskManager to use a separate state file for the simulation
import agent.risk as _risk_mod
_orig_state = _risk_mod._STATE_FILE
from pathlib import Path
_risk_mod._STATE_FILE = Path(SIM_STATE_FILE)
STARTING_BNB = 1.0 # simulate starting with 1 BNB
trader = PancakeSwapTrader()
console.print(Panel(
f"[bold cyan]BNB AI Trading Agent — {args.cycles}-Cycle Simulation[/bold cyan]\n"
f"[dim]Starting balance: {STARTING_BNB} BNB | Paper trading only[/dim]",
expand=False,
))
# ── history for summary table ─────────────────────────────────────────────────
history = []
simulated_bnb = STARTING_BNB
simulated_positions: dict = {}
# ── main simulation loop ──────────────────────────────────────────────────────
for cycle in range(1, args.cycles + 1):
console.rule(f"[bold]Cycle {cycle}/{args.cycles}[/bold]")
# fetch live data
console.print("[yellow] Fetching market data…[/yellow]", end=" ")
bnb_price = get_bnb_price()
bsc_tokens = get_top_bsc_tokens(limit=25)
global_data = get_global_metrics()
console.print(f"[green]BNB ${bnb_price:,.2f}[/green]")
token_prices = {t["symbol"]: t["price_usd"] for t in bsc_tokens}
# init or update risk manager
if cycle == 1:
risk = RiskManager(bnb_price=bnb_price, initial_bnb_balance=simulated_bnb)
risk.update_bnb_price(bnb_price)
positions = risk.get_positions(token_prices)
positions_usd = sum(p["current_value_usd"] for p in positions.values())
total_value = simulated_bnb * bnb_price + positions_usd
risk.maybe_reset_day(total_value)
daily_pnl = risk.daily_pnl_pct(total_value)
total_pnl = risk.total_pnl_pct(total_value)
# check automatic TP/SL exits
for exit_pos in risk.check_exits(positions):
console.print(f" [red]Auto-exit {exit_pos['symbol']}: {exit_pos['reason']}[/red]")
result = trader.sell_token(exit_pos["address"])
bnb_back = result.get("bnb_received", 0)
simulated_bnb += bnb_back
risk.record_sell(
exit_pos["address"], exit_pos["symbol"],
bnb_back, "paper_trade", True,
exit_pos["reason"], 100,
)
# risk gate
tradeable, reason = risk.can_trade(total_value)
if not tradeable:
console.print(f" [bold red]Risk gate: {reason} — skipping trade[/bold red]")
history.append({
"cycle": cycle, "action": "BLOCKED", "symbol": "—",
"bnb_balance": simulated_bnb, "total_usd": total_value,
"daily_pnl": daily_pnl, "total_pnl": total_pnl,
"reasoning": reason,
})
continue
# AI decision
console.print(" [yellow]Asking AI…[/yellow]", end=" ")
market_summary = format_market_summary(bsc_tokens, global_data, bnb_price)
portfolio_ctx = {
"bnb_balance": simulated_bnb,
"bnb_price": bnb_price,
"positions": positions,
"total_value_usd": total_value,
"daily_pnl_pct": daily_pnl,
}
decision = decide(market_summary, portfolio_ctx, bsc_tokens)
action = decision.get("action", "hold").upper()
symbol = decision.get("token_symbol") or "—"
confidence = decision.get("confidence", 0)
reasoning = decision.get("reasoning", "")
colour = {"BUY": "green", "SELL": "red", "HOLD": "yellow"}.get(action, "white")
console.print(f"[bold {colour}]{action}[/bold {colour}] {symbol} (conf={confidence})")
console.print(f" [dim]{reasoning}[/dim]")
# simulate execution
if action == "BUY":
token_addr = decision.get("token_address")
amount_bnb = float(decision.get("amount_bnb") or 0)
safe_amount = min(amount_bnb, simulated_bnb - 0.005)
if token_addr and safe_amount > 0:
raw_tokens = trader.quote_bnb_to_token(token_addr, safe_amount)
token_price = token_prices.get(symbol, 0)
simulated_bnb -= safe_amount
risk.record_buy(
token_addr, symbol, token_price,
safe_amount, raw_tokens,
"paper_trade", True, reasoning, confidence,
)
console.print(f" [green]Bought {raw_tokens} raw units of {symbol} for {safe_amount:.4f} BNB[/green]")
elif action == "SELL":
token_addr = decision.get("token_address")
if token_addr and token_addr in positions:
result = trader.sell_token(token_addr)
bnb_back = result.get("bnb_received", 0)
simulated_bnb += bnb_back
risk.record_sell(
token_addr, symbol, bnb_back,
"paper_trade", True, reasoning, confidence,
)
console.print(f" [red]Sold {symbol} → received {bnb_back:.4f} BNB[/red]")
# recalculate after trade
positions = risk.get_positions(token_prices)
positions_usd = sum(p["current_value_usd"] for p in positions.values())
total_value = simulated_bnb * bnb_price + positions_usd
daily_pnl = risk.daily_pnl_pct(total_value)
total_pnl = risk.total_pnl_pct(total_value)
history.append({
"cycle": cycle, "action": action, "symbol": symbol,
"confidence": confidence,
"bnb_balance": simulated_bnb, "total_usd": total_value,
"daily_pnl": daily_pnl, "total_pnl": total_pnl,
"reasoning": reasoning,
})
console.print(
f" Portfolio: [cyan]${total_value:,.2f}[/cyan] | "
f"Daily P&L: [{'green' if daily_pnl >= 0 else 'red'}]{daily_pnl:+.2f}%[/] | "
f"Total P&L: [{'green' if total_pnl >= 0 else 'red'}]{total_pnl:+.2f}%[/]"
)
if cycle < args.cycles:
time.sleep(2) # small pause between cycles so CMC rate limits aren't hit
# ── summary table ─────────────────────────────────────────────────────────────
console.rule("[bold]Simulation Summary[/bold]")
table = Table(box=box.ROUNDED, border_style="cyan")
table.add_column("Cycle", justify="center")
table.add_column("Action", justify="center")
table.add_column("Token", justify="center")
table.add_column("Conf", justify="right")
table.add_column("BNB Bal", justify="right")
table.add_column("Total USD", justify="right")
table.add_column("Daily P&L", justify="right")
table.add_column("Total P&L", justify="right")
for h in history:
action_colour = {"BUY": "green", "SELL": "red", "HOLD": "yellow", "BLOCKED": "bright_red"}.get(h["action"], "white")
dpnl = h["daily_pnl"]
tpnl = h["total_pnl"]
table.add_row(
str(h["cycle"]),
f"[{action_colour}]{h['action']}[/{action_colour}]",
h.get("symbol", "—"),
str(h.get("confidence", "—")),
f"{h['bnb_balance']:.4f}",
f"${h['total_usd']:,.2f}",
f"[{'green' if dpnl >= 0 else 'red'}]{dpnl:+.2f}%[/]",
f"[{'green' if tpnl >= 0 else 'red'}]{tpnl:+.2f}%[/]",
)
console.print(table)
if history:
start_usd = STARTING_BNB * get_bnb_price()
end_usd = history[-1]["total_usd"]
net = end_usd - start_usd
console.print(f"\nNet result over {args.cycles} cycles: [bold]${net:+,.2f}[/bold] ({history[-1]['total_pnl']:+.2f}%)")
# cleanup sim state file
_risk_mod._STATE_FILE = _orig_state
if os.path.exists(SIM_STATE_FILE):
os.remove(SIM_STATE_FILE)
console.print("\n[dim]Simulation complete. No real transactions were made.[/dim]")