-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_simulation.py
More file actions
169 lines (140 loc) · 6.08 KB
/
run_simulation.py
File metadata and controls
169 lines (140 loc) · 6.08 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
"""
run_simulation.py
=================
Main entry point for the DeFi Risk Simulation Lab.
Usage:
python run_simulation.py
# With Groq Wildcard agent:
set GROQ_API_KEY=gsk_your_key_here (Windows)
python run_simulation.py
Output:
- defi_simulation.db — SQLite database (12-column schema)
- simulation_log.csv — CSV export for ML anomaly detection
- Console summary — Per-agent action breakdown
"""
import logging
import sys
import os
import config
from model import DeFiSimulationModel
# ------------------------------------------------------------------ #
# LOGGING SETUP #
# ------------------------------------------------------------------ #
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)-8s | %(name)-28s | %(message)s",
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler("simulation.log", mode="w"),
],
)
logger = logging.getLogger(__name__)
def print_banner() -> None:
print("\n" + "=" * 65)
print(" [*] DeFi Risk Simulation Lab")
print(" Mesa ABM + Groq Wildcard Agent")
print("=" * 65)
print(f" Steps : {config.SIMULATION_STEPS}")
print(f" Agents : 7 Instances")
print(f" Total Accounts : {config.TOTAL_ACCOUNTS}")
print(f" Pool start : {config.INITIAL_RESERVE_USDC:,.0f} USDC / "
f"{config.INITIAL_RESERVE_ETH:.0f} ETH")
print(f" Starting price : ${config.INITIAL_RESERVE_USDC / config.INITIAL_RESERVE_ETH:,.2f} USDC/ETH")
groq_status = "[OK] configured" if config.GROQ_API_KEY else "[!] not set (fallback mode)"
print(f" Groq API key : {groq_status}")
print("=" * 65 + "\n")
def print_final_summary(model: DeFiSimulationModel) -> None:
"""Print end-of-run metrics and DB summary."""
liq = model.protocol.get_pool_liquidity()
price = model.protocol.get_token_price()
oracle = model.protocol.get_oracle_price()
spread = (price - oracle) / oracle * 100 if oracle else 0.0
print("\n" + "=" * 65)
print(" [>>] SIMULATION COMPLETE")
print("=" * 65)
print(f" Steps run : {model.schedule.steps}")
print(f" Final pool : {liq['reserve_usdc']:>12,.2f} USDC")
print(f" {liq['reserve_eth']:>12,.4f} ETH")
print(f" AMM price : ${price:>10,.2f} USDC/ETH")
print(f" Oracle price : ${oracle:>10,.2f} USDC/ETH")
print(f" AMM/Oracle gap : {spread:>+9.3f}%")
print("\n Action summary (from SQLite):")
summary = model.db.get_summary()
for agent_type, actions in sorted(summary.items()):
print(f" {agent_type}")
for action, count in sorted(actions.items()):
print(f" {action:<25} {count:>5} times")
print("=" * 65 + "\n")
def run_inline_assertions(model: DeFiSimulationModel) -> None:
"""
Quick sanity checks for hackathon demo / CI purposes.
Prints PASS/FAIL for each check without crashing the run.
"""
summary = model.db.get_summary()
checks = {
"Arbitrageur acted": bool(summary.get("ArbitrageTraderAgent")),
"Whale acted": bool(summary.get("CryptoWhaleAgent")),
"Retail traded": bool(summary.get("RetailTraderAgent")),
"MEV routed": bool(summary.get("MEVSearcherAgent")),
"DB rows written": sum(sum(v.values()) for v in summary.values()) > 0,
}
print(" [CHECKS] Assertion Results:")
all_passed = True
for check, passed in checks.items():
status = "PASS" if passed else "FAIL"
print(f" [{status}] {check}")
if not passed:
all_passed = False
if all_passed:
print("\n All checks passed! Ready for the hackathon.")
else:
print("\n Some checks failed. Review logs above.")
print()
def main() -> None:
print_banner()
# Remove old DB to start fresh each run (delete if it exists)
if os.path.exists(config.DB_PATH):
os.remove(config.DB_PATH)
logger.info("Removed old database: %s", config.DB_PATH)
# ---------------------------------------------------------------- #
# BUILD MODEL #
# ---------------------------------------------------------------- #
model = DeFiSimulationModel(
seed = config.RANDOM_SEED,
db_path = config.DB_PATH,
)
# ---------------------------------------------------------------- #
# RUN SIMULATION #
# ---------------------------------------------------------------- #
print(f"Running {config.SIMULATION_STEPS} steps ...\n")
for step in range(config.SIMULATION_STEPS):
model.step()
# Print a progress dot every 10 steps
if (step + 1) % 10 == 0:
liq = model.protocol.get_pool_liquidity()
price = model.protocol.get_token_price()
print(
f" Step {step+1:>3}/{config.SIMULATION_STEPS} | "
f"price=${price:>8.2f} | "
f"pool={liq['reserve_usdc']:>10,.0f} USDC / {liq['reserve_eth']:>7.3f} ETH"
)
# ---------------------------------------------------------------- #
# EXPORT DATA #
# ---------------------------------------------------------------- #
csv_path = model.db.export_csv(config.CSV_PATH)
print("\n Data exported to:")
print(f" SQLite -> {os.path.abspath(config.DB_PATH)}")
print(f" CSV -> {os.path.abspath(csv_path)}")
# DataCollector time-series (for ML / plotting)
df = model.datacollector.get_model_vars_dataframe()
ts_path = "timeseries.csv"
df.to_csv(ts_path)
print(f" Time → {os.path.abspath(ts_path)}")
# ---------------------------------------------------------------- #
# SUMMARY & ASSERTIONS #
# ---------------------------------------------------------------- #
print_final_summary(model)
run_inline_assertions(model)
model.close()
if __name__ == "__main__":
main()