@exagent/agent 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/{chunk-VDK4XPAC.js → chunk-WTECTX2Z.js} +31 -4
  2. package/dist/cli.js +212 -77
  3. package/dist/index.js +1 -1
  4. package/package.json +1 -1
  5. package/src/cli.ts +122 -3
  6. package/src/config.ts +19 -2
  7. package/src/runtime.ts +18 -2
  8. package/src/setup.ts +118 -67
  9. package/dist/chunk-25J5ZDKX.js +0 -5622
  10. package/dist/chunk-2ML4XS5X.js +0 -5626
  11. package/dist/chunk-2OKYNZ3J.js +0 -5622
  12. package/dist/chunk-2PAASZJN.js +0 -5132
  13. package/dist/chunk-2WAYVOLU.js +0 -5624
  14. package/dist/chunk-2XBVVY3I.js +0 -5621
  15. package/dist/chunk-37HCPVBZ.js +0 -2941
  16. package/dist/chunk-3DZAZBLF.js +0 -5652
  17. package/dist/chunk-3IXCKNSV.js +0 -5008
  18. package/dist/chunk-3MXFTRXB.js +0 -3326
  19. package/dist/chunk-4MURFLNJ.js +0 -5136
  20. package/dist/chunk-4UVMO6ZM.js +0 -6318
  21. package/dist/chunk-56YQROFU.js +0 -5639
  22. package/dist/chunk-5B3ZEGMD.js +0 -4330
  23. package/dist/chunk-5NU6FDDE.js +0 -6020
  24. package/dist/chunk-5WADKPJU.js +0 -1552
  25. package/dist/chunk-6LOIFEEV.js +0 -4895
  26. package/dist/chunk-6YIXPNL4.js +0 -5626
  27. package/dist/chunk-72HK2V74.js +0 -5224
  28. package/dist/chunk-7Q72QQIV.js +0 -4697
  29. package/dist/chunk-7V3XTBIF.js +0 -4896
  30. package/dist/chunk-A4CM4F7Q.js +0 -5633
  31. package/dist/chunk-ADXXR2MA.js +0 -4816
  32. package/dist/chunk-AG6CJPIC.js +0 -4895
  33. package/dist/chunk-AJPXHBTF.js +0 -4459
  34. package/dist/chunk-AQ6R37XV.js +0 -4809
  35. package/dist/chunk-AS4UEZMU.js +0 -5001
  36. package/dist/chunk-ASYMD22Y.js +0 -5624
  37. package/dist/chunk-AU4MCQCE.js +0 -5624
  38. package/dist/chunk-B4VHIITU.js +0 -5748
  39. package/dist/chunk-B6GVDNKQ.js +0 -5624
  40. package/dist/chunk-BCIAW6ZL.js +0 -5132
  41. package/dist/chunk-BJZ5PCG3.js +0 -5358
  42. package/dist/chunk-BS4J5QSM.js +0 -5622
  43. package/dist/chunk-BV2AUUX6.js +0 -2940
  44. package/dist/chunk-BWNSH2LK.js +0 -1574
  45. package/dist/chunk-C3GMBW3R.js +0 -5640
  46. package/dist/chunk-C6CVQGJ4.js +0 -5624
  47. package/dist/chunk-CGXKXNUJ.js +0 -5626
  48. package/dist/chunk-CIEZAYOU.js +0 -4701
  49. package/dist/chunk-CORZCEAQ.js +0 -5621
  50. package/dist/chunk-CS5LGZWP.js +0 -5357
  51. package/dist/chunk-CVT3KC24.js +0 -5624
  52. package/dist/chunk-D5MJ45R7.js +0 -3258
  53. package/dist/chunk-DSBRZ5DZ.js +0 -5624
  54. package/dist/chunk-E2X7JARQ.js +0 -4437
  55. package/dist/chunk-E3GY36ZP.js +0 -3258
  56. package/dist/chunk-E6NCIFKB.js +0 -4733
  57. package/dist/chunk-EOXLKW4D.js +0 -4895
  58. package/dist/chunk-FCI7LX4Q.js +0 -5624
  59. package/dist/chunk-FFJSKTOL.js +0 -4539
  60. package/dist/chunk-FOQYP3IB.js +0 -2950
  61. package/dist/chunk-GNEYTZDH.js +0 -4686
  62. package/dist/chunk-GPMXUMYH.js +0 -5991
  63. package/dist/chunk-GZWPAQPU.js +0 -4593
  64. package/dist/chunk-H5DXDKMX.js +0 -5619
  65. package/dist/chunk-HFQRTMS6.js +0 -3377
  66. package/dist/chunk-HQKRHX6Y.js +0 -5626
  67. package/dist/chunk-HTF3TNBY.js +0 -4834
  68. package/dist/chunk-IADSQBBY.js +0 -5523
  69. package/dist/chunk-IE2SXMZK.js +0 -4890
  70. package/dist/chunk-IGUQVJCB.js +0 -5622
  71. package/dist/chunk-IIREL7SL.js +0 -5615
  72. package/dist/chunk-IJK4EFTJ.js +0 -6043
  73. package/dist/chunk-J2MQ3Y5O.js +0 -5223
  74. package/dist/chunk-J3NG7AGT.js +0 -6047
  75. package/dist/chunk-JIBBZ3NV.js +0 -5132
  76. package/dist/chunk-JIPSBE6S.js +0 -5622
  77. package/dist/chunk-JPG755XK.js +0 -4589
  78. package/dist/chunk-JQBNL5GX.js +0 -5230
  79. package/dist/chunk-KS3F5WSX.js +0 -4831
  80. package/dist/chunk-KUYTQ4FR.js +0 -4808
  81. package/dist/chunk-KVP4CMJ5.js +0 -4711
  82. package/dist/chunk-LAR2I44B.js +0 -5626
  83. package/dist/chunk-LBTHSED2.js +0 -1531
  84. package/dist/chunk-M6OAMYVM.js +0 -5621
  85. package/dist/chunk-MFN5WWOY.js +0 -5132
  86. package/dist/chunk-MMTSKXLK.js +0 -5624
  87. package/dist/chunk-MPUSQLTH.js +0 -5626
  88. package/dist/chunk-MREXDTWL.js +0 -1555
  89. package/dist/chunk-MUEDKRFC.js +0 -5624
  90. package/dist/chunk-NOVPL2JH.js +0 -3327
  91. package/dist/chunk-NQIP4MHV.js +0 -4334
  92. package/dist/chunk-NXXKMYLS.js +0 -5624
  93. package/dist/chunk-OBYNZXNM.js +0 -4756
  94. package/dist/chunk-OFY4HBOJ.js +0 -5624
  95. package/dist/chunk-OJNUEZEK.js +0 -5602
  96. package/dist/chunk-OQCJOMUQ.js +0 -5624
  97. package/dist/chunk-OZH75GY6.js +0 -5132
  98. package/dist/chunk-P3IJVDMZ.js +0 -4700
  99. package/dist/chunk-PMYMYMBH.js +0 -4877
  100. package/dist/chunk-PRELNRVN.js +0 -5623
  101. package/dist/chunk-PSQUSNSI.js +0 -4703
  102. package/dist/chunk-QAIQ5IB6.js +0 -5624
  103. package/dist/chunk-QG22GADV.js +0 -6316
  104. package/dist/chunk-QNE2KGGK.js +0 -3315
  105. package/dist/chunk-RH7ZBSG4.js +0 -5132
  106. package/dist/chunk-RLD5MUCR.js +0 -5626
  107. package/dist/chunk-S42VEBNR.js +0 -3268
  108. package/dist/chunk-SEM6UXU4.js +0 -3324
  109. package/dist/chunk-SI5WP77M.js +0 -4430
  110. package/dist/chunk-SID4SQSY.js +0 -4837
  111. package/dist/chunk-SIELPKWF.js +0 -1558
  112. package/dist/chunk-SVBLY6QT.js +0 -5742
  113. package/dist/chunk-SVFTC5V2.js +0 -6021
  114. package/dist/chunk-SXHTX62B.js +0 -4823
  115. package/dist/chunk-T2YCEA5U.js +0 -4730
  116. package/dist/chunk-TARCHIOU.js +0 -4718
  117. package/dist/chunk-TDACLKD7.js +0 -5867
  118. package/dist/chunk-TGCBM3NP.js +0 -4890
  119. package/dist/chunk-TIWG6KAK.js +0 -4769
  120. package/dist/chunk-TKLKATVM.js +0 -1534
  121. package/dist/chunk-TSLZ4A5P.js +0 -5222
  122. package/dist/chunk-TWSDKORW.js +0 -4698
  123. package/dist/chunk-U5QHYVMJ.js +0 -3341
  124. package/dist/chunk-UAP5CTHB.js +0 -5985
  125. package/dist/chunk-UK6SEUWU.js +0 -3210
  126. package/dist/chunk-UKU5YO65.js +0 -5132
  127. package/dist/chunk-UOZQXP4Q.js +0 -5144
  128. package/dist/chunk-UPTN2TSS.js +0 -4727
  129. package/dist/chunk-UQT2APOE.js +0 -2944
  130. package/dist/chunk-V32QDZKW.js +0 -5132
  131. package/dist/chunk-VKY2CDCD.js +0 -5622
  132. package/dist/chunk-VUCSYMCY.js +0 -3323
  133. package/dist/chunk-VVLNBD5Y.js +0 -5132
  134. package/dist/chunk-W3TQ22O6.js +0 -4459
  135. package/dist/chunk-WA4DSGOM.js +0 -3355
  136. package/dist/chunk-WI6MIICK.js +0 -4687
  137. package/dist/chunk-XRHJLL74.js +0 -4893
  138. package/dist/chunk-XXWXEBJQ.js +0 -4885
  139. package/dist/chunk-YC6TH2H3.js +0 -5624
  140. package/dist/chunk-YDH6HCUJ.js +0 -5624
  141. package/dist/chunk-YJD35VKQ.js +0 -4890
  142. package/dist/chunk-ZBIQJBY7.js +0 -5620
  143. package/dist/chunk-ZKTSA2AE.js +0 -5629
  144. package/dist/chunk-ZKZZL3PE.js +0 -3379
  145. package/dist/chunk-ZM5KCPRK.js +0 -4541
  146. package/dist/chunk-ZTYPDSE3.js +0 -3258
@@ -1,1574 +0,0 @@
1
- // src/config.ts
2
- import { readFileSync, existsSync, writeFileSync } from "fs";
3
- import { z } from "zod";
4
- var configSchema = z.object({
5
- agentId: z.string(),
6
- apiUrl: z.string().url(),
7
- apiToken: z.string(),
8
- wallet: z.object({
9
- privateKey: z.string()
10
- }).optional(),
11
- llm: z.object({
12
- provider: z.enum(["openai", "anthropic", "google", "deepseek", "mistral", "groq", "together", "ollama"]),
13
- model: z.string().optional(),
14
- apiKey: z.string().optional(),
15
- endpoint: z.string().optional(),
16
- temperature: z.number().min(0).max(2).optional(),
17
- maxTokens: z.number().optional()
18
- }),
19
- strategy: z.object({
20
- file: z.string().optional(),
21
- template: z.string().optional()
22
- }),
23
- trading: z.object({
24
- mode: z.enum(["live", "paper"]).default("paper"),
25
- timeHorizon: z.enum(["intraday", "swing", "position"]).default("swing"),
26
- maxPositionSizeBps: z.number().min(100).max(1e4).default(2e3),
27
- maxDailyLossBps: z.number().min(0).max(1e4).default(500),
28
- maxConcurrentPositions: z.number().min(1).max(100).default(5),
29
- tradingIntervalMs: z.number().min(1e3).default(6e4),
30
- maxSlippageBps: z.number().min(10).max(1e3).default(100),
31
- minTradeValueUSD: z.number().min(0).default(10),
32
- initialCapitalUSD: z.number().optional()
33
- }),
34
- venues: z.object({
35
- hyperliquid_perp: z.object({
36
- enabled: z.boolean().default(false),
37
- apiUrl: z.string().default("https://api.hyperliquid.xyz"),
38
- wsUrl: z.string().default("wss://api.hyperliquid.xyz/ws"),
39
- maxLeverage: z.number().min(1).max(50).default(10),
40
- maxNotionalUSD: z.number().default(5e4),
41
- allowedInstruments: z.array(z.string()).optional()
42
- }).optional(),
43
- polymarket: z.object({
44
- enabled: z.boolean().default(false),
45
- clobApiUrl: z.string().default("https://clob.polymarket.com"),
46
- gammaApiUrl: z.string().default("https://gamma-api.polymarket.com"),
47
- maxNotionalUSD: z.number().default(1e3),
48
- maxTotalExposureUSD: z.number().default(5e3),
49
- allowedCategories: z.array(z.string()).optional()
50
- }).optional()
51
- }).optional(),
52
- relay: z.object({
53
- url: z.string(),
54
- heartbeatIntervalMs: z.number().default(3e4),
55
- reconnectMaxAttempts: z.number().default(50)
56
- })
57
- });
58
- function loadConfig(path = "agent-config.json") {
59
- if (!existsSync(path)) {
60
- throw new Error(`Config file not found: ${path}. Run 'exagent init' first.`);
61
- }
62
- const raw = readFileSync(path, "utf-8");
63
- let parsed;
64
- try {
65
- parsed = JSON.parse(raw);
66
- } catch {
67
- throw new Error(`Invalid JSON in ${path}`);
68
- }
69
- const config = parsed;
70
- const llm = config.llm || {};
71
- if (process.env.EXAGENT_LLM_PROVIDER) llm.provider = process.env.EXAGENT_LLM_PROVIDER;
72
- if (process.env.EXAGENT_LLM_MODEL) llm.model = process.env.EXAGENT_LLM_MODEL;
73
- if (process.env.EXAGENT_LLM_API_KEY) llm.apiKey = process.env.EXAGENT_LLM_API_KEY;
74
- if (process.env.EXAGENT_API_URL) config.apiUrl = process.env.EXAGENT_API_URL;
75
- if (process.env.EXAGENT_API_TOKEN) config.apiToken = process.env.EXAGENT_API_TOKEN;
76
- if (process.env.EXAGENT_WALLET_PRIVATE_KEY) {
77
- config.wallet = { privateKey: process.env.EXAGENT_WALLET_PRIVATE_KEY };
78
- }
79
- config.llm = llm;
80
- const result = configSchema.safeParse(config);
81
- if (!result.success) {
82
- const issues = result.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
83
- throw new Error(`Invalid config:
84
- ${issues}`);
85
- }
86
- return result.data;
87
- }
88
- function generateSampleConfig(agentId, apiUrl) {
89
- const config = {
90
- agentId,
91
- apiUrl,
92
- apiToken: "<your-jwt-token>",
93
- wallet: {
94
- privateKey: "<your-hex-private-key>"
95
- },
96
- llm: {
97
- provider: "openai",
98
- model: "gpt-4o",
99
- apiKey: "<your-api-key>"
100
- },
101
- strategy: {
102
- template: "momentum"
103
- },
104
- trading: {
105
- mode: "paper",
106
- timeHorizon: "swing",
107
- maxPositionSizeBps: 2e3,
108
- maxDailyLossBps: 500,
109
- maxConcurrentPositions: 5,
110
- tradingIntervalMs: 6e4,
111
- maxSlippageBps: 100,
112
- minTradeValueUSD: 10,
113
- initialCapitalUSD: 1e4
114
- },
115
- venues: {
116
- hyperliquid_perp: {
117
- enabled: false,
118
- apiUrl: "https://api.hyperliquid.xyz",
119
- wsUrl: "wss://api.hyperliquid.xyz/ws",
120
- maxLeverage: 10,
121
- maxNotionalUSD: 5e4
122
- },
123
- polymarket: {
124
- enabled: false,
125
- clobApiUrl: "https://clob.polymarket.com",
126
- gammaApiUrl: "https://gamma-api.polymarket.com",
127
- maxNotionalUSD: 1e3,
128
- maxTotalExposureUSD: 5e3
129
- }
130
- },
131
- relay: {
132
- url: apiUrl.replace(/^http/, "ws") + "/ws/agent",
133
- heartbeatIntervalMs: 3e4,
134
- reconnectMaxAttempts: 50
135
- }
136
- };
137
- return JSON.stringify(config, null, 2);
138
- }
139
- function writeSampleConfig(agentId, apiUrl, path = "agent-config.json") {
140
- writeFileSync(path, generateSampleConfig(agentId, apiUrl));
141
- }
142
-
143
- // src/relay.ts
144
- import WebSocket from "ws";
145
- var RelayClient = class {
146
- ws = null;
147
- config;
148
- heartbeatTimer = null;
149
- reconnectTimer = null;
150
- reconnectAttempts = 0;
151
- intentionalClose = false;
152
- authenticated = false;
153
- lastStatus = null;
154
- onCommand;
155
- onConnected;
156
- onDisconnected;
157
- constructor(config) {
158
- this.config = {
159
- url: config.url,
160
- agentId: config.agentId,
161
- token: config.token,
162
- heartbeatIntervalMs: config.heartbeatIntervalMs ?? 3e4,
163
- reconnectMaxAttempts: config.reconnectMaxAttempts ?? 50
164
- };
165
- this.onCommand = config.onCommand;
166
- this.onConnected = config.onConnected;
167
- this.onDisconnected = config.onDisconnected;
168
- }
169
- get isConnected() {
170
- return this.ws?.readyState === WebSocket.OPEN && this.authenticated;
171
- }
172
- async connect() {
173
- return new Promise((resolve2, reject) => {
174
- try {
175
- this.intentionalClose = false;
176
- this.ws = new WebSocket(this.config.url);
177
- const timeout = setTimeout(() => {
178
- if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
179
- this.ws.terminate();
180
- reject(new Error("Connection timeout (15s)"));
181
- }
182
- }, 15e3);
183
- this.ws.on("open", () => {
184
- clearTimeout(timeout);
185
- this.reconnectAttempts = 0;
186
- this.authenticate();
187
- });
188
- this.ws.on("message", (data) => {
189
- try {
190
- const msg = JSON.parse(data.toString());
191
- this.handleMessage(msg, resolve2);
192
- } catch {
193
- console.error("[relay] Failed to parse message");
194
- }
195
- });
196
- this.ws.on("close", () => {
197
- this.cleanup();
198
- this.onDisconnected?.();
199
- if (!this.intentionalClose) {
200
- this.scheduleReconnect();
201
- }
202
- });
203
- this.ws.on("error", (err) => {
204
- console.error("[relay] WebSocket error:", err.message);
205
- if (!this.authenticated) {
206
- clearTimeout(timeout);
207
- reject(err);
208
- }
209
- });
210
- } catch (err) {
211
- reject(err);
212
- }
213
- });
214
- }
215
- disconnect() {
216
- this.intentionalClose = true;
217
- this.cleanup();
218
- if (this.ws) {
219
- this.ws.close();
220
- this.ws = null;
221
- }
222
- }
223
- authenticate() {
224
- this.send({
225
- type: "auth",
226
- agentId: this.config.agentId,
227
- token: this.config.token
228
- });
229
- }
230
- handleMessage(msg, onAuth) {
231
- switch (msg.type) {
232
- case "auth_success":
233
- this.authenticated = true;
234
- this.startHeartbeat();
235
- this.onConnected?.();
236
- onAuth?.();
237
- console.log(`[relay] Authenticated as agent ${this.config.agentId}`);
238
- break;
239
- case "auth_error":
240
- console.error("[relay] Auth failed:", msg.error);
241
- this.disconnect();
242
- break;
243
- case "command":
244
- this.onCommand?.(msg.command);
245
- break;
246
- case "pong":
247
- break;
248
- }
249
- }
250
- send(msg) {
251
- if (this.ws?.readyState === WebSocket.OPEN) {
252
- this.ws.send(JSON.stringify(msg));
253
- }
254
- }
255
- sendHeartbeat(status) {
256
- this.lastStatus = status;
257
- this.send({
258
- type: "heartbeat",
259
- agentId: this.config.agentId,
260
- status,
261
- timestamp: Date.now()
262
- });
263
- }
264
- sendMessage(messageType, level, title, body, data) {
265
- this.send({
266
- type: "message",
267
- agentId: this.config.agentId,
268
- messageType,
269
- level,
270
- title,
271
- body,
272
- data,
273
- timestamp: Date.now()
274
- });
275
- }
276
- sendTradeSignal(signal) {
277
- this.send({
278
- type: "trade_signal",
279
- agentId: this.config.agentId,
280
- signal,
281
- timestamp: Date.now()
282
- });
283
- }
284
- startHeartbeat() {
285
- this.stopHeartbeat();
286
- this.heartbeatTimer = setInterval(() => {
287
- if (this.lastStatus) {
288
- this.sendHeartbeat(this.lastStatus);
289
- }
290
- }, this.config.heartbeatIntervalMs);
291
- }
292
- stopHeartbeat() {
293
- if (this.heartbeatTimer) {
294
- clearInterval(this.heartbeatTimer);
295
- this.heartbeatTimer = null;
296
- }
297
- }
298
- cleanup() {
299
- this.stopHeartbeat();
300
- this.authenticated = false;
301
- if (this.reconnectTimer) {
302
- clearTimeout(this.reconnectTimer);
303
- this.reconnectTimer = null;
304
- }
305
- }
306
- scheduleReconnect() {
307
- if (this.reconnectAttempts >= this.config.reconnectMaxAttempts) {
308
- console.error(`[relay] Max reconnect attempts (${this.config.reconnectMaxAttempts}) reached`);
309
- return;
310
- }
311
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts), 3e4);
312
- this.reconnectAttempts++;
313
- console.log(`[relay] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
314
- this.reconnectTimer = setTimeout(async () => {
315
- try {
316
- await this.connect();
317
- } catch (err) {
318
- console.error("[relay] Reconnect failed:", err.message);
319
- }
320
- }, delay);
321
- }
322
- };
323
-
324
- // src/signal.ts
325
- var SignalReporter = class {
326
- relay;
327
- constructor(relay) {
328
- this.relay = relay;
329
- }
330
- reportTrade(signal) {
331
- if (!this.relay.isConnected) {
332
- console.warn("[signal] Not connected to relay \u2014 trade signal queued locally");
333
- return;
334
- }
335
- this.relay.sendTradeSignal(signal);
336
- this.relay.sendMessage(
337
- "trade_executed",
338
- "success",
339
- `${signal.side.toUpperCase()} ${signal.symbol}`,
340
- `${signal.side} ${signal.size} ${signal.symbol} @ $${signal.price.toFixed(2)} on ${signal.venue}`,
341
- { signal }
342
- );
343
- }
344
- reportPerpFill(signal) {
345
- if (!this.relay.isConnected) return;
346
- this.relay.sendTradeSignal(signal);
347
- this.relay.sendMessage(
348
- "perp_fill",
349
- "success",
350
- `Perp ${signal.side.toUpperCase()} ${signal.symbol}`,
351
- `${signal.side} ${signal.size} ${signal.symbol} @ $${signal.price.toFixed(2)} (${signal.leverage ?? 1}x)`,
352
- { signal }
353
- );
354
- }
355
- reportPredictionFill(signal) {
356
- if (!this.relay.isConnected) return;
357
- this.relay.sendTradeSignal(signal);
358
- this.relay.sendMessage(
359
- "prediction_fill",
360
- "success",
361
- `Prediction ${signal.side.toUpperCase()}`,
362
- `${signal.side} $${signal.size.toFixed(2)} on ${signal.symbol} @ ${signal.price.toFixed(4)}`,
363
- { signal }
364
- );
365
- }
366
- reportError(title, body, data) {
367
- if (!this.relay.isConnected) return;
368
- this.relay.sendMessage("error", "error", title, body, data);
369
- }
370
- reportInfo(title, body, data) {
371
- if (!this.relay.isConnected) return;
372
- this.relay.sendMessage("info", "info", title, body, data);
373
- }
374
- };
375
-
376
- // src/store.ts
377
- import { readFileSync as readFileSync2, writeFileSync as writeFileSync2, mkdirSync, existsSync as existsSync2 } from "fs";
378
- import { dirname } from "path";
379
- var FileStore = class {
380
- data = {};
381
- filePath;
382
- constructor(filePath = "data/strategy-store.json") {
383
- this.filePath = filePath;
384
- this.load();
385
- }
386
- load() {
387
- try {
388
- if (existsSync2(this.filePath)) {
389
- const raw = readFileSync2(this.filePath, "utf-8");
390
- this.data = JSON.parse(raw);
391
- }
392
- } catch {
393
- this.data = {};
394
- }
395
- }
396
- flush() {
397
- const dir = dirname(this.filePath);
398
- if (!existsSync2(dir)) {
399
- mkdirSync(dir, { recursive: true });
400
- }
401
- writeFileSync2(this.filePath, JSON.stringify(this.data, null, 2));
402
- }
403
- get(key) {
404
- return this.data[key];
405
- }
406
- set(key, value) {
407
- this.data[key] = value;
408
- this.flush();
409
- }
410
- delete(key) {
411
- delete this.data[key];
412
- this.flush();
413
- }
414
- keys() {
415
- return Object.keys(this.data);
416
- }
417
- };
418
-
419
- // src/position-tracker.ts
420
- var BASE_ASSETS = /* @__PURE__ */ new Set(["ETH", "WETH", "USDC", "USDbC", "DAI", "USDT", "EURC"]);
421
- var PositionTracker = class {
422
- positions = /* @__PURE__ */ new Map();
423
- trades = [];
424
- realizedPnL = 0;
425
- store;
426
- constructor(store) {
427
- this.store = store;
428
- this.load();
429
- }
430
- load() {
431
- const saved = this.store.get("position_tracker");
432
- if (saved) {
433
- this.positions = new Map(saved.positions);
434
- this.trades = saved.trades;
435
- this.realizedPnL = saved.realizedPnL;
436
- }
437
- }
438
- save() {
439
- this.store.set("position_tracker", {
440
- positions: Array.from(this.positions.entries()),
441
- trades: this.trades.slice(-1e3),
442
- realizedPnL: this.realizedPnL
443
- });
444
- }
445
- recordBuy(token, quantity, price, fee, venue, chain, venueFillId) {
446
- if (BASE_ASSETS.has(token)) return;
447
- const existing = this.positions.get(token);
448
- if (existing) {
449
- const totalQty = existing.quantity + quantity;
450
- const totalCost = existing.costBasisPerUnit * existing.quantity + price * quantity;
451
- existing.costBasisPerUnit = totalCost / totalQty;
452
- existing.quantity = totalQty;
453
- } else {
454
- this.positions.set(token, {
455
- token,
456
- quantity,
457
- costBasisPerUnit: price,
458
- entryTimestamp: Date.now(),
459
- venue,
460
- chain
461
- });
462
- }
463
- this.trades.push({
464
- token,
465
- action: "buy",
466
- quantity,
467
- price,
468
- fee,
469
- timestamp: Date.now(),
470
- venue,
471
- chain,
472
- venueFillId
473
- });
474
- this.save();
475
- }
476
- recordSell(token, quantity, price, fee, venue, chain, venueFillId) {
477
- if (BASE_ASSETS.has(token)) return;
478
- const existing = this.positions.get(token);
479
- if (existing) {
480
- const pnl = (price - existing.costBasisPerUnit) * quantity - fee;
481
- this.realizedPnL += pnl;
482
- existing.quantity -= quantity;
483
- if (existing.quantity <= 1e-6) {
484
- this.positions.delete(token);
485
- }
486
- }
487
- this.trades.push({
488
- token,
489
- action: "sell",
490
- quantity,
491
- price,
492
- fee,
493
- timestamp: Date.now(),
494
- venue,
495
- chain,
496
- venueFillId
497
- });
498
- this.save();
499
- }
500
- getSummary(prices) {
501
- let totalUnrealizedPnL = 0;
502
- const openPositions = Array.from(this.positions.values());
503
- for (const pos of openPositions) {
504
- const currentPrice = prices[pos.token];
505
- if (currentPrice) {
506
- totalUnrealizedPnL += (currentPrice - pos.costBasisPerUnit) * pos.quantity;
507
- }
508
- }
509
- return {
510
- openPositions,
511
- totalUnrealizedPnL,
512
- totalRealizedPnL: this.realizedPnL
513
- };
514
- }
515
- getPositions() {
516
- return Array.from(this.positions.values());
517
- }
518
- getTrades(limit) {
519
- if (limit) return this.trades.slice(-limit);
520
- return [...this.trades];
521
- }
522
- getRealizedPnL() {
523
- return this.realizedPnL;
524
- }
525
- reset() {
526
- this.positions.clear();
527
- this.trades = [];
528
- this.realizedPnL = 0;
529
- this.save();
530
- }
531
- };
532
-
533
- // src/llm/base.ts
534
- var BaseLLMAdapter = class {
535
- config;
536
- constructor(config) {
537
- this.config = config;
538
- }
539
- getTemperature() {
540
- return this.config.temperature ?? 0.7;
541
- }
542
- getMaxTokens() {
543
- return this.config.maxTokens ?? 4096;
544
- }
545
- };
546
-
547
- // src/llm/openai.ts
548
- var OpenAIAdapter = class extends BaseLLMAdapter {
549
- endpoint;
550
- constructor(config) {
551
- super(config);
552
- this.endpoint = config.endpoint || "https://api.openai.com/v1";
553
- }
554
- async chat(messages) {
555
- const res = await fetch(`${this.endpoint}/chat/completions`, {
556
- method: "POST",
557
- headers: {
558
- "Content-Type": "application/json",
559
- Authorization: `Bearer ${this.config.apiKey}`
560
- },
561
- body: JSON.stringify({
562
- model: this.config.model || "gpt-4o",
563
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
564
- temperature: this.getTemperature(),
565
- max_tokens: this.getMaxTokens()
566
- })
567
- });
568
- if (!res.ok) {
569
- const body = await res.text();
570
- throw new Error(`OpenAI API error ${res.status}: ${body}`);
571
- }
572
- const data = await res.json();
573
- return {
574
- content: data.choices[0]?.message?.content || "",
575
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
576
- };
577
- }
578
- getMetadata() {
579
- return {
580
- provider: "openai",
581
- model: this.config.model || "gpt-4o"
582
- };
583
- }
584
- };
585
-
586
- // src/llm/anthropic.ts
587
- var AnthropicAdapter = class extends BaseLLMAdapter {
588
- endpoint;
589
- constructor(config) {
590
- super(config);
591
- this.endpoint = config.endpoint || "https://api.anthropic.com";
592
- }
593
- async chat(messages) {
594
- const systemMessage = messages.find((m) => m.role === "system");
595
- const nonSystemMessages = messages.filter((m) => m.role !== "system");
596
- const body = {
597
- model: this.config.model || "claude-sonnet-4-20250514",
598
- messages: nonSystemMessages.map((m) => ({ role: m.role, content: m.content })),
599
- max_tokens: this.getMaxTokens(),
600
- temperature: this.getTemperature()
601
- };
602
- if (systemMessage) {
603
- body.system = systemMessage.content;
604
- }
605
- const res = await fetch(`${this.endpoint}/v1/messages`, {
606
- method: "POST",
607
- headers: {
608
- "Content-Type": "application/json",
609
- "x-api-key": this.config.apiKey || "",
610
- "anthropic-version": "2023-06-01"
611
- },
612
- body: JSON.stringify(body)
613
- });
614
- if (!res.ok) {
615
- const text = await res.text();
616
- throw new Error(`Anthropic API error ${res.status}: ${text}`);
617
- }
618
- const data = await res.json();
619
- const textContent = data.content.find((c) => c.type === "text");
620
- return {
621
- content: textContent?.text || "",
622
- tokens: data.usage ? { input: data.usage.input_tokens, output: data.usage.output_tokens } : void 0
623
- };
624
- }
625
- getMetadata() {
626
- return {
627
- provider: "anthropic",
628
- model: this.config.model || "claude-sonnet-4-20250514"
629
- };
630
- }
631
- };
632
-
633
- // src/llm/google.ts
634
- var GoogleAdapter = class extends BaseLLMAdapter {
635
- constructor(config) {
636
- super(config);
637
- }
638
- async chat(messages) {
639
- const model = this.config.model || "gemini-2.5-flash";
640
- const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${this.config.apiKey}`;
641
- const systemMessage = messages.find((m) => m.role === "system");
642
- const nonSystemMessages = messages.filter((m) => m.role !== "system");
643
- const body = {
644
- contents: nonSystemMessages.map((m) => ({
645
- role: m.role === "assistant" ? "model" : "user",
646
- parts: [{ text: m.content }]
647
- })),
648
- generationConfig: {
649
- temperature: this.getTemperature(),
650
- maxOutputTokens: this.getMaxTokens()
651
- }
652
- };
653
- if (systemMessage) {
654
- body.systemInstruction = { parts: [{ text: systemMessage.content }] };
655
- }
656
- const res = await fetch(url, {
657
- method: "POST",
658
- headers: { "Content-Type": "application/json" },
659
- body: JSON.stringify(body)
660
- });
661
- if (!res.ok) {
662
- const text2 = await res.text();
663
- throw new Error(`Google AI error ${res.status}: ${text2}`);
664
- }
665
- const data = await res.json();
666
- const text = data.candidates[0]?.content?.parts[0]?.text || "";
667
- return {
668
- content: text,
669
- tokens: data.usageMetadata ? { input: data.usageMetadata.promptTokenCount, output: data.usageMetadata.candidatesTokenCount } : void 0
670
- };
671
- }
672
- getMetadata() {
673
- return {
674
- provider: "google",
675
- model: this.config.model || "gemini-2.5-flash"
676
- };
677
- }
678
- };
679
-
680
- // src/llm/deepseek.ts
681
- var DeepSeekAdapter = class extends BaseLLMAdapter {
682
- constructor(config) {
683
- super(config);
684
- }
685
- async chat(messages) {
686
- const res = await fetch("https://api.deepseek.com/chat/completions", {
687
- method: "POST",
688
- headers: {
689
- "Content-Type": "application/json",
690
- Authorization: `Bearer ${this.config.apiKey}`
691
- },
692
- body: JSON.stringify({
693
- model: this.config.model || "deepseek-chat",
694
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
695
- temperature: this.getTemperature(),
696
- max_tokens: this.getMaxTokens()
697
- })
698
- });
699
- if (!res.ok) {
700
- const body = await res.text();
701
- throw new Error(`DeepSeek API error ${res.status}: ${body}`);
702
- }
703
- const data = await res.json();
704
- return {
705
- content: data.choices[0]?.message?.content || "",
706
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
707
- };
708
- }
709
- getMetadata() {
710
- return {
711
- provider: "deepseek",
712
- model: this.config.model || "deepseek-chat"
713
- };
714
- }
715
- };
716
-
717
- // src/llm/mistral.ts
718
- var MistralAdapter = class extends BaseLLMAdapter {
719
- constructor(config) {
720
- super(config);
721
- }
722
- async chat(messages) {
723
- const res = await fetch("https://api.mistral.ai/v1/chat/completions", {
724
- method: "POST",
725
- headers: {
726
- "Content-Type": "application/json",
727
- Authorization: `Bearer ${this.config.apiKey}`
728
- },
729
- body: JSON.stringify({
730
- model: this.config.model || "mistral-large-latest",
731
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
732
- temperature: this.getTemperature(),
733
- max_tokens: this.getMaxTokens()
734
- })
735
- });
736
- if (!res.ok) {
737
- const body = await res.text();
738
- throw new Error(`Mistral API error ${res.status}: ${body}`);
739
- }
740
- const data = await res.json();
741
- return {
742
- content: data.choices[0]?.message?.content || "",
743
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
744
- };
745
- }
746
- getMetadata() {
747
- return {
748
- provider: "mistral",
749
- model: this.config.model || "mistral-large-latest"
750
- };
751
- }
752
- };
753
-
754
- // src/llm/groq.ts
755
- var GroqAdapter = class extends BaseLLMAdapter {
756
- constructor(config) {
757
- super(config);
758
- }
759
- async chat(messages) {
760
- const res = await fetch("https://api.groq.com/openai/v1/chat/completions", {
761
- method: "POST",
762
- headers: {
763
- "Content-Type": "application/json",
764
- Authorization: `Bearer ${this.config.apiKey}`
765
- },
766
- body: JSON.stringify({
767
- model: this.config.model || "llama-3.3-70b-versatile",
768
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
769
- temperature: this.getTemperature(),
770
- max_tokens: this.getMaxTokens()
771
- })
772
- });
773
- if (!res.ok) {
774
- const body = await res.text();
775
- throw new Error(`Groq API error ${res.status}: ${body}`);
776
- }
777
- const data = await res.json();
778
- return {
779
- content: data.choices[0]?.message?.content || "",
780
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
781
- };
782
- }
783
- getMetadata() {
784
- return {
785
- provider: "groq",
786
- model: this.config.model || "llama-3.3-70b-versatile"
787
- };
788
- }
789
- };
790
-
791
- // src/llm/together.ts
792
- var TogetherAdapter = class extends BaseLLMAdapter {
793
- constructor(config) {
794
- super(config);
795
- }
796
- async chat(messages) {
797
- const res = await fetch("https://api.together.xyz/v1/chat/completions", {
798
- method: "POST",
799
- headers: {
800
- "Content-Type": "application/json",
801
- Authorization: `Bearer ${this.config.apiKey}`
802
- },
803
- body: JSON.stringify({
804
- model: this.config.model || "meta-llama/Llama-3.3-70B-Instruct-Turbo",
805
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
806
- temperature: this.getTemperature(),
807
- max_tokens: this.getMaxTokens()
808
- })
809
- });
810
- if (!res.ok) {
811
- const body = await res.text();
812
- throw new Error(`Together API error ${res.status}: ${body}`);
813
- }
814
- const data = await res.json();
815
- return {
816
- content: data.choices[0]?.message?.content || "",
817
- tokens: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0
818
- };
819
- }
820
- getMetadata() {
821
- return {
822
- provider: "together",
823
- model: this.config.model || "meta-llama/Llama-3.3-70B-Instruct-Turbo"
824
- };
825
- }
826
- };
827
-
828
- // src/llm/ollama.ts
829
- var OllamaAdapter = class extends BaseLLMAdapter {
830
- endpoint;
831
- constructor(config) {
832
- super(config);
833
- this.endpoint = config.endpoint || "http://localhost:11434";
834
- }
835
- async chat(messages) {
836
- const res = await fetch(`${this.endpoint}/api/chat`, {
837
- method: "POST",
838
- headers: { "Content-Type": "application/json" },
839
- body: JSON.stringify({
840
- model: this.config.model || "llama3.3",
841
- messages: messages.map((m) => ({ role: m.role, content: m.content })),
842
- stream: false,
843
- options: {
844
- temperature: this.getTemperature(),
845
- num_predict: this.getMaxTokens()
846
- }
847
- })
848
- });
849
- if (!res.ok) {
850
- const body = await res.text();
851
- throw new Error(`Ollama error ${res.status}: ${body}`);
852
- }
853
- const data = await res.json();
854
- return {
855
- content: data.message?.content || "",
856
- tokens: data.prompt_eval_count ? { input: data.prompt_eval_count, output: data.eval_count || 0 } : void 0
857
- };
858
- }
859
- getMetadata() {
860
- return {
861
- provider: "ollama",
862
- model: this.config.model || "llama3.3"
863
- };
864
- }
865
- };
866
-
867
- // src/llm/index.ts
868
- function createLLMAdapter(config) {
869
- switch (config.provider) {
870
- case "openai":
871
- return new OpenAIAdapter(config);
872
- case "anthropic":
873
- return new AnthropicAdapter(config);
874
- case "google":
875
- return new GoogleAdapter(config);
876
- case "deepseek":
877
- return new DeepSeekAdapter(config);
878
- case "mistral":
879
- return new MistralAdapter(config);
880
- case "groq":
881
- return new GroqAdapter(config);
882
- case "together":
883
- return new TogetherAdapter(config);
884
- case "ollama":
885
- return new OllamaAdapter(config);
886
- default:
887
- throw new Error(`Unknown LLM provider: ${config.provider}`);
888
- }
889
- }
890
-
891
- // src/strategy/templates.ts
892
- var templates = [
893
- {
894
- id: "momentum",
895
- name: "Momentum Trader",
896
- description: "Identifies tokens with strong upward price momentum and rides the trend. Uses LLM to analyze price action and market sentiment.",
897
- category: "momentum",
898
- venues: ["hyperliquid_perp", "hyperliquid_spot"],
899
- riskLevel: "moderate",
900
- systemPrompt: `You are a momentum trading agent. Analyze the provided market data and identify tokens with strong upward momentum.
901
-
902
- Rules:
903
- - Only trade tokens with clear directional momentum (avoid choppy markets)
904
- - Use trailing stops to protect gains
905
- - Size positions based on conviction (higher confidence = larger position)
906
- - Cut losses quickly if momentum reverses
907
- - Consider volume as confirmation of momentum
908
-
909
- Return a JSON array of trade signals.`,
910
- code: `
911
- const prices = context.market.getPrices();
912
- const positions = context.position.openPositions;
913
-
914
- const messages = [
915
- { role: 'system', content: 'You are a momentum trading agent. Analyze market data and return trade signals as a JSON array. Each signal: { symbol, side: "buy"|"sell", confidence: 0-1, reasoning }. Return [] if no opportunities.' },
916
- { role: 'user', content: 'Current prices: ' + JSON.stringify(prices) + '\\nOpen positions: ' + JSON.stringify(positions.map(p => p.token)) + '\\nAnalyze for momentum opportunities.' }
917
- ];
918
-
919
- const response = await context.llm.chat(messages);
920
- try {
921
- const signals = JSON.parse(response.content);
922
- return Array.isArray(signals) ? signals : [];
923
- } catch {
924
- return [];
925
- }
926
- `
927
- },
928
- {
929
- id: "value",
930
- name: "Value Investor",
931
- description: "Identifies undervalued tokens based on fundamental analysis. Buys dips and holds for mean reversion.",
932
- category: "value",
933
- venues: ["hyperliquid_spot"],
934
- riskLevel: "conservative",
935
- systemPrompt: `You are a value investing agent. Identify tokens trading below their intrinsic value.
936
-
937
- Rules:
938
- - Focus on established tokens with strong fundamentals
939
- - Buy on significant dips (>10% from recent highs)
940
- - Hold positions longer (swing/position timeframe)
941
- - Avoid chasing pumps
942
- - Diversify across sectors
943
-
944
- Return a JSON array of trade signals.`,
945
- code: `
946
- const prices = context.market.getPrices();
947
- const positions = context.position.openPositions;
948
-
949
- const messages = [
950
- { role: 'system', content: 'You are a value investing agent. Identify undervalued tokens. Return trade signals as JSON array: { symbol, side: "buy"|"sell", confidence: 0-1, reasoning }. Return [] if nothing is compelling.' },
951
- { role: 'user', content: 'Current prices: ' + JSON.stringify(prices) + '\\nPositions: ' + JSON.stringify(positions.map(p => ({ token: p.token, entry: p.costBasisPerUnit }))) + '\\nLook for value opportunities.' }
952
- ];
953
-
954
- const response = await context.llm.chat(messages);
955
- try {
956
- const signals = JSON.parse(response.content);
957
- return Array.isArray(signals) ? signals : [];
958
- } catch {
959
- return [];
960
- }
961
- `
962
- },
963
- {
964
- id: "arbitrage",
965
- name: "Arbitrage Hunter",
966
- description: "Scans for price discrepancies across venues and chains. Executes quickly to capture spreads.",
967
- category: "arbitrage",
968
- venues: ["hyperliquid_perp", "hyperliquid_spot", "uniswap", "aerodrome"],
969
- riskLevel: "aggressive",
970
- systemPrompt: `You are an arbitrage agent. Find price discrepancies between venues.
971
-
972
- Rules:
973
- - Speed is critical \u2014 execute quickly before spreads close
974
- - Account for fees and slippage in profitability calculations
975
- - Only trade when net profit > 0.5% after all costs
976
- - Monitor cross-chain opportunities (CEX vs DEX spreads)
977
-
978
- Return a JSON array of trade signals.`,
979
- code: `
980
- const prices = context.market.getPrices();
981
-
982
- const messages = [
983
- { role: 'system', content: 'You are an arbitrage agent. Find price discrepancies. Return trade signals as JSON array: { symbol, side: "buy"|"sell", venue, confidence: 0-1, reasoning }. Return [] if no arb opportunities.' },
984
- { role: 'user', content: 'Market prices: ' + JSON.stringify(prices) + '\\nScan for cross-venue arbitrage opportunities.' }
985
- ];
986
-
987
- const response = await context.llm.chat(messages);
988
- try {
989
- const signals = JSON.parse(response.content);
990
- return Array.isArray(signals) ? signals : [];
991
- } catch {
992
- return [];
993
- }
994
- `
995
- },
996
- {
997
- id: "hold",
998
- name: "Hold (No Trading)",
999
- description: "Passive strategy that makes no trades. Useful for monitoring only.",
1000
- category: "custom",
1001
- venues: [],
1002
- riskLevel: "conservative",
1003
- systemPrompt: "",
1004
- code: `return [];`
1005
- }
1006
- ];
1007
- function getTemplate(id) {
1008
- return templates.find((t) => t.id === id);
1009
- }
1010
- function listTemplates() {
1011
- return [...templates];
1012
- }
1013
-
1014
- // src/strategy/loader.ts
1015
- import { existsSync as existsSync3 } from "fs";
1016
- import { resolve } from "path";
1017
- async function loadStrategy(config) {
1018
- if (config.file) {
1019
- return loadFromFile(config.file);
1020
- }
1021
- if (config.template) {
1022
- const template = getTemplate(config.template);
1023
- if (!template) {
1024
- throw new Error(`Unknown strategy template: ${config.template}. Available: momentum, value, arbitrage, hold`);
1025
- }
1026
- return loadFromCode(template.code);
1027
- }
1028
- return holdStrategy;
1029
- }
1030
- async function loadFromFile(filePath) {
1031
- const resolved = resolve(filePath);
1032
- if (!existsSync3(resolved)) {
1033
- throw new Error(`Strategy file not found: ${resolved}`);
1034
- }
1035
- try {
1036
- const mod = await import(resolved);
1037
- const fn = mod.default || mod.strategy;
1038
- if (typeof fn !== "function") {
1039
- throw new Error(`Strategy file must export a default function or 'strategy' function`);
1040
- }
1041
- return fn;
1042
- } catch (err) {
1043
- throw new Error(`Failed to load strategy from ${resolved}: ${err.message}`);
1044
- }
1045
- }
1046
- async function loadFromCode(code) {
1047
- const AsyncFunction = Object.getPrototypeOf(async function() {
1048
- }).constructor;
1049
- const fn = new AsyncFunction("context", code);
1050
- return fn;
1051
- }
1052
- var holdStrategy = async (_context) => {
1053
- return [];
1054
- };
1055
-
1056
- // src/trading/risk.ts
1057
- var RiskManager = class {
1058
- params;
1059
- dailyPnL = 0;
1060
- dailyFees = 0;
1061
- lastResetDate = "";
1062
- initialCapitalUSD;
1063
- constructor(params, initialCapitalUSD = 1e4) {
1064
- this.params = params;
1065
- this.initialCapitalUSD = initialCapitalUSD;
1066
- this.resetIfNewDay();
1067
- }
1068
- filterSignals(signals, market, openPositionCount) {
1069
- this.resetIfNewDay();
1070
- if (this.isDailyLossLimitHit()) {
1071
- console.log("[risk] Daily loss limit hit \u2014 blocking all trades");
1072
- return [];
1073
- }
1074
- return signals.filter((signal) => this.validateSignal(signal, market, openPositionCount));
1075
- }
1076
- validateSignal(signal, market, openPositionCount) {
1077
- const threshold = this.params.confidenceThreshold ?? 0.5;
1078
- if (signal.confidence !== void 0 && signal.confidence < threshold) {
1079
- console.log(`[risk] Blocked ${signal.symbol}: confidence ${signal.confidence} < ${threshold}`);
1080
- return false;
1081
- }
1082
- const tradeValue = signal.size * signal.price;
1083
- const maxPositionValue = this.params.maxPositionSizeBps / 1e4 * this.initialCapitalUSD;
1084
- if (tradeValue > maxPositionValue) {
1085
- console.log(`[risk] Blocked ${signal.symbol}: trade $${tradeValue.toFixed(0)} > max $${maxPositionValue.toFixed(0)}`);
1086
- return false;
1087
- }
1088
- if (tradeValue < this.params.minTradeValueUSD) {
1089
- console.log(`[risk] Blocked ${signal.symbol}: trade $${tradeValue.toFixed(2)} < min $${this.params.minTradeValueUSD}`);
1090
- return false;
1091
- }
1092
- if ((signal.side === "buy" || signal.side === "long") && openPositionCount >= this.params.maxConcurrentPositions) {
1093
- console.log(`[risk] Blocked ${signal.symbol}: ${openPositionCount} positions >= max ${this.params.maxConcurrentPositions}`);
1094
- return false;
1095
- }
1096
- if (signal.orderType === "market") {
1097
- const currentPrice = market.getPrice(signal.symbol);
1098
- if (currentPrice) {
1099
- const slippageBps = Math.abs(signal.price - currentPrice) / currentPrice * 1e4;
1100
- if (slippageBps > this.params.maxSlippageBps) {
1101
- console.log(`[risk] Blocked ${signal.symbol}: slippage ${slippageBps.toFixed(0)}bps > max ${this.params.maxSlippageBps}bps`);
1102
- return false;
1103
- }
1104
- }
1105
- }
1106
- return true;
1107
- }
1108
- recordTrade(pnl, fee) {
1109
- this.dailyPnL += pnl;
1110
- this.dailyFees += fee;
1111
- }
1112
- isDailyLossLimitHit() {
1113
- const limit = this.params.maxDailyLossBps / 1e4 * this.initialCapitalUSD;
1114
- return this.dailyPnL < -limit;
1115
- }
1116
- getDailyPnL() {
1117
- return this.dailyPnL;
1118
- }
1119
- getDailyLossLimit() {
1120
- return this.params.maxDailyLossBps / 1e4 * this.initialCapitalUSD;
1121
- }
1122
- resetIfNewDay() {
1123
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1124
- if (today !== this.lastResetDate) {
1125
- this.dailyPnL = 0;
1126
- this.dailyFees = 0;
1127
- this.lastResetDate = today;
1128
- }
1129
- }
1130
- };
1131
-
1132
- // src/trading/market.ts
1133
- var MarketDataService = class {
1134
- prices = {};
1135
- lastFetch = 0;
1136
- cacheTTL;
1137
- constructor(cacheTTLMs = 3e4) {
1138
- this.cacheTTL = cacheTTLMs;
1139
- }
1140
- async refreshPrices(symbols) {
1141
- if (symbols.length === 0) return this.prices;
1142
- const now = Date.now();
1143
- if (now - this.lastFetch < this.cacheTTL && Object.keys(this.prices).length > 0) {
1144
- return this.prices;
1145
- }
1146
- try {
1147
- const ids = symbols.map((s) => s.toLowerCase()).join(",");
1148
- const res = await fetch(
1149
- `https://api.coingecko.com/api/v3/simple/price?ids=${ids}&vs_currencies=usd`
1150
- );
1151
- if (res.ok) {
1152
- const data = await res.json();
1153
- for (const [id, price] of Object.entries(data)) {
1154
- this.prices[id.toUpperCase()] = price.usd;
1155
- }
1156
- this.lastFetch = now;
1157
- }
1158
- } catch (err) {
1159
- console.warn("[market] Price fetch failed:", err.message);
1160
- }
1161
- return this.prices;
1162
- }
1163
- getPrice(symbol) {
1164
- return this.prices[symbol.toUpperCase()];
1165
- }
1166
- getPrices() {
1167
- return { ...this.prices };
1168
- }
1169
- setPrice(symbol, price) {
1170
- this.prices[symbol.toUpperCase()] = price;
1171
- }
1172
- setPrices(prices) {
1173
- for (const [symbol, price] of Object.entries(prices)) {
1174
- this.prices[symbol.toUpperCase()] = price;
1175
- }
1176
- }
1177
- getOHLCV(_symbol, _timeframe) {
1178
- return [];
1179
- }
1180
- };
1181
-
1182
- // src/paper/executor.ts
1183
- import { randomUUID } from "crypto";
1184
- var PaperExecutor = class {
1185
- cash;
1186
- positions = /* @__PURE__ */ new Map();
1187
- trades = [];
1188
- equityCurve = [];
1189
- slippageBps;
1190
- feeRate;
1191
- peakEquity;
1192
- maxDrawdown = 0;
1193
- constructor(initialCash = 1e4, slippageBps = 50, feeRate = 2e-3) {
1194
- this.cash = initialCash;
1195
- this.slippageBps = slippageBps;
1196
- this.feeRate = feeRate;
1197
- this.peakEquity = initialCash;
1198
- this.recordEquity();
1199
- }
1200
- execute(signal, market) {
1201
- const marketPrice = market.getPrice(signal.symbol);
1202
- if (!marketPrice) {
1203
- console.warn(`[paper] No price for ${signal.symbol}`);
1204
- return null;
1205
- }
1206
- const isBuy = signal.side === "buy" || signal.side === "long";
1207
- const slippage = this.slippageBps / 1e4 * marketPrice;
1208
- const executedPrice = isBuy ? marketPrice + slippage : marketPrice - slippage;
1209
- const fee = signal.size * executedPrice * this.feeRate;
1210
- if (isBuy) {
1211
- const totalCost = signal.size * executedPrice + fee;
1212
- if (totalCost > this.cash) {
1213
- console.warn(`[paper] Insufficient funds: need $${totalCost.toFixed(2)}, have $${this.cash.toFixed(2)}`);
1214
- return null;
1215
- }
1216
- this.cash -= totalCost;
1217
- const existing = this.positions.get(signal.symbol);
1218
- if (existing) {
1219
- const totalQty = existing.quantity + signal.size;
1220
- existing.avgPrice = (existing.avgPrice * existing.quantity + executedPrice * signal.size) / totalQty;
1221
- existing.quantity = totalQty;
1222
- } else {
1223
- this.positions.set(signal.symbol, { quantity: signal.size, avgPrice: executedPrice });
1224
- }
1225
- } else {
1226
- const existing = this.positions.get(signal.symbol);
1227
- if (!existing || existing.quantity < signal.size) {
1228
- console.warn(`[paper] No position to sell: ${signal.symbol}`);
1229
- return null;
1230
- }
1231
- const proceeds = signal.size * executedPrice - fee;
1232
- this.cash += proceeds;
1233
- existing.quantity -= signal.size;
1234
- if (existing.quantity <= 1e-6) {
1235
- this.positions.delete(signal.symbol);
1236
- }
1237
- }
1238
- const trade = {
1239
- id: randomUUID(),
1240
- symbol: signal.symbol,
1241
- side: isBuy ? "buy" : "sell",
1242
- size: signal.size,
1243
- entryPrice: executedPrice,
1244
- fee,
1245
- timestamp: Date.now(),
1246
- venue: `paper_${signal.venue}`
1247
- };
1248
- this.trades.push(trade);
1249
- this.recordEquity();
1250
- return trade;
1251
- }
1252
- recordEquity() {
1253
- const equity = this.getEquity();
1254
- this.equityCurve.push({ timestamp: Date.now(), equity });
1255
- if (equity > this.peakEquity) this.peakEquity = equity;
1256
- const drawdown = (this.peakEquity - equity) / this.peakEquity;
1257
- if (drawdown > this.maxDrawdown) this.maxDrawdown = drawdown;
1258
- }
1259
- getEquity() {
1260
- let positionValue = 0;
1261
- for (const [, pos] of this.positions) {
1262
- positionValue += pos.quantity * pos.avgPrice;
1263
- }
1264
- return this.cash + positionValue;
1265
- }
1266
- getCash() {
1267
- return this.cash;
1268
- }
1269
- getPositions() {
1270
- return new Map(this.positions);
1271
- }
1272
- getTrades() {
1273
- return [...this.trades];
1274
- }
1275
- getEquityCurve() {
1276
- return [...this.equityCurve];
1277
- }
1278
- getMetrics() {
1279
- const initialEquity = this.equityCurve[0]?.equity || 0;
1280
- const currentEquity = this.getEquity();
1281
- const totalReturn = initialEquity > 0 ? (currentEquity - initialEquity) / initialEquity : 0;
1282
- const dailyReturns = this.calculateDailyReturns();
1283
- const sharpeRatio = this.calculateSharpe(dailyReturns);
1284
- let wins = 0;
1285
- let losses = 0;
1286
- let grossProfit = 0;
1287
- let grossLoss = 0;
1288
- const sellTrades = this.trades.filter((t) => t.side === "sell");
1289
- for (const sell of sellTrades) {
1290
- const buyTrades = this.trades.filter((t) => t.side === "buy" && t.symbol === sell.symbol);
1291
- const avgEntry = buyTrades.reduce((sum, t) => sum + t.entryPrice, 0) / (buyTrades.length || 1);
1292
- const pnl = (sell.entryPrice - avgEntry) * sell.size - sell.fee;
1293
- if (pnl > 0) {
1294
- wins++;
1295
- grossProfit += pnl;
1296
- } else {
1297
- losses++;
1298
- grossLoss += Math.abs(pnl);
1299
- }
1300
- }
1301
- return {
1302
- totalReturn,
1303
- sharpeRatio,
1304
- maxDrawdown: this.maxDrawdown,
1305
- winRate: wins + losses > 0 ? wins / (wins + losses) : 0,
1306
- profitFactor: grossLoss > 0 ? grossProfit / grossLoss : grossProfit > 0 ? Infinity : 0,
1307
- totalTrades: this.trades.length
1308
- };
1309
- }
1310
- calculateDailyReturns() {
1311
- if (this.equityCurve.length < 2) return [];
1312
- const dailyEquity = /* @__PURE__ */ new Map();
1313
- for (const point of this.equityCurve) {
1314
- const date = new Date(point.timestamp).toISOString().slice(0, 10);
1315
- dailyEquity.set(date, point.equity);
1316
- }
1317
- const dates = Array.from(dailyEquity.keys()).sort();
1318
- const returns = [];
1319
- for (let i = 1; i < dates.length; i++) {
1320
- const prev = dailyEquity.get(dates[i - 1]);
1321
- const curr = dailyEquity.get(dates[i]);
1322
- if (prev > 0) returns.push((curr - prev) / prev);
1323
- }
1324
- return returns;
1325
- }
1326
- calculateSharpe(returns) {
1327
- if (returns.length < 2) return 0;
1328
- const mean = returns.reduce((a, b) => a + b, 0) / returns.length;
1329
- const variance = returns.reduce((sum, r) => sum + (r - mean) ** 2, 0) / (returns.length - 1);
1330
- const std = Math.sqrt(variance);
1331
- if (std === 0) return 0;
1332
- return mean / std * Math.sqrt(365);
1333
- }
1334
- };
1335
-
1336
- // src/runtime.ts
1337
- var SDK_VERSION = "0.1.0";
1338
- var AgentRuntime = class {
1339
- config;
1340
- relay;
1341
- signal;
1342
- store;
1343
- positions;
1344
- llm;
1345
- strategy = null;
1346
- risk;
1347
- market;
1348
- paper = null;
1349
- mode = "idle";
1350
- cycleCount = 0;
1351
- lastCycleAt = 0;
1352
- tradingInterval = null;
1353
- running = false;
1354
- constructor(config) {
1355
- this.config = config;
1356
- this.store = new FileStore(`data/${config.agentId}-store.json`);
1357
- this.positions = new PositionTracker(this.store);
1358
- this.market = new MarketDataService();
1359
- this.risk = new RiskManager(
1360
- {
1361
- maxPositionSizeBps: config.trading.maxPositionSizeBps,
1362
- maxDailyLossBps: config.trading.maxDailyLossBps,
1363
- maxConcurrentPositions: config.trading.maxConcurrentPositions,
1364
- maxSlippageBps: config.trading.maxSlippageBps,
1365
- minTradeValueUSD: config.trading.minTradeValueUSD
1366
- },
1367
- config.trading.initialCapitalUSD
1368
- );
1369
- this.llm = createLLMAdapter(config.llm);
1370
- this.relay = new RelayClient({
1371
- url: config.relay.url,
1372
- agentId: config.agentId,
1373
- token: config.apiToken,
1374
- heartbeatIntervalMs: config.relay.heartbeatIntervalMs,
1375
- reconnectMaxAttempts: config.relay.reconnectMaxAttempts,
1376
- onCommand: (cmd) => this.handleCommand(cmd),
1377
- onConnected: () => {
1378
- console.log(`[runtime] Connected to command center`);
1379
- this.sendStatus();
1380
- },
1381
- onDisconnected: () => {
1382
- console.log(`[runtime] Disconnected from command center`);
1383
- }
1384
- });
1385
- this.signal = new SignalReporter(this.relay);
1386
- if (config.trading.mode === "paper") {
1387
- this.paper = new PaperExecutor(config.trading.initialCapitalUSD ?? 1e4);
1388
- }
1389
- }
1390
- async start() {
1391
- console.log(`[runtime] Starting agent ${this.config.agentId}`);
1392
- console.log(`[runtime] Mode: ${this.config.trading.mode}`);
1393
- console.log(`[runtime] LLM: ${this.config.llm.provider}/${this.config.llm.model}`);
1394
- try {
1395
- this.strategy = await loadStrategy(this.config.strategy);
1396
- console.log(`[runtime] Strategy loaded`);
1397
- } catch (err) {
1398
- console.error(`[runtime] Failed to load strategy:`, err.message);
1399
- this.strategy = null;
1400
- }
1401
- try {
1402
- await this.relay.connect();
1403
- this.signal.reportInfo("Agent Started", `Agent ${this.config.agentId} connected to command center`);
1404
- } catch (err) {
1405
- console.error(`[runtime] Failed to connect to relay:`, err.message);
1406
- console.log(`[runtime] Will retry in background...`);
1407
- }
1408
- this.running = true;
1409
- this.mode = "idle";
1410
- this.sendStatus();
1411
- if (this.config.trading.mode === "paper" || this.config.trading.mode === "live") {
1412
- this.startTrading();
1413
- }
1414
- process.on("SIGTERM", () => this.stop());
1415
- process.on("SIGINT", () => this.stop());
1416
- }
1417
- async stop() {
1418
- console.log(`[runtime] Stopping agent ${this.config.agentId}`);
1419
- this.running = false;
1420
- this.stopTrading();
1421
- this.signal.reportInfo("Agent Stopped", `Agent ${this.config.agentId} shutting down`);
1422
- this.relay.disconnect();
1423
- console.log(`[runtime] Agent stopped`);
1424
- process.exit(0);
1425
- }
1426
- startTrading() {
1427
- if (this.tradingInterval) return;
1428
- this.mode = this.config.trading.mode === "paper" ? "paper" : "trading";
1429
- console.log(`[runtime] Trading started (${this.mode}, interval: ${this.config.trading.tradingIntervalMs}ms)`);
1430
- this.sendStatus();
1431
- this.signal.reportInfo("Trading Started", `Mode: ${this.mode}`);
1432
- this.runCycle();
1433
- this.tradingInterval = setInterval(() => {
1434
- this.runCycle();
1435
- }, this.config.trading.tradingIntervalMs);
1436
- }
1437
- stopTrading() {
1438
- if (this.tradingInterval) {
1439
- clearInterval(this.tradingInterval);
1440
- this.tradingInterval = null;
1441
- }
1442
- this.mode = "idle";
1443
- this.sendStatus();
1444
- console.log(`[runtime] Trading stopped`);
1445
- }
1446
- async runCycle() {
1447
- if (!this.running || !this.strategy) return;
1448
- this.cycleCount++;
1449
- this.lastCycleAt = Date.now();
1450
- try {
1451
- const prices = this.market.getPrices();
1452
- const positionSummary = this.positions.getSummary(prices);
1453
- const signals = await this.strategy({
1454
- llm: this.llm,
1455
- market: this.market,
1456
- position: positionSummary,
1457
- store: this.store,
1458
- config: this.config.trading,
1459
- log: (msg) => {
1460
- console.log(`[strategy] ${msg}`);
1461
- this.signal.reportInfo("Strategy Log", msg);
1462
- }
1463
- });
1464
- if (!Array.isArray(signals) || signals.length === 0) {
1465
- this.sendStatus();
1466
- return;
1467
- }
1468
- const filtered = this.risk.filterSignals(signals, this.market, positionSummary.openPositions.length);
1469
- for (const sig of filtered) {
1470
- try {
1471
- if (this.paper) {
1472
- const trade = this.paper.execute(sig, this.market);
1473
- if (trade) {
1474
- this.signal.reportTrade({
1475
- ...sig,
1476
- price: trade.entryPrice,
1477
- fee: trade.fee,
1478
- venue: trade.venue,
1479
- venueFillId: trade.id,
1480
- venueTimestamp: new Date(trade.timestamp).toISOString()
1481
- });
1482
- }
1483
- } else {
1484
- console.log(`[runtime] Live trade signal: ${sig.side} ${sig.size} ${sig.symbol}`);
1485
- }
1486
- } catch (err) {
1487
- console.error(`[runtime] Trade execution error:`, err.message);
1488
- this.signal.reportError("Trade Error", err.message);
1489
- }
1490
- }
1491
- } catch (err) {
1492
- console.error(`[runtime] Cycle error:`, err.message);
1493
- this.signal.reportError("Cycle Error", err.message);
1494
- this.mode = "idle";
1495
- }
1496
- this.sendStatus();
1497
- }
1498
- handleCommand(command) {
1499
- console.log(`[runtime] Command received: ${command.type}`);
1500
- switch (command.type) {
1501
- case "start_trading":
1502
- this.startTrading();
1503
- break;
1504
- case "stop_trading":
1505
- this.stopTrading();
1506
- break;
1507
- case "update_risk_params":
1508
- if (command.params) {
1509
- console.log(`[runtime] Risk params updated`);
1510
- }
1511
- break;
1512
- case "get_status":
1513
- this.sendStatus();
1514
- break;
1515
- case "reload_config":
1516
- console.log(`[runtime] Config reload requested`);
1517
- break;
1518
- default:
1519
- console.warn(`[runtime] Unknown command: ${command.type}`);
1520
- }
1521
- }
1522
- sendStatus() {
1523
- const status = {
1524
- mode: this.mode,
1525
- agentId: this.config.agentId,
1526
- sdkVersion: SDK_VERSION,
1527
- cycleCount: this.cycleCount,
1528
- lastCycleAt: this.lastCycleAt,
1529
- tradingIntervalMs: this.config.trading.tradingIntervalMs,
1530
- llm: {
1531
- provider: this.config.llm.provider,
1532
- model: this.config.llm.model || "default"
1533
- },
1534
- risk: {
1535
- dailyPnL: this.risk.getDailyPnL(),
1536
- dailyLossLimit: this.risk.getDailyLossLimit(),
1537
- isLimitHit: this.risk.isDailyLossLimitHit()
1538
- },
1539
- positions: {
1540
- openPositions: this.positions.getPositions().length,
1541
- totalUnrealizedPnL: 0,
1542
- totalRealizedPnL: this.positions.getRealizedPnL()
1543
- }
1544
- };
1545
- if (this.paper) {
1546
- const metrics = this.paper.getMetrics();
1547
- status.paper = {
1548
- active: true,
1549
- simulatedValue: this.paper.getEquity(),
1550
- simulatedPnLPct: metrics.totalReturn * 100
1551
- };
1552
- status.portfolioValue = this.paper.getEquity();
1553
- }
1554
- this.relay.sendHeartbeat(status);
1555
- }
1556
- };
1557
-
1558
- export {
1559
- loadConfig,
1560
- generateSampleConfig,
1561
- writeSampleConfig,
1562
- RelayClient,
1563
- SignalReporter,
1564
- FileStore,
1565
- PositionTracker,
1566
- createLLMAdapter,
1567
- getTemplate,
1568
- listTemplates,
1569
- loadStrategy,
1570
- RiskManager,
1571
- MarketDataService,
1572
- PaperExecutor,
1573
- AgentRuntime
1574
- };