-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunner.py
More file actions
323 lines (254 loc) · 9.31 KB
/
runner.py
File metadata and controls
323 lines (254 loc) · 9.31 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import hashlib
import hmac
import json
import os
import time
import requests
from dotenv import load_dotenv
from supabase import create_client
from experiment_context import get_experiment_context, with_experiment_context
load_dotenv()
PAPER_SYMBOL = "tTESTBTC:TESTUSD"
BITFINEX_ORDER_URL_PATH = "auth/w/order/submit"
BITFINEX_ORDER_URL = f"https://api.bitfinex.com/v2/{BITFINEX_ORDER_URL_PATH}"
REQUEST_TIMEOUT_SECONDS = 20
SUPABASE_URL = os.getenv("SUPABASE_URL")
SUPABASE_SERVICE_ROLE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY")
BITFINEX_API_KEY = os.getenv("BITFINEX_API_KEY")
BITFINEX_API_SECRET = os.getenv("BITFINEX_API_SECRET")
PAPER_MODE = os.getenv("PAPER_MODE", "false").lower() == "true"
SYMBOL = os.getenv("SYMBOL", PAPER_SYMBOL)
def parse_positive_int_env(name, default):
raw_value = os.getenv(name)
if raw_value in (None, ""):
return default
try:
value = int(raw_value)
except ValueError as exc:
raise RuntimeError(f"{name} must be an integer.") from exc
if value <= 0:
raise RuntimeError(f"{name} must be greater than zero.")
return value
def parse_positive_float_env(name, default):
raw_value = os.getenv(name)
if raw_value in (None, ""):
return default
try:
value = float(raw_value)
except ValueError as exc:
raise RuntimeError(f"{name} must be a number.") from exc
if value <= 0:
raise RuntimeError(f"{name} must be greater than zero.")
return value
RUNNER_POLL_SECONDS = parse_positive_int_env("RUNNER_POLL_SECONDS", 5)
DEFAULT_ORDER_AMOUNT = parse_positive_float_env("DEFAULT_ORDER_AMOUNT", 0.0001)
def fail_closed_check():
missing = []
for name, value in {
"SUPABASE_URL": SUPABASE_URL,
"SUPABASE_SERVICE_ROLE_KEY": SUPABASE_SERVICE_ROLE_KEY,
"BITFINEX_API_KEY": BITFINEX_API_KEY,
"BITFINEX_API_SECRET": BITFINEX_API_SECRET,
}.items():
if not value:
missing.append(name)
if missing:
raise RuntimeError(f"Missing required env values: {', '.join(missing)}")
if not PAPER_MODE:
raise RuntimeError("PAPER_MODE must be true. Refusing to run.")
if SYMBOL != PAPER_SYMBOL:
raise RuntimeError(f"SYMBOL must be {PAPER_SYMBOL} for paper trading.")
def audit(supabase, event_type, severity="info", signal_id=None, order_id=None, payload=None):
supabase.table("agent_audit_log").insert({
"event_type": event_type,
"severity": severity,
"signal_id": signal_id,
"order_id": order_id,
"payload": with_experiment_context(payload),
}).execute()
def fetch_next_signal(supabase):
result = (
supabase.table("agent_signals")
.select("*")
.eq("status", "queued")
.order("created_at")
.limit(1)
.execute()
)
if not result.data:
return None
return result.data[0]
def mark_signal(supabase, signal_id, status):
supabase.table("agent_signals").update({
"status": status,
}).eq("id", signal_id).execute()
def create_paper_order_record(supabase, signal):
result = supabase.table("paper_orders").insert({
"signal_id": signal["id"],
"exchange": "bitfinex",
"symbol": signal["symbol"],
"side": signal["side"],
"order_type": "market",
"amount": DEFAULT_ORDER_AMOUNT,
"status": "created",
"request_payload": {
"paper_mode": True,
"source": "agent_trader_mcp_paper",
"symbol": SYMBOL,
"experiment": get_experiment_context(),
},
}).execute()
return result.data[0]
def update_order_result(supabase, order_id, response):
supabase.table("paper_orders").update({
"status": "accepted",
"exchange_order_id": response.get("exchange_order_id"),
"response_payload": response,
}).eq("id", order_id).execute()
def mark_order_failed(supabase, order_id, response):
supabase.table("paper_orders").update({
"status": "failed",
"response_payload": response,
}).eq("id", order_id).execute()
def submit_bitfinex_paper_order(signal, amount):
signed_amount = amount if signal["side"] == "buy" else -amount
body = {
"type": "EXCHANGE MARKET",
"symbol": signal["symbol"],
"amount": str(signed_amount),
"price": "0",
"meta": {
"source": "agent_trader_mcp_paper",
"paper_only": True,
"signal_id": signal["id"],
"experiment": get_experiment_context(),
},
}
body_json = json.dumps(body)
nonce = str(int(time.time() * 1_000_000))
signature_payload = f"/api/v2/{BITFINEX_ORDER_URL_PATH}{nonce}{body_json}"
signature = hmac.new(
BITFINEX_API_SECRET.encode("utf-8"),
signature_payload.encode("utf-8"),
hashlib.sha384,
).hexdigest()
headers = {
"bfx-nonce": nonce,
"bfx-apikey": BITFINEX_API_KEY,
"bfx-signature": signature,
"content-type": "application/json",
}
response = requests.post(
BITFINEX_ORDER_URL,
headers=headers,
data=body_json,
timeout=REQUEST_TIMEOUT_SECONDS,
)
return {
"ok": response.ok,
"http_status": response.status_code,
"response_text": response.text,
"request": body,
"symbol": signal["symbol"],
"side": signal["side"],
"amount": str(signed_amount),
}
def main():
fail_closed_check()
supabase = create_client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
print("Agent Trader MCP Paper Runner started.")
print(f"Mode: PAPER ONLY | symbol={SYMBOL} | poll_seconds={RUNNER_POLL_SECONDS}")
audit(
supabase,
"runner_started",
payload={
"paper_mode": PAPER_MODE,
"symbol": SYMBOL,
"default_order_amount": DEFAULT_ORDER_AMOUNT,
"runner_poll_seconds": RUNNER_POLL_SECONDS,
},
)
while True:
signal_id = None
order_id = None
try:
signal = fetch_next_signal(supabase)
if not signal:
time.sleep(RUNNER_POLL_SECONDS)
continue
signal_id = signal["id"]
signal_symbol = signal.get("symbol")
if signal_symbol != SYMBOL:
mark_signal(supabase, signal_id, "failed")
audit(
supabase,
"signal_rejected_disallowed_symbol",
severity="error",
signal_id=signal_id,
payload={
"expected_symbol": SYMBOL,
"received_symbol": signal_symbol,
},
)
print(f"Rejected signal {signal_id}: symbol {signal_symbol} is not allowed.")
time.sleep(RUNNER_POLL_SECONDS)
continue
print(f"Processing signal: {signal_id} ({signal_symbol})")
mark_signal(supabase, signal_id, "processing")
audit(supabase, "signal_processing_started", signal_id=signal_id, payload=signal)
order = create_paper_order_record(supabase, signal)
order_id = order["id"]
response = submit_bitfinex_paper_order(signal, DEFAULT_ORDER_AMOUNT)
if response.get("ok"):
update_order_result(supabase, order_id, response)
mark_signal(supabase, signal_id, "executed")
audit(
supabase,
"paper_order_executed",
signal_id=signal_id,
order_id=order_id,
payload=response,
)
print(f"Signal executed: {signal_id}")
else:
mark_order_failed(supabase, order_id, response)
mark_signal(supabase, signal_id, "failed")
audit(
supabase,
"paper_order_failed",
severity="error",
signal_id=signal_id,
order_id=order_id,
payload=response,
)
print(f"Signal failed: {signal_id} | http_status={response.get('http_status')}")
except Exception as exc:
print(f"ERROR: {exc}")
if order_id is not None:
try:
mark_order_failed(
supabase,
order_id,
{"ok": False, "error": str(exc)},
)
except Exception as order_exc:
print(f"ERROR writing failed order state: {order_exc}")
if signal_id is not None:
try:
mark_signal(supabase, signal_id, "failed")
except Exception as signal_exc:
print(f"ERROR writing failed signal state: {signal_exc}")
try:
audit(
supabase,
"runner_error",
severity="error",
signal_id=signal_id,
order_id=order_id,
payload={"error": str(exc)},
)
except Exception as audit_exc:
print(f"ERROR writing runner_error audit event: {audit_exc}")
time.sleep(RUNNER_POLL_SECONDS)
if __name__ == "__main__":
main()