@one_deploy/sdk 1.0.6 → 1.2.0

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 (104) hide show
  1. package/README.md +339 -0
  2. package/dist/ForexPoolDataGenerator--__twRwl.d.mts +76 -0
  3. package/dist/ForexPoolDataGenerator-eUgwsU_B.d.ts +76 -0
  4. package/dist/OneForexTradeHistory-TlKxjbFF.d.ts +250 -0
  5. package/dist/OneForexTradeHistory-iDySMcw0.d.mts +250 -0
  6. package/dist/components/index.d.mts +539 -0
  7. package/dist/components/index.d.ts +539 -0
  8. package/dist/components/index.js +7295 -0
  9. package/dist/components/index.js.map +1 -0
  10. package/dist/components/index.mjs +7243 -0
  11. package/dist/components/index.mjs.map +1 -0
  12. package/dist/config/index.d.mts +1 -0
  13. package/dist/config/index.d.ts +1 -0
  14. package/dist/console-BfTMA7ah.d.mts +504 -0
  15. package/dist/console-BfTMA7ah.d.ts +504 -0
  16. package/dist/hooks/index.d.mts +323 -1
  17. package/dist/hooks/index.d.ts +323 -1
  18. package/dist/hooks/index.js +3223 -0
  19. package/dist/hooks/index.js.map +1 -1
  20. package/dist/hooks/index.mjs +3204 -1
  21. package/dist/hooks/index.mjs.map +1 -1
  22. package/dist/index.d.mts +18 -352
  23. package/dist/index.d.ts +18 -352
  24. package/dist/index.js +8646 -574
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +8449 -432
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/providers/index.d.mts +31 -31
  29. package/dist/providers/index.d.ts +31 -31
  30. package/dist/providers/index.js +140 -153
  31. package/dist/providers/index.js.map +1 -1
  32. package/dist/providers/index.mjs +100 -109
  33. package/dist/providers/index.mjs.map +1 -1
  34. package/dist/react-native.d.mts +8 -140
  35. package/dist/react-native.d.ts +8 -140
  36. package/dist/react-native.js +2527 -0
  37. package/dist/react-native.js.map +1 -1
  38. package/dist/react-native.mjs +2497 -2
  39. package/dist/react-native.mjs.map +1 -1
  40. package/dist/services/index.d.mts +85 -4
  41. package/dist/services/index.d.ts +85 -4
  42. package/dist/services/index.js +1621 -0
  43. package/dist/services/index.js.map +1 -1
  44. package/dist/services/index.mjs +1619 -1
  45. package/dist/services/index.mjs.map +1 -1
  46. package/dist/types/index.d.mts +203 -1
  47. package/dist/types/index.d.ts +203 -1
  48. package/dist/types/index.js +275 -0
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/types/index.mjs +251 -0
  51. package/dist/types/index.mjs.map +1 -1
  52. package/dist/useForexTrading-BleeSor8.d.mts +80 -0
  53. package/dist/useForexTrading-ZgW_G40Q.d.ts +80 -0
  54. package/package.json +9 -2
  55. package/src/components/OneConnectButton.tsx +24 -1
  56. package/src/components/OneNFTGallery.tsx +13 -7
  57. package/src/components/OneOfframpWidget.tsx +4 -3
  58. package/src/components/OnePayWidget.tsx +10 -1
  59. package/src/components/OneSendWidget.tsx +3 -3
  60. package/src/components/OneSwapWidget.tsx +4 -4
  61. package/src/components/OneTransactionButton.tsx +28 -3
  62. package/src/components/OneWalletBalance.tsx +1 -1
  63. package/src/components/ai/OneForexCapitalSplit.tsx +112 -0
  64. package/src/components/ai/OneForexConsoleView.tsx +90 -0
  65. package/src/components/ai/OneForexPairSelector.tsx +101 -0
  66. package/src/components/ai/OneForexPoolCard.tsx +105 -0
  67. package/src/components/ai/OneForexTradeHistory.tsx +107 -0
  68. package/src/components/ai/console/OneAIQuantConsole.tsx +423 -0
  69. package/src/components/ai/console/OneAgentCard.tsx +383 -0
  70. package/src/components/ai/console/OneAgentConsole.tsx +469 -0
  71. package/src/components/ai/console/OneDecisionTimeline.tsx +433 -0
  72. package/src/components/ai/console/OneMetricsDashboard.tsx +493 -0
  73. package/src/components/ai/console/OnePositionCard.tsx +406 -0
  74. package/src/components/ai/console/OnePositionDetail.tsx +600 -0
  75. package/src/components/ai/console/OneRiskIndicator.tsx +464 -0
  76. package/src/components/ai/console/OneTradingConsole.tsx +660 -0
  77. package/src/components/ai/console/index.ts +17 -0
  78. package/src/components/ai/index.ts +10 -0
  79. package/src/hooks/index.ts +46 -0
  80. package/src/hooks/useAIDecisions.ts +280 -0
  81. package/src/hooks/useAIPositions.ts +349 -0
  82. package/src/hooks/useAIQuantConsole.ts +283 -0
  83. package/src/hooks/useAIRiskStatus.ts +276 -0
  84. package/src/hooks/useAITrading.ts +190 -0
  85. package/src/hooks/useBotSimulation.ts +201 -0
  86. package/src/hooks/useForexTrading.ts +430 -0
  87. package/src/hooks/useTradingConsole.ts +243 -0
  88. package/src/index.ts +123 -5
  89. package/src/providers/OneProvider.tsx +181 -5
  90. package/src/providers/index.ts +22 -8
  91. package/src/react-native.ts +41 -0
  92. package/src/services/forex/BotSimulationEngine.ts +968 -0
  93. package/src/services/forex/ForexPoolDataGenerator.ts +542 -0
  94. package/src/services/forex/ForexSimulationEngine.ts +482 -0
  95. package/src/services/forex/index.ts +21 -0
  96. package/src/services/index.ts +16 -0
  97. package/src/types/aiTrading.ts +151 -0
  98. package/src/types/console.ts +380 -0
  99. package/src/types/forex.ts +282 -0
  100. package/src/types/index.ts +106 -0
  101. package/dist/price-CgqXPnT3.d.ts +0 -13
  102. package/dist/price-ClbLHHjv.d.mts +0 -13
  103. package/dist/supabase-BT0c7q9e.d.mts +0 -82
  104. package/dist/supabase-BT0c7q9e.d.ts +0 -82
@@ -1,5 +1,1686 @@
1
1
  import { useState, useRef, useCallback, useEffect, useMemo } from 'react';
2
2
 
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+
24
+ // src/types/forex.ts
25
+ var forex_exports = {};
26
+ __export(forex_exports, {
27
+ FOREX_AGENT: () => FOREX_AGENT,
28
+ FOREX_CAPITAL_SPLIT: () => FOREX_CAPITAL_SPLIT,
29
+ FOREX_CURRENCY_PAIRS: () => FOREX_CURRENCY_PAIRS,
30
+ FOREX_CYCLE_OPTIONS: () => FOREX_CYCLE_OPTIONS,
31
+ FOREX_POOL_DEFAULTS: () => FOREX_POOL_DEFAULTS,
32
+ calculateForexNetProfit: () => calculateForexNetProfit,
33
+ computePoolAllocations: () => computePoolAllocations,
34
+ estimateForexProfit: () => estimateForexProfit
35
+ });
36
+ function computePoolAllocations(amount) {
37
+ const totalPoolReserves = amount * FOREX_CAPITAL_SPLIT.poolReserves;
38
+ const tradingCapital = amount * FOREX_CAPITAL_SPLIT.tradingCapital;
39
+ return {
40
+ tradingCapital,
41
+ totalPoolReserves,
42
+ clearing: totalPoolReserves * 0.5,
43
+ hedging: totalPoolReserves * 0.3,
44
+ insurance: totalPoolReserves * 0.2
45
+ };
46
+ }
47
+ function calculateForexNetProfit(grossProfit, cycleOption) {
48
+ const feeAmount = grossProfit * cycleOption.feeRate;
49
+ const postFeeProfit = grossProfit - feeAmount;
50
+ const netProfit = postFeeProfit * cycleOption.commissionRate;
51
+ return { feeAmount, postFeeProfit, netProfit };
52
+ }
53
+ function estimateForexProfit(amount, cycleDays, agent = FOREX_AGENT) {
54
+ const cycleOption = FOREX_CYCLE_OPTIONS.find((c) => c.days === cycleDays) || FOREX_CYCLE_OPTIONS[0];
55
+ const estimatedApy = (agent.dailyRoiMin + agent.dailyRoiMax) / 2 * 365 * 100;
56
+ const dailyRate = estimatedApy / 100 / 365;
57
+ const grossProfit = amount * dailyRate * cycleDays;
58
+ const { feeAmount, netProfit } = calculateForexNetProfit(grossProfit, cycleOption);
59
+ return { grossProfit, feeAmount, netProfit, dailyRate };
60
+ }
61
+ var FOREX_CAPITAL_SPLIT, FOREX_CYCLE_OPTIONS, FOREX_CURRENCY_PAIRS, FOREX_POOL_DEFAULTS, FOREX_AGENT;
62
+ var init_forex = __esm({
63
+ "src/types/forex.ts"() {
64
+ FOREX_CAPITAL_SPLIT = {
65
+ poolReserves: 0.5,
66
+ tradingCapital: 0.5
67
+ };
68
+ FOREX_CYCLE_OPTIONS = [
69
+ { days: 30, feeRate: 0.1, commissionRate: 0.6, label: "30D" },
70
+ { days: 60, feeRate: 0.08, commissionRate: 0.7, label: "60D" },
71
+ { days: 90, feeRate: 0.07, commissionRate: 0.75, label: "90D" },
72
+ { days: 180, feeRate: 0.05, commissionRate: 0.85, label: "180D" },
73
+ { days: 360, feeRate: 0.03, commissionRate: 0.9, label: "360D" }
74
+ ];
75
+ FOREX_CURRENCY_PAIRS = [
76
+ { id: "USDC_EURC", base: "USDC", quote: "EURC", symbol: "USDC/EURC", flag: "\u{1F1EA}\u{1F1FA}", name: "Euro", basePrice: 0.923, pipSize: 1e-4, spreadPips: 1.2 },
77
+ { id: "USDC_GBPC", base: "USDC", quote: "GBPC", symbol: "USDC/GBPC", flag: "\u{1F1EC}\u{1F1E7}", name: "British Pound", basePrice: 0.789, pipSize: 1e-4, spreadPips: 1.5 },
78
+ { id: "USDC_JPYC", base: "USDC", quote: "JPYC", symbol: "USDC/JPYC", flag: "\u{1F1EF}\u{1F1F5}", name: "Japanese Yen", basePrice: 154.5, pipSize: 0.01, spreadPips: 1 },
79
+ { id: "USDC_AUDC", base: "USDC", quote: "AUDC", symbol: "USDC/AUDC", flag: "\u{1F1E6}\u{1F1FA}", name: "Australian Dollar", basePrice: 1.538, pipSize: 1e-4, spreadPips: 1.8 },
80
+ { id: "USDC_CADC", base: "USDC", quote: "CADC", symbol: "USDC/CADC", flag: "\u{1F1E8}\u{1F1E6}", name: "Canadian Dollar", basePrice: 1.364, pipSize: 1e-4, spreadPips: 1.5 },
81
+ { id: "USDC_CHFC", base: "USDC", quote: "CHFC", symbol: "USDC/CHFC", flag: "\u{1F1E8}\u{1F1ED}", name: "Swiss Franc", basePrice: 0.875, pipSize: 1e-4, spreadPips: 1.3 }
82
+ ];
83
+ FOREX_POOL_DEFAULTS = [
84
+ { id: "clearing", nameKey: "forex.pool_clearing", descriptionKey: "forex.pool_clearing_desc", allocation: 0.5, totalSize: 125e5, utilization: 0.78, color: "#3B82F6", apy7d: 12.8, apy30d: 11.5, netFlow24h: 185e3, txCount24h: 42, txCountTotal: 12840, totalDeposits: 452e5, totalWithdrawals: 327e5, profitDistributed: 185e4, lastUpdated: Date.now() },
85
+ { id: "hedging", nameKey: "forex.pool_hedging", descriptionKey: "forex.pool_hedging_desc", allocation: 0.3, totalSize: 75e5, utilization: 0.65, color: "#F59E0B", apy7d: 8.1, apy30d: 7.6, netFlow24h: 72e3, txCount24h: 24, txCountTotal: 7620, totalDeposits: 285e5, totalWithdrawals: 21e6, profitDistributed: 98e4, lastUpdated: Date.now() },
86
+ { id: "insurance", nameKey: "forex.pool_insurance", descriptionKey: "forex.pool_insurance_desc", allocation: 0.2, totalSize: 5e6, utilization: 0.42, color: "#10B981", apy7d: 4.8, apy30d: 4.5, netFlow24h: 35e3, txCount24h: 14, txCountTotal: 4280, totalDeposits: 158e5, totalWithdrawals: 108e5, profitDistributed: 52e4, lastUpdated: Date.now() }
87
+ ];
88
+ FOREX_AGENT = {
89
+ id: "stablefx-01",
90
+ nameKey: "forex.agent_name",
91
+ descriptionKey: "forex.agent_description",
92
+ icon: "\u{1F4B1}",
93
+ color: "#0EA5E9",
94
+ supportedPairs: FOREX_CURRENCY_PAIRS.map((p) => p.id),
95
+ dailyRoiMin: 2e-3,
96
+ dailyRoiMax: 5e-3,
97
+ totalManaged: 25e6,
98
+ totalUsers: 3847,
99
+ winRate: 72.5
100
+ };
101
+ }
102
+ });
103
+
104
+ // src/services/forex/ForexPoolDataGenerator.ts
105
+ var ForexPoolDataGenerator_exports = {};
106
+ __export(ForexPoolDataGenerator_exports, {
107
+ ForexPoolDataGenerator: () => ForexPoolDataGenerator
108
+ });
109
+ function rand(min, max) {
110
+ return min + Math.random() * (max - min);
111
+ }
112
+ function randInt(min, max) {
113
+ return Math.floor(rand(min, max + 1));
114
+ }
115
+ function pick(arr) {
116
+ return arr[Math.floor(Math.random() * arr.length)];
117
+ }
118
+ function genTxHash() {
119
+ const chars = "0123456789abcdef";
120
+ let hash = "0x";
121
+ for (let i = 0; i < 64; i++) hash += chars[Math.floor(Math.random() * 16)];
122
+ return hash;
123
+ }
124
+ function formatDate(d) {
125
+ return d.toISOString().split("T")[0];
126
+ }
127
+ function genId(prefix) {
128
+ return `${prefix}_${Date.now().toString(36)}_${(++_idCounter).toString(36)}`;
129
+ }
130
+ var _idCounter, POOL_PARAMS, ForexPoolDataGeneratorClass, _instance, ForexPoolDataGenerator;
131
+ var init_ForexPoolDataGenerator = __esm({
132
+ "src/services/forex/ForexPoolDataGenerator.ts"() {
133
+ init_forex();
134
+ _idCounter = 0;
135
+ POOL_PARAMS = {
136
+ clearing: {
137
+ meanDailyPnlPct: 35e-5,
138
+ stddevPnlPct: 15e-5,
139
+ utilizationMin: 0.7,
140
+ utilizationMax: 0.85,
141
+ depositsPerDay: [15, 25],
142
+ withdrawalsPerDay: [8, 12],
143
+ profitDistPerDay: 5,
144
+ avgDepositSize: 25e3,
145
+ avgWithdrawalSize: 18e3
146
+ },
147
+ hedging: {
148
+ meanDailyPnlPct: 22e-5,
149
+ stddevPnlPct: 2e-4,
150
+ utilizationMin: 0.55,
151
+ utilizationMax: 0.75,
152
+ depositsPerDay: [8, 15],
153
+ withdrawalsPerDay: [5, 8],
154
+ profitDistPerDay: 3,
155
+ avgDepositSize: 18e3,
156
+ avgWithdrawalSize: 12e3
157
+ },
158
+ insurance: {
159
+ meanDailyPnlPct: 13e-5,
160
+ stddevPnlPct: 8e-5,
161
+ utilizationMin: 0.3,
162
+ utilizationMax: 0.5,
163
+ depositsPerDay: [5, 10],
164
+ withdrawalsPerDay: [3, 5],
165
+ profitDistPerDay: 2,
166
+ avgDepositSize: 12e3,
167
+ avgWithdrawalSize: 8e3
168
+ }
169
+ };
170
+ ForexPoolDataGeneratorClass = class {
171
+ constructor() {
172
+ this.snapshotCache = null;
173
+ this.transactionCache = null;
174
+ this.baseBlockNumber = 195e5;
175
+ }
176
+ // ── Public API ─────────────────────────────────────────────────────────
177
+ generateAllSnapshots() {
178
+ if (this.snapshotCache) return this.snapshotCache;
179
+ const result = {
180
+ clearing: [],
181
+ hedging: [],
182
+ insurance: []
183
+ };
184
+ for (const pool of FOREX_POOL_DEFAULTS) {
185
+ result[pool.id] = this.generatePoolSnapshots(pool.id, pool.totalSize);
186
+ }
187
+ this.snapshotCache = result;
188
+ return result;
189
+ }
190
+ generateAllTransactions() {
191
+ if (this.transactionCache) return this.transactionCache;
192
+ const allTx = [];
193
+ for (const pool of FOREX_POOL_DEFAULTS) {
194
+ const snapshots = this.snapshotCache?.[pool.id] || this.generatePoolSnapshots(pool.id, pool.totalSize);
195
+ const txs = this.generatePoolTransactions(pool.id, snapshots);
196
+ allTx.push(...txs);
197
+ }
198
+ const now = /* @__PURE__ */ new Date();
199
+ for (let i = 0; i < 60; i++) {
200
+ const day = new Date(now);
201
+ day.setDate(day.getDate() - (60 - i));
202
+ const dayOfWeek = day.getDay();
203
+ if (dayOfWeek === 2 || dayOfWeek === 4 || dayOfWeek === 5 && Math.random() < 0.4) {
204
+ const fromPool = pick(["clearing", "hedging", "insurance"]);
205
+ const toOptions = ["clearing", "hedging", "insurance"].filter((p) => p !== fromPool);
206
+ const toPool = pick(toOptions);
207
+ const amount = rand(5e4, 2e5);
208
+ const ts = day.getTime() + randInt(10, 18) * 36e5;
209
+ allTx.push({
210
+ id: genId("ipt"),
211
+ poolId: fromPool,
212
+ type: "inter_pool_transfer",
213
+ amount: -amount,
214
+ balanceBefore: 0,
215
+ balanceAfter: 0,
216
+ txHash: genTxHash(),
217
+ blockNumber: this.baseBlockNumber + i * 7200 + randInt(0, 100),
218
+ timestamp: ts,
219
+ description: `Transfer to ${toPool} pool`
220
+ });
221
+ allTx.push({
222
+ id: genId("ipt"),
223
+ poolId: toPool,
224
+ type: "inter_pool_transfer",
225
+ amount,
226
+ balanceBefore: 0,
227
+ balanceAfter: 0,
228
+ txHash: genTxHash(),
229
+ blockNumber: this.baseBlockNumber + i * 7200 + randInt(100, 200),
230
+ timestamp: ts + 5e3,
231
+ description: `Transfer from ${fromPool} pool`
232
+ });
233
+ }
234
+ if (dayOfWeek === 3 && Math.random() < 0.85) {
235
+ const pool = pick(FOREX_POOL_DEFAULTS);
236
+ const rebalanceAmt = rand(2e4, 1e5);
237
+ const ts = day.getTime() + randInt(2, 6) * 36e5;
238
+ allTx.push({
239
+ id: genId("rrb"),
240
+ poolId: pool.id,
241
+ type: "reserve_rebalance",
242
+ amount: Math.random() < 0.5 ? rebalanceAmt : -rebalanceAmt,
243
+ balanceBefore: 0,
244
+ balanceAfter: 0,
245
+ txHash: genTxHash(),
246
+ blockNumber: this.baseBlockNumber + i * 7200 + randInt(200, 300),
247
+ timestamp: ts,
248
+ description: "Automated reserve rebalance"
249
+ });
250
+ }
251
+ }
252
+ allTx.sort((a, b) => a.timestamp - b.timestamp);
253
+ const runningBalance = {
254
+ clearing: FOREX_POOL_DEFAULTS[0].totalSize * 0.85,
255
+ hedging: FOREX_POOL_DEFAULTS[1].totalSize * 0.82,
256
+ insurance: FOREX_POOL_DEFAULTS[2].totalSize * 0.88
257
+ };
258
+ for (const tx of allTx) {
259
+ tx.balanceBefore = runningBalance[tx.poolId];
260
+ runningBalance[tx.poolId] += tx.amount;
261
+ tx.balanceAfter = runningBalance[tx.poolId];
262
+ }
263
+ this.transactionCache = allTx;
264
+ return allTx;
265
+ }
266
+ generateTradeHistory(investmentAmount, startDate, selectedPairs) {
267
+ const trades = [];
268
+ const start = new Date(startDate);
269
+ const now = /* @__PURE__ */ new Date();
270
+ const dayCount = Math.min(60, Math.ceil((now.getTime() - start.getTime()) / 864e5));
271
+ let cumulativePnl = 0;
272
+ let blockNum = this.baseBlockNumber + randInt(0, 5e3);
273
+ for (let d = 0; d < dayCount; d++) {
274
+ const day = new Date(start);
275
+ day.setDate(day.getDate() + d);
276
+ const dayOfWeek = day.getDay();
277
+ const baseCount = dayOfWeek === 0 || dayOfWeek === 6 ? randInt(1, 2) : randInt(3, 8);
278
+ for (let t = 0; t < baseCount; t++) {
279
+ const pair = FOREX_CURRENCY_PAIRS.find((p) => p.id === pick(selectedPairs)) || pick(FOREX_CURRENCY_PAIRS);
280
+ const side = Math.random() > 0.5 ? "BUY" : "SELL";
281
+ const lots = parseFloat(rand(0.1, 2.5).toFixed(2));
282
+ const rfqPrice = pair.basePrice * (1 + rand(-3e-3, 3e-3));
283
+ const quoteSpread = rand(0.5, 2) * pair.pipSize;
284
+ const quotePrice = side === "BUY" ? rfqPrice + quoteSpread : rfqPrice - quoteSpread;
285
+ const matched = Math.random() < 0.85;
286
+ if (!matched) continue;
287
+ const matchPrice = quotePrice * (1 + rand(-5e-5, 5e-5));
288
+ const settlePrice = matchPrice * (1 + rand(-2e-5, 2e-5));
289
+ const pips = (settlePrice - rfqPrice) / pair.pipSize * (side === "BUY" ? 1 : -1);
290
+ const pnl = pips * pair.pipSize * lots * 1e5;
291
+ const isWin = Math.random() < FOREX_AGENT.winRate / 100;
292
+ const finalPnl = isWin ? Math.abs(pnl) : -Math.abs(pnl) * rand(0.3, 0.8);
293
+ cumulativePnl += finalPnl;
294
+ const clearingFee = Math.abs(finalPnl) * rand(1e-3, 3e-3);
295
+ const hedgingCost = Math.abs(finalPnl) * rand(5e-4, 2e-3);
296
+ const insuranceReserve = Math.abs(finalPnl) * rand(3e-4, 1e-3);
297
+ blockNum += randInt(1, 20);
298
+ const timestamp = day.getTime() + randInt(0, 23) * 36e5 + randInt(0, 36e5);
299
+ trades.push({
300
+ id: genId("FXT"),
301
+ timestamp,
302
+ pairId: pair.id,
303
+ pairSymbol: pair.symbol,
304
+ side,
305
+ rfqPrice,
306
+ quotePrice,
307
+ matchPrice,
308
+ settlePrice,
309
+ lots,
310
+ pips: isWin ? Math.abs(pips) : -Math.abs(pips) * rand(0.3, 0.8),
311
+ pnl: finalPnl,
312
+ status: "SETTLED",
313
+ pvpSettled: true,
314
+ clearingFee,
315
+ hedgingCost,
316
+ insuranceReserve,
317
+ txHash: genTxHash(),
318
+ blockNumber: blockNum,
319
+ cycleDay: d + 1,
320
+ cumulativePnl
321
+ });
322
+ }
323
+ }
324
+ trades.sort((a, b) => a.timestamp - b.timestamp);
325
+ return trades;
326
+ }
327
+ generateLiveTransaction(poolId, type, baseAmount) {
328
+ const params = POOL_PARAMS[poolId];
329
+ let amount;
330
+ switch (type) {
331
+ case "deposit":
332
+ amount = baseAmount ?? rand(params.avgDepositSize * 0.5, params.avgDepositSize * 1.5);
333
+ break;
334
+ case "withdrawal":
335
+ amount = -(baseAmount ?? rand(params.avgWithdrawalSize * 0.5, params.avgWithdrawalSize * 1.5));
336
+ break;
337
+ case "profit_distribution":
338
+ amount = baseAmount ?? rand(500, 5e3);
339
+ break;
340
+ case "fee_collection":
341
+ amount = baseAmount ?? rand(100, 2e3);
342
+ break;
343
+ case "loss_absorption":
344
+ amount = -(baseAmount ?? rand(200, 3e3));
345
+ break;
346
+ default:
347
+ amount = baseAmount ?? rand(-5e3, 5e3);
348
+ }
349
+ const pool = FOREX_POOL_DEFAULTS.find((p) => p.id === poolId);
350
+ const balanceBefore = pool.totalSize;
351
+ return {
352
+ id: genId("ptx"),
353
+ poolId,
354
+ type,
355
+ amount,
356
+ balanceBefore,
357
+ balanceAfter: balanceBefore + amount,
358
+ txHash: genTxHash(),
359
+ blockNumber: this.baseBlockNumber + Math.floor(Date.now() / 12e3),
360
+ timestamp: Date.now(),
361
+ description: this.getTxDescription(type, poolId, Math.abs(amount))
362
+ };
363
+ }
364
+ // ── Private Methods ────────────────────────────────────────────────────
365
+ generatePoolSnapshots(poolId, currentSize) {
366
+ const params = POOL_PARAMS[poolId];
367
+ const snapshots = [];
368
+ const now = /* @__PURE__ */ new Date();
369
+ let balance = currentSize * rand(0.82, 0.88);
370
+ let cumulativePnl = 0;
371
+ for (let i = 59; i >= 0; i--) {
372
+ const day = new Date(now);
373
+ day.setDate(day.getDate() - i);
374
+ const dayOfWeek = day.getDay();
375
+ const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
376
+ const openBalance = balance;
377
+ const activityMultiplier = isWeekend ? 0.2 : 1;
378
+ const isDrawdown = !isWeekend && Math.random() < 0.2;
379
+ let dailyPnlPct;
380
+ if (isDrawdown) {
381
+ dailyPnlPct = -rand(1e-4, params.stddevPnlPct * 2);
382
+ } else {
383
+ dailyPnlPct = this.gaussianRandom(params.meanDailyPnlPct, params.stddevPnlPct);
384
+ }
385
+ dailyPnlPct *= activityMultiplier;
386
+ const dailyPnl = balance * dailyPnlPct;
387
+ cumulativePnl += dailyPnl;
388
+ const depositCount = isWeekend ? randInt(1, Math.ceil(params.depositsPerDay[0] * 0.2)) : randInt(params.depositsPerDay[0], params.depositsPerDay[1]);
389
+ const withdrawalCount = isWeekend ? randInt(0, Math.ceil(params.withdrawalsPerDay[0] * 0.2)) : randInt(params.withdrawalsPerDay[0], params.withdrawalsPerDay[1]);
390
+ const deposits = depositCount * params.avgDepositSize * rand(0.7, 1.3) * activityMultiplier;
391
+ const withdrawals = withdrawalCount * params.avgWithdrawalSize * rand(0.7, 1.3) * activityMultiplier;
392
+ const netFlow = deposits - withdrawals;
393
+ balance += dailyPnl + netFlow;
394
+ const txCount = depositCount + withdrawalCount + Math.round(params.profitDistPerDay * activityMultiplier);
395
+ const utilization = rand(params.utilizationMin, params.utilizationMax);
396
+ const activeUsers = Math.round(rand(80, 400) * activityMultiplier);
397
+ snapshots.push({
398
+ poolId,
399
+ date: formatDate(day),
400
+ openBalance,
401
+ closeBalance: balance,
402
+ deposits,
403
+ withdrawals,
404
+ netFlow,
405
+ dailyPnl,
406
+ dailyPnlPct,
407
+ cumulativePnl,
408
+ utilization,
409
+ txCount,
410
+ activeUsers
411
+ });
412
+ }
413
+ return snapshots;
414
+ }
415
+ generatePoolTransactions(poolId, snapshots) {
416
+ const params = POOL_PARAMS[poolId];
417
+ const transactions = [];
418
+ for (const snap of snapshots) {
419
+ const day = new Date(snap.date);
420
+ const dayOfWeek = day.getDay();
421
+ const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
422
+ const mult = isWeekend ? 0.2 : 1;
423
+ const depositCount = Math.round(randInt(params.depositsPerDay[0], params.depositsPerDay[1]) * mult);
424
+ const withdrawalCount = Math.round(randInt(params.withdrawalsPerDay[0], params.withdrawalsPerDay[1]) * mult);
425
+ const profitCount = Math.round(params.profitDistPerDay * mult);
426
+ for (let i = 0; i < depositCount; i++) {
427
+ const amount = rand(params.avgDepositSize * 0.3, params.avgDepositSize * 2);
428
+ const ts = day.getTime() + randInt(0, 23) * 36e5 + randInt(0, 36e5);
429
+ transactions.push({
430
+ id: genId("dep"),
431
+ poolId,
432
+ type: "deposit",
433
+ amount,
434
+ balanceBefore: 0,
435
+ balanceAfter: 0,
436
+ txHash: genTxHash(),
437
+ blockNumber: this.baseBlockNumber + Math.floor(ts / 12e3) + randInt(0, 50),
438
+ timestamp: ts,
439
+ description: `Deposit to ${poolId} pool`
440
+ });
441
+ }
442
+ for (let i = 0; i < withdrawalCount; i++) {
443
+ const amount = rand(params.avgWithdrawalSize * 0.3, params.avgWithdrawalSize * 2);
444
+ const ts = day.getTime() + randInt(0, 23) * 36e5 + randInt(0, 36e5);
445
+ transactions.push({
446
+ id: genId("wdr"),
447
+ poolId,
448
+ type: "withdrawal",
449
+ amount: -amount,
450
+ balanceBefore: 0,
451
+ balanceAfter: 0,
452
+ txHash: genTxHash(),
453
+ blockNumber: this.baseBlockNumber + Math.floor(ts / 12e3) + randInt(0, 50),
454
+ timestamp: ts,
455
+ description: `Withdrawal from ${poolId} pool`
456
+ });
457
+ }
458
+ for (let i = 0; i < profitCount; i++) {
459
+ const amount = rand(500, 8e3);
460
+ const ts = day.getTime() + randInt(6, 22) * 36e5 + randInt(0, 36e5);
461
+ transactions.push({
462
+ id: genId("prd"),
463
+ poolId,
464
+ type: "profit_distribution",
465
+ amount,
466
+ balanceBefore: 0,
467
+ balanceAfter: 0,
468
+ txHash: genTxHash(),
469
+ blockNumber: this.baseBlockNumber + Math.floor(ts / 12e3) + randInt(0, 50),
470
+ timestamp: ts,
471
+ description: `Profit distribution from ${poolId} pool`
472
+ });
473
+ }
474
+ if (!isWeekend) {
475
+ const feeCount = randInt(1, 2);
476
+ for (let i = 0; i < feeCount; i++) {
477
+ const amount = rand(100, 3e3);
478
+ const ts = day.getTime() + randInt(8, 20) * 36e5;
479
+ transactions.push({
480
+ id: genId("fee"),
481
+ poolId,
482
+ type: "fee_collection",
483
+ amount,
484
+ balanceBefore: 0,
485
+ balanceAfter: 0,
486
+ txHash: genTxHash(),
487
+ blockNumber: this.baseBlockNumber + Math.floor(ts / 12e3) + randInt(0, 50),
488
+ timestamp: ts,
489
+ description: `Fee collection for ${poolId} pool`
490
+ });
491
+ }
492
+ }
493
+ }
494
+ return transactions;
495
+ }
496
+ gaussianRandom(mean, stddev) {
497
+ let u = 0, v = 0;
498
+ while (u === 0) u = Math.random();
499
+ while (v === 0) v = Math.random();
500
+ const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
501
+ return mean + z * stddev;
502
+ }
503
+ getTxDescription(type, poolId, amount) {
504
+ const fmt = `$${amount.toLocaleString(void 0, { maximumFractionDigits: 0 })}`;
505
+ switch (type) {
506
+ case "deposit":
507
+ return `Deposit ${fmt} to ${poolId} pool`;
508
+ case "withdrawal":
509
+ return `Withdrawal ${fmt} from ${poolId} pool`;
510
+ case "profit_distribution":
511
+ return `Profit distribution ${fmt} from ${poolId}`;
512
+ case "loss_absorption":
513
+ return `Loss absorbed ${fmt} by ${poolId} pool`;
514
+ case "inter_pool_transfer":
515
+ return `Inter-pool transfer ${fmt}`;
516
+ case "fee_collection":
517
+ return `Fee collected ${fmt} in ${poolId}`;
518
+ case "reserve_rebalance":
519
+ return `Reserve rebalance ${fmt} in ${poolId}`;
520
+ default:
521
+ return `${type} ${fmt}`;
522
+ }
523
+ }
524
+ };
525
+ _instance = null;
526
+ ForexPoolDataGenerator = {
527
+ getInstance() {
528
+ if (!_instance) {
529
+ _instance = new ForexPoolDataGeneratorClass();
530
+ }
531
+ return _instance;
532
+ }
533
+ };
534
+ }
535
+ });
536
+
537
+ // src/services/forex/ForexSimulationEngine.ts
538
+ var ForexSimulationEngine_exports = {};
539
+ __export(ForexSimulationEngine_exports, {
540
+ forexSimulationEngine: () => forexSimulationEngine
541
+ });
542
+ function genId2() {
543
+ return `fxlog_${Date.now()}_${++idCounter}`;
544
+ }
545
+ function tradeId() {
546
+ return `FXT_${Date.now().toString(36).toUpperCase()}_${(++idCounter).toString(36).toUpperCase()}`;
547
+ }
548
+ function rand2(min, max) {
549
+ return min + Math.random() * (max - min);
550
+ }
551
+ function randInt2(min, max) {
552
+ return Math.floor(rand2(min, max + 1));
553
+ }
554
+ function pick2(arr) {
555
+ return arr[Math.floor(Math.random() * arr.length)];
556
+ }
557
+ function formatRate(price, pair) {
558
+ if (pair.pipSize >= 0.01) return price.toFixed(3);
559
+ return price.toFixed(5);
560
+ }
561
+ var idCounter, FX_NEWS, ForexSimulationEngine, forexSimulationEngine;
562
+ var init_ForexSimulationEngine = __esm({
563
+ "src/services/forex/ForexSimulationEngine.ts"() {
564
+ init_forex();
565
+ idCounter = 0;
566
+ FX_NEWS = [
567
+ "ECB signals potential rate adjustment, EUR pairs volatile",
568
+ "BOJ maintains yield curve control, JPY weakens further",
569
+ "Fed minutes reveal hawkish sentiment, USD strengthens",
570
+ "UK CPI data beats expectations, GBP rallies",
571
+ "RBA holds rates steady, AUD consolidates",
572
+ "SNB intervenes in currency markets, CHF stabilizes",
573
+ "Bank of Canada rate decision pending, CAD in focus",
574
+ "Cross-border stablecoin settlement volume hits $2.1B daily",
575
+ "Circle USDC reserves fully backed, attestation report released",
576
+ "DeFi forex protocol TVL reaches new high at $890M",
577
+ "On-chain FX liquidity deepens across major pairs",
578
+ "Institutional adoption of on-chain forex accelerates"
579
+ ];
580
+ ForexSimulationEngine = class {
581
+ constructor() {
582
+ this.listeners = [];
583
+ this.poolTxListeners = [];
584
+ this.cycleTimer = null;
585
+ this.pairStates = /* @__PURE__ */ new Map();
586
+ this.running = false;
587
+ this.openPositions = [];
588
+ this.totalPnl = 0;
589
+ this.totalTrades = 0;
590
+ this.totalPips = 0;
591
+ this.totalLots = 0;
592
+ for (const pair of FOREX_CURRENCY_PAIRS) {
593
+ const jitter = pair.basePrice * rand2(-3e-3, 3e-3);
594
+ const price = pair.basePrice + jitter;
595
+ const halfSpread = pair.spreadPips * pair.pipSize / 2;
596
+ this.pairStates.set(pair.id, {
597
+ pair,
598
+ currentPrice: price,
599
+ bidPrice: price - halfSpread,
600
+ askPrice: price + halfSpread,
601
+ lastSpread: pair.spreadPips
602
+ });
603
+ }
604
+ }
605
+ // ── Public API ─────────────────────────────────────────────────────────────
606
+ start() {
607
+ this.running = true;
608
+ this.scheduleCycle();
609
+ }
610
+ stop() {
611
+ this.running = false;
612
+ if (this.cycleTimer) {
613
+ clearTimeout(this.cycleTimer);
614
+ this.cycleTimer = null;
615
+ }
616
+ }
617
+ onLog(callback) {
618
+ this.listeners.push(callback);
619
+ return () => {
620
+ this.listeners = this.listeners.filter((l) => l !== callback);
621
+ };
622
+ }
623
+ onPoolTransaction(callback) {
624
+ this.poolTxListeners.push(callback);
625
+ return () => {
626
+ this.poolTxListeners = this.poolTxListeners.filter((l) => l !== callback);
627
+ };
628
+ }
629
+ isRunning() {
630
+ return this.running;
631
+ }
632
+ getStats() {
633
+ return {
634
+ totalPnl: this.totalPnl,
635
+ totalTrades: this.totalTrades,
636
+ totalPips: this.totalPips,
637
+ totalLots: this.totalLots,
638
+ positions: this.openPositions.length
639
+ };
640
+ }
641
+ getPairStates() {
642
+ return this.pairStates;
643
+ }
644
+ emitBootSequence() {
645
+ const bootMessages = [
646
+ { msg: "Initializing StableFX Engine v2.1.0...", delay: 0 },
647
+ { msg: "Connecting to Circle StableFX RFQ network...", delay: 500 },
648
+ { msg: "Loading USDC stablecoin pair feeds (6 pairs)...", delay: 1200 },
649
+ { msg: "Calibrating PvP settlement engine...", delay: 2e3 },
650
+ { msg: "Initializing clearing pool ($12.5M)...", delay: 2800 },
651
+ { msg: "Initializing hedging pool ($7.5M)...", delay: 3400 },
652
+ { msg: "Initializing insurance pool ($5.0M)...", delay: 4e3 },
653
+ { msg: "Risk management module online (max exposure: 25%)", delay: 4500 },
654
+ { msg: "=== StableFX Engine ready. Starting RFQ cycles ===", delay: 5e3 }
655
+ ];
656
+ for (const { msg, delay } of bootMessages) {
657
+ setTimeout(() => {
658
+ this.emit({
659
+ id: genId2(),
660
+ timestamp: Date.now(),
661
+ type: "SYSTEM",
662
+ message: msg,
663
+ importance: "medium"
664
+ });
665
+ }, delay);
666
+ }
667
+ }
668
+ destroy() {
669
+ this.stop();
670
+ this.listeners = [];
671
+ this.poolTxListeners = [];
672
+ this.pairStates.clear();
673
+ this.openPositions = [];
674
+ }
675
+ // ── Private Methods ────────────────────────────────────────────────────────
676
+ emit(entry) {
677
+ for (const listener of this.listeners) {
678
+ listener(entry);
679
+ }
680
+ }
681
+ emitPoolTx(tx) {
682
+ for (const listener of this.poolTxListeners) {
683
+ listener(tx);
684
+ }
685
+ }
686
+ generatePoolTxFromEvent(type, data) {
687
+ try {
688
+ const { ForexPoolDataGenerator: ForexPoolDataGenerator2 } = (init_ForexPoolDataGenerator(), __toCommonJS(ForexPoolDataGenerator_exports));
689
+ const generator = ForexPoolDataGenerator2.getInstance();
690
+ if (type === "SETTLE" && data.pnl !== void 0) {
691
+ const tx = generator.generateLiveTransaction("clearing", "fee_collection", Math.abs(data.pnl) * rand2(1e-3, 3e-3));
692
+ this.emitPoolTx(tx);
693
+ } else if (type === "HEDGE") {
694
+ const tx = generator.generateLiveTransaction("hedging", data.pnl && data.pnl < 0 ? "loss_absorption" : "profit_distribution", Math.abs(data.lots || 1) * rand2(50, 200));
695
+ this.emitPoolTx(tx);
696
+ } else if (type === "CLEAR") {
697
+ const tx = generator.generateLiveTransaction("clearing", "profit_distribution", (data.volume || 1e5) * rand2(1e-4, 5e-4));
698
+ this.emitPoolTx(tx);
699
+ }
700
+ } catch {
701
+ }
702
+ }
703
+ scheduleCycle() {
704
+ if (!this.running) return;
705
+ const interval = rand2(8e3, 14e3);
706
+ this.cycleTimer = setTimeout(() => {
707
+ if (this.running) {
708
+ this.runTradeCycle();
709
+ this.scheduleCycle();
710
+ }
711
+ }, interval);
712
+ }
713
+ simulatePrice(pairId) {
714
+ const state = this.pairStates.get(pairId);
715
+ if (!state) return 0;
716
+ const volatility = state.pair.id.includes("JPYC") ? 8e-4 : 4e-4;
717
+ const drift = rand2(-volatility, volatility);
718
+ const newPrice = state.currentPrice * (1 + drift);
719
+ const halfSpread = (state.pair.spreadPips + rand2(-0.3, 0.3)) * state.pair.pipSize / 2;
720
+ state.currentPrice = newPrice;
721
+ state.bidPrice = newPrice - halfSpread;
722
+ state.askPrice = newPrice + halfSpread;
723
+ state.lastSpread = halfSpread * 2 / state.pair.pipSize;
724
+ return newPrice;
725
+ }
726
+ runTradeCycle() {
727
+ const pairState = pick2(Array.from(this.pairStates.values()));
728
+ const pair = pairState.pair;
729
+ const entries = [];
730
+ let delay = 0;
731
+ const price = this.simulatePrice(pair.id);
732
+ const side = Math.random() > 0.5 ? "BUY" : "SELL";
733
+ const lots = parseFloat(rand2(0.1, 2.5).toFixed(2));
734
+ const notional = lots * 1e5;
735
+ const rfqId = tradeId();
736
+ entries.push({
737
+ entry: {
738
+ type: "RFQ",
739
+ message: `RFQ ${rfqId} | ${pair.symbol} ${side} ${lots.toFixed(2)} lots ($${(notional / 1e3).toFixed(0)}K) | Mid: ${formatRate(price, pair)}`,
740
+ data: { rfqId, pair: pair.id, side, lots, price },
741
+ importance: "medium",
742
+ pairId: pair.id
743
+ },
744
+ delay
745
+ });
746
+ delay += rand2(400, 800);
747
+ const quoteSpread = rand2(0.5, 2) * pair.pipSize;
748
+ const quotePrice = side === "BUY" ? price + quoteSpread : price - quoteSpread;
749
+ const quotePips = Math.abs(quotePrice - price) / pair.pipSize;
750
+ entries.push({
751
+ entry: {
752
+ type: "QUOTE",
753
+ message: `QUOTE ${rfqId} | ${pair.symbol} @ ${formatRate(quotePrice, pair)} | Spread: ${quotePips.toFixed(1)} pips | Valid: 3s`,
754
+ data: { rfqId, quotePrice, spread: quotePips },
755
+ importance: "medium",
756
+ pairId: pair.id
757
+ },
758
+ delay
759
+ });
760
+ delay += rand2(500, 1e3);
761
+ const matched = Math.random() < 0.85;
762
+ if (matched) {
763
+ const matchPrice = quotePrice * (1 + rand2(-5e-5, 5e-5));
764
+ entries.push({
765
+ entry: {
766
+ type: "MATCH",
767
+ message: `MATCH ${rfqId} | ${pair.symbol} ${side} @ ${formatRate(matchPrice, pair)} | ${lots.toFixed(2)} lots | Counterparty: LP-${randInt2(1, 8)}`,
768
+ data: { rfqId, matchPrice, counterparty: `LP-${randInt2(1, 8)}` },
769
+ importance: "high",
770
+ pairId: pair.id
771
+ },
772
+ delay
773
+ });
774
+ delay += rand2(1e3, 2500);
775
+ const settlePrice = matchPrice * (1 + rand2(-2e-5, 2e-5));
776
+ const pips = (settlePrice - price) / pair.pipSize * (side === "BUY" ? 1 : -1);
777
+ const pnl = pips * pair.pipSize * lots * 1e5;
778
+ entries.push({
779
+ entry: {
780
+ type: "SETTLE",
781
+ message: `SETTLE ${rfqId} | PvP confirmed | ${pair.symbol} @ ${formatRate(settlePrice, pair)} | P&L: ${pips >= 0 ? "+" : ""}${pips.toFixed(1)} pips ($${pnl >= 0 ? "+" : ""}${pnl.toFixed(2)})`,
782
+ data: { rfqId, settlePrice, pips, pnl, pvp: true },
783
+ importance: "high",
784
+ pairId: pair.id
785
+ },
786
+ delay
787
+ });
788
+ delay += rand2(300, 600);
789
+ entries.push({
790
+ entry: {
791
+ type: "PVP",
792
+ message: `PvP ${rfqId} | Atomic settlement confirmed on-chain | USDC transferred: $${notional.toLocaleString()} | Gas: ~$0.${randInt2(10, 50)}`,
793
+ data: { rfqId, settled: true, gasWei: randInt2(10, 50) },
794
+ importance: "medium",
795
+ pairId: pair.id
796
+ },
797
+ delay
798
+ });
799
+ this.generatePoolTxFromEvent("SETTLE", { pnl });
800
+ this.totalTrades++;
801
+ this.totalPnl += pnl;
802
+ this.totalPips += pips;
803
+ this.totalLots += lots;
804
+ if (Math.random() < 0.4) {
805
+ this.openPositions.push({
806
+ id: rfqId,
807
+ pairId: pair.id,
808
+ side,
809
+ lots,
810
+ pips,
811
+ entryPrice: matchPrice,
812
+ currentPrice: settlePrice,
813
+ pnl,
814
+ openTime: Date.now()
815
+ });
816
+ if (this.openPositions.length > 5) {
817
+ this.openPositions.shift();
818
+ }
819
+ }
820
+ } else {
821
+ entries.push({
822
+ entry: {
823
+ type: "MATCH",
824
+ message: `MATCH FAILED ${rfqId} | ${pair.symbol} | No counterparty at requested price | Requoting...`,
825
+ data: { rfqId, matched: false },
826
+ importance: "low",
827
+ pairId: pair.id
828
+ },
829
+ delay
830
+ });
831
+ }
832
+ if (Math.random() < 0.2) {
833
+ delay += rand2(400, 800);
834
+ const hedgePair = pick2(FOREX_CURRENCY_PAIRS);
835
+ const hedgeLots = parseFloat(rand2(0.5, 5).toFixed(2));
836
+ const hedgeDirection = Math.random() > 0.5 ? "LONG" : "SHORT";
837
+ entries.push({
838
+ entry: {
839
+ type: "HEDGE",
840
+ message: `HEDGE | ${hedgePair.symbol} ${hedgeDirection} ${hedgeLots.toFixed(2)} lots | Pool delta neutralization | Exposure: ${rand2(5, 20).toFixed(1)}%`,
841
+ data: { pair: hedgePair.id, direction: hedgeDirection, lots: hedgeLots },
842
+ importance: "medium"
843
+ },
844
+ delay
845
+ });
846
+ this.generatePoolTxFromEvent("HEDGE", { lots: hedgeLots });
847
+ }
848
+ if (Math.random() < 0.15) {
849
+ delay += rand2(300, 600);
850
+ const clearAmount = randInt2(5e4, 5e5);
851
+ entries.push({
852
+ entry: {
853
+ type: "CLEAR",
854
+ message: `CLEAR | Netting cycle complete | Volume: $${(clearAmount / 1e3).toFixed(0)}K | Pairs settled: ${randInt2(2, 6)} | Pool util: ${rand2(60, 85).toFixed(1)}%`,
855
+ data: { volume: clearAmount, pairsSettled: randInt2(2, 6) },
856
+ importance: "low"
857
+ },
858
+ delay
859
+ });
860
+ this.generatePoolTxFromEvent("CLEAR", { volume: clearAmount });
861
+ }
862
+ if (this.openPositions.length > 0 && Math.random() < 0.25) {
863
+ delay += rand2(300, 600);
864
+ const posUpdates = this.openPositions.slice(0, 3).map((pos) => {
865
+ const pState = this.pairStates.get(pos.pairId);
866
+ if (pState) {
867
+ pos.currentPrice = pState.currentPrice;
868
+ pos.pips = (pos.currentPrice - pos.entryPrice) / pState.pair.pipSize * (pos.side === "BUY" ? 1 : -1);
869
+ pos.pnl = pos.pips * pState.pair.pipSize * pos.lots * 1e5;
870
+ }
871
+ return `${pState?.pair.symbol || pos.pairId} ${pos.side}: ${pos.pips >= 0 ? "+" : ""}${pos.pips.toFixed(1)} pips`;
872
+ });
873
+ entries.push({
874
+ entry: {
875
+ type: "POSITION",
876
+ message: `POSITION | ${posUpdates.join(" | ")} | Open: ${this.openPositions.length}`,
877
+ data: { positions: this.openPositions.length },
878
+ importance: "low"
879
+ },
880
+ delay
881
+ });
882
+ if (this.openPositions.length > 2 && Math.random() < 0.3) {
883
+ const closed = this.openPositions.shift();
884
+ this.totalPnl += closed.pnl * rand2(0.01, 0.03);
885
+ }
886
+ }
887
+ if (Math.random() < 0.3) {
888
+ delay += rand2(300, 600);
889
+ entries.push({
890
+ entry: {
891
+ type: "PNL",
892
+ message: `PNL | Session: $${this.totalPnl >= 0 ? "+" : ""}${this.totalPnl.toFixed(2)} | Trades: ${this.totalTrades} | Pips: ${this.totalPips >= 0 ? "+" : ""}${this.totalPips.toFixed(1)} | Lots: ${this.totalLots.toFixed(2)}`,
893
+ data: { totalPnl: this.totalPnl, totalTrades: this.totalTrades, totalPips: this.totalPips },
894
+ importance: "medium"
895
+ },
896
+ delay
897
+ });
898
+ }
899
+ if (Math.random() < 0.1) {
900
+ delay += rand2(300, 600);
901
+ entries.push({
902
+ entry: {
903
+ type: "SYSTEM",
904
+ message: `[Market] ${pick2(FX_NEWS)}`,
905
+ importance: "medium"
906
+ },
907
+ delay
908
+ });
909
+ }
910
+ for (const { entry, delay: d } of entries) {
911
+ setTimeout(() => {
912
+ if (this.running) {
913
+ this.emit({
914
+ ...entry,
915
+ id: genId2(),
916
+ timestamp: Date.now()
917
+ });
918
+ }
919
+ }, d);
920
+ }
921
+ }
922
+ };
923
+ forexSimulationEngine = new ForexSimulationEngine();
924
+ }
925
+ });
926
+
927
+ // src/services/forex/BotSimulationEngine.ts
928
+ var BotSimulationEngine_exports = {};
929
+ __export(BotSimulationEngine_exports, {
930
+ STRATEGY_PERSONALITIES: () => STRATEGY_PERSONALITIES,
931
+ botSimulationEngine: () => botSimulationEngine
932
+ });
933
+ function genId3() {
934
+ return `log_${Date.now()}_${++idCounter2}`;
935
+ }
936
+ function rand3(min, max) {
937
+ return min + Math.random() * (max - min);
938
+ }
939
+ function randInt3(min, max) {
940
+ return Math.floor(rand3(min, max + 1));
941
+ }
942
+ function pick3(arr) {
943
+ return arr[Math.floor(Math.random() * arr.length)];
944
+ }
945
+ function clamp(val, min, max) {
946
+ return Math.max(min, Math.min(max, val));
947
+ }
948
+ function formatPrice(price) {
949
+ if (price >= 1e3) return price.toFixed(2);
950
+ if (price >= 1) return price.toFixed(3);
951
+ return price.toFixed(5);
952
+ }
953
+ var STRATEGY_PERSONALITIES, PAIR_PRICES, CHAIN_INFO, NEWS_HEADLINES, idCounter2, BotSimulationEngine, botSimulationEngine;
954
+ var init_BotSimulationEngine = __esm({
955
+ "src/services/forex/BotSimulationEngine.ts"() {
956
+ STRATEGY_PERSONALITIES = [
957
+ {
958
+ id: "balanced-01",
959
+ name: "Balanced Alpha",
960
+ shortName: "BAL",
961
+ color: "#3B82F6",
962
+ scanIntervalMin: 25e3,
963
+ // Slower: 25-40s between cycles
964
+ scanIntervalMax: 4e4,
965
+ tradeFrequency: 0.4,
966
+ positionSizeMin: 15,
967
+ positionSizeMax: 35,
968
+ leverageMin: 3,
969
+ leverageMax: 10,
970
+ primaryIndicators: ["RSI", "MACD"],
971
+ riskTolerance: "medium",
972
+ preferredPairs: ["BTC/USDT", "ETH/USDT", "SOL/USDT"],
973
+ rsiBias: 50
974
+ },
975
+ {
976
+ id: "conservative-01",
977
+ name: "Conservative Shield",
978
+ shortName: "CON",
979
+ color: "#10B981",
980
+ scanIntervalMin: 35e3,
981
+ // Slower: 35-55s between cycles
982
+ scanIntervalMax: 55e3,
983
+ tradeFrequency: 0.25,
984
+ positionSizeMin: 10,
985
+ positionSizeMax: 20,
986
+ leverageMin: 2,
987
+ leverageMax: 5,
988
+ primaryIndicators: ["Bollinger", "Volume"],
989
+ riskTolerance: "low",
990
+ preferredPairs: ["BTC/USDT", "ETH/USDT"],
991
+ rsiBias: 45
992
+ },
993
+ {
994
+ id: "aggressive-01",
995
+ name: "Aggressive Momentum",
996
+ shortName: "AGG",
997
+ color: "#EF4444",
998
+ scanIntervalMin: 18e3,
999
+ // Slower: 18-30s between cycles
1000
+ scanIntervalMax: 3e4,
1001
+ tradeFrequency: 0.5,
1002
+ positionSizeMin: 25,
1003
+ positionSizeMax: 50,
1004
+ leverageMin: 5,
1005
+ leverageMax: 20,
1006
+ primaryIndicators: ["RSI", "MACD", "EMA", "Volume"],
1007
+ riskTolerance: "high",
1008
+ preferredPairs: ["BTC/USDT", "ETH/USDT", "SOL/USDT", "DOGE/USDT", "AVAX/USDT"],
1009
+ rsiBias: 55
1010
+ }
1011
+ ];
1012
+ PAIR_PRICES = {
1013
+ "BTC/USDT": 67500,
1014
+ "ETH/USDT": 3450,
1015
+ "BNB/USDT": 605,
1016
+ "SOL/USDT": 178,
1017
+ "XRP/USDT": 0.62,
1018
+ "DOGE/USDT": 0.165,
1019
+ "ADA/USDT": 0.45,
1020
+ "AVAX/USDT": 38.5,
1021
+ "ARB/USDT": 1.18,
1022
+ "MATIC/USDT": 0.72,
1023
+ "LINK/USDT": 14.5,
1024
+ "UNI/USDT": 7.8,
1025
+ "AAVE/USDT": 92,
1026
+ "OP/USDT": 2.45,
1027
+ "APT/USDT": 8.9,
1028
+ "INJ/USDT": 24.5,
1029
+ "TIA/USDT": 11.2,
1030
+ "SUI/USDT": 1.65,
1031
+ "DOT/USDT": 7.2,
1032
+ "ATOM/USDT": 9.8,
1033
+ "FIL/USDT": 5.6,
1034
+ "LTC/USDT": 72,
1035
+ "NEAR/USDT": 5.1,
1036
+ "FTM/USDT": 0.42
1037
+ };
1038
+ CHAIN_INFO = {
1039
+ ethereum: { name: "Ethereum", shortName: "ETH", icon: "\u039E" },
1040
+ arbitrum: { name: "Arbitrum", shortName: "ARB", icon: "\u25C6" },
1041
+ bsc: { name: "BSC", shortName: "BSC", icon: "\u25C6" },
1042
+ base: { name: "Base", shortName: "BASE", icon: "\u25CF" },
1043
+ polygon: { name: "Polygon", shortName: "POLY", icon: "\u2B21" },
1044
+ optimism: { name: "Optimism", shortName: "OP", icon: "\u25C9" },
1045
+ avalanche: { name: "Avalanche", shortName: "AVAX", icon: "\u25B2" },
1046
+ linea: { name: "Linea", shortName: "LINEA", icon: "\u2550" },
1047
+ zksync: { name: "zkSync", shortName: "ZK", icon: "\u2B22" },
1048
+ scroll: { name: "Scroll", shortName: "SCRL", icon: "\u25CE" }
1049
+ };
1050
+ NEWS_HEADLINES = [
1051
+ "Fed signals potential rate pause, crypto markets react positively",
1052
+ "Major institutional investor increases BTC allocation by 15%",
1053
+ "On-chain data shows whale accumulation pattern forming",
1054
+ "DeFi TVL reaches new monthly high across major protocols",
1055
+ "Exchange outflows surge as holders move to cold storage",
1056
+ "Options market signals increased volatility expected this week",
1057
+ "Mining difficulty adjustment approaching, hash rate stable",
1058
+ "Regulatory clarity in EU boosts market sentiment",
1059
+ "Stablecoin supply expanding, potential bullish indicator",
1060
+ "Social sentiment score shifts to extreme greed zone",
1061
+ "Cross-chain bridge volume hits record daily high",
1062
+ "Layer 2 adoption metrics show 40% MoM growth"
1063
+ ];
1064
+ idCounter2 = 0;
1065
+ BotSimulationEngine = class {
1066
+ constructor() {
1067
+ this.listeners = [];
1068
+ this.botTimers = /* @__PURE__ */ new Map();
1069
+ this.botStates = /* @__PURE__ */ new Map();
1070
+ this.priceState = /* @__PURE__ */ new Map();
1071
+ this.indicatorState = /* @__PURE__ */ new Map();
1072
+ this.running = false;
1073
+ this.userPairs = [];
1074
+ this.userChains = [];
1075
+ for (const [pair, base] of Object.entries(PAIR_PRICES)) {
1076
+ this.priceState.set(pair, base * (1 + rand3(-0.02, 0.02)));
1077
+ }
1078
+ }
1079
+ // ── Public API ─────────────────────────────────────────────────────────────
1080
+ getStrategies() {
1081
+ return STRATEGY_PERSONALITIES;
1082
+ }
1083
+ start(strategyIds, userPairs, userChains) {
1084
+ this.running = true;
1085
+ this.userPairs = (userPairs || []).map((p) => p.includes("/") ? p : `${p}/USDT`).filter((p) => p in PAIR_PRICES);
1086
+ this.userChains = (userChains || []).filter((c) => c in CHAIN_INFO);
1087
+ const strategies = strategyIds ? STRATEGY_PERSONALITIES.filter((s) => strategyIds.includes(s.id)) : STRATEGY_PERSONALITIES;
1088
+ for (const strategy of strategies) {
1089
+ this.initBotState(strategy);
1090
+ this.scheduleCycle(strategy);
1091
+ }
1092
+ }
1093
+ stop(strategyIds) {
1094
+ const ids = strategyIds || Array.from(this.botTimers.keys());
1095
+ for (const id of ids) {
1096
+ const timer = this.botTimers.get(id);
1097
+ if (timer) {
1098
+ clearTimeout(timer);
1099
+ this.botTimers.delete(id);
1100
+ }
1101
+ }
1102
+ if (!strategyIds) {
1103
+ this.running = false;
1104
+ }
1105
+ }
1106
+ onLog(callback) {
1107
+ this.listeners.push(callback);
1108
+ return () => {
1109
+ this.listeners = this.listeners.filter((l) => l !== callback);
1110
+ };
1111
+ }
1112
+ getBotState(strategyId) {
1113
+ return this.botStates.get(strategyId);
1114
+ }
1115
+ getAllBotStates() {
1116
+ return this.botStates;
1117
+ }
1118
+ isRunning() {
1119
+ return this.running;
1120
+ }
1121
+ emitBootSequence() {
1122
+ const bootMessages = [
1123
+ { msg: "Initializing ONE Trading Engine v3.2.1...", delay: 0 },
1124
+ { msg: "Loading market data feeds...", delay: 500 },
1125
+ { msg: "Connecting to exchange WebSocket streams...", delay: 1200 },
1126
+ { msg: "Calibrating indicator engines (RSI, MACD, EMA, Bollinger)...", delay: 2e3 },
1127
+ { msg: "Loading strategy personalities: balanced-01, conservative-01, aggressive-01", delay: 2800 },
1128
+ { msg: "Risk management module initialized (max drawdown: 15%)", delay: 3600 },
1129
+ { msg: "Portfolio allocation engine ready", delay: 4200 },
1130
+ { msg: "=== All systems online. Starting trading cycles ===", delay: 5e3 }
1131
+ ];
1132
+ for (const { msg, delay } of bootMessages) {
1133
+ setTimeout(() => {
1134
+ this.emit({
1135
+ id: genId3(),
1136
+ timestamp: Date.now(),
1137
+ strategyId: "system",
1138
+ strategyName: "SYSTEM",
1139
+ type: "SYSTEM",
1140
+ message: msg,
1141
+ importance: "medium"
1142
+ });
1143
+ }, delay);
1144
+ }
1145
+ }
1146
+ destroy() {
1147
+ this.stop();
1148
+ this.listeners = [];
1149
+ this.botStates.clear();
1150
+ this.priceState.clear();
1151
+ this.indicatorState.clear();
1152
+ this.userPairs = [];
1153
+ this.userChains = [];
1154
+ }
1155
+ // ── Private Methods ────────────────────────────────────────────────────────
1156
+ emit(entry) {
1157
+ for (const listener of this.listeners) {
1158
+ listener(entry);
1159
+ }
1160
+ }
1161
+ getActivePairs(strategy) {
1162
+ return this.userPairs.length > 0 ? this.userPairs : strategy.preferredPairs;
1163
+ }
1164
+ getActiveChain() {
1165
+ const chains = this.userChains.length > 0 ? this.userChains : ["ethereum", "arbitrum", "bsc"];
1166
+ return pick3(chains);
1167
+ }
1168
+ getChainLabel(chainId) {
1169
+ const info = CHAIN_INFO[chainId];
1170
+ return info ? info.shortName : chainId;
1171
+ }
1172
+ initBotState(strategy) {
1173
+ const activePairs = this.getActivePairs(strategy);
1174
+ const pair = pick3(activePairs);
1175
+ const price = this.priceState.get(pair) || PAIR_PRICES[pair] || 5e4;
1176
+ const indicators = this.generateIndicators(strategy, price);
1177
+ this.indicatorState.set(strategy.id, indicators);
1178
+ this.botStates.set(strategy.id, {
1179
+ strategyId: strategy.id,
1180
+ strategyName: strategy.name,
1181
+ isRunning: true,
1182
+ currentPair: pair,
1183
+ currentPrice: price,
1184
+ indicators,
1185
+ openPositions: [],
1186
+ totalPnl: rand3(-50, 200),
1187
+ totalTrades: randInt3(5, 25),
1188
+ winRate: rand3(0.48, 0.68),
1189
+ lastSignal: "HOLD",
1190
+ lastSignalConfidence: 0
1191
+ });
1192
+ }
1193
+ scheduleCycle(strategy) {
1194
+ if (!this.running) return;
1195
+ const interval = rand3(strategy.scanIntervalMin, strategy.scanIntervalMax);
1196
+ const timer = setTimeout(() => {
1197
+ if (this.running) {
1198
+ this.runBotCycle(strategy);
1199
+ this.scheduleCycle(strategy);
1200
+ }
1201
+ }, interval);
1202
+ this.botTimers.set(strategy.id, timer);
1203
+ }
1204
+ async runBotCycle(strategy) {
1205
+ const state = this.botStates.get(strategy.id);
1206
+ if (!state) return;
1207
+ const activePairs = this.getActivePairs(strategy);
1208
+ const pair = pick3(activePairs);
1209
+ const price = this.simulatePrice(pair);
1210
+ const indicators = this.generateIndicators(strategy, price);
1211
+ this.indicatorState.set(strategy.id, indicators);
1212
+ state.currentPair = pair;
1213
+ state.currentPrice = price;
1214
+ state.indicators = indicators;
1215
+ const entries = [];
1216
+ let delay = 0;
1217
+ const chain = this.getActiveChain();
1218
+ const chainLabel = this.getChainLabel(chain);
1219
+ entries.push({
1220
+ entry: {
1221
+ strategyId: strategy.id,
1222
+ strategyName: strategy.shortName,
1223
+ type: "SCAN",
1224
+ message: `Scanning ${pair} on ${chainLabel} | Price: $${formatPrice(price)}`,
1225
+ data: { pair, chain, chainLabel },
1226
+ importance: "low"
1227
+ },
1228
+ delay
1229
+ });
1230
+ delay += rand3(800, 1500);
1231
+ const thinkingMessages = this.generateThinkingProcess(strategy, pair, price);
1232
+ for (const thinking of thinkingMessages) {
1233
+ entries.push({
1234
+ entry: {
1235
+ strategyId: strategy.id,
1236
+ strategyName: strategy.shortName,
1237
+ type: "THINKING",
1238
+ message: thinking,
1239
+ importance: "low"
1240
+ },
1241
+ delay
1242
+ });
1243
+ delay += rand3(600, 1200);
1244
+ }
1245
+ const indicatorParts = [];
1246
+ if (strategy.primaryIndicators.includes("RSI") || strategy.primaryIndicators.includes("MACD")) {
1247
+ indicatorParts.push(`RSI: ${indicators.rsi.toFixed(1)}`);
1248
+ }
1249
+ if (strategy.primaryIndicators.includes("MACD") || strategy.primaryIndicators.includes("RSI")) {
1250
+ indicatorParts.push(`MACD: ${indicators.macd.histogram > 0 ? "+" : ""}${indicators.macd.histogram.toFixed(3)}`);
1251
+ }
1252
+ if (strategy.primaryIndicators.includes("EMA")) {
1253
+ indicatorParts.push(`EMA: ${indicators.ema.short.toFixed(1)}/${indicators.ema.long.toFixed(1)}`);
1254
+ if (indicators.ema.crossover !== "none") {
1255
+ indicatorParts.push(`[${indicators.ema.crossover.toUpperCase()} CROSS]`);
1256
+ }
1257
+ }
1258
+ if (strategy.primaryIndicators.includes("Bollinger")) {
1259
+ indicatorParts.push(`BB: ${indicators.bollinger.position.toFixed(1)}% width=${indicators.bollinger.width.toFixed(2)}`);
1260
+ }
1261
+ if (strategy.primaryIndicators.includes("Volume")) {
1262
+ indicatorParts.push(`Vol: ${indicators.volume.ratio.toFixed(2)}x avg`);
1263
+ }
1264
+ entries.push({
1265
+ entry: {
1266
+ strategyId: strategy.id,
1267
+ strategyName: strategy.shortName,
1268
+ type: "INDICATOR",
1269
+ message: indicatorParts.join(" | "),
1270
+ data: { indicators },
1271
+ importance: "low"
1272
+ },
1273
+ delay
1274
+ });
1275
+ delay += rand3(800, 1500);
1276
+ if (Math.random() < 0.12) {
1277
+ const sentiment = Math.random() > 0.4 ? "Bullish" : "Bearish";
1278
+ entries.push({
1279
+ entry: {
1280
+ strategyId: strategy.id,
1281
+ strategyName: strategy.shortName,
1282
+ type: "NEWS",
1283
+ message: `[${sentiment}] ${pick3(NEWS_HEADLINES)}`,
1284
+ importance: "medium"
1285
+ },
1286
+ delay
1287
+ });
1288
+ delay += rand3(1e3, 1800);
1289
+ }
1290
+ if (Math.random() < 0.4) {
1291
+ const analysis = this.generateAnalysis(strategy, indicators, pair);
1292
+ entries.push({
1293
+ entry: {
1294
+ strategyId: strategy.id,
1295
+ strategyName: strategy.shortName,
1296
+ type: "ANALYSIS",
1297
+ message: analysis,
1298
+ importance: "medium"
1299
+ },
1300
+ delay
1301
+ });
1302
+ delay += rand3(1e3, 2e3);
1303
+ }
1304
+ const signal = this.evaluateSignal(strategy, indicators);
1305
+ state.lastSignal = signal.direction;
1306
+ state.lastSignalConfidence = signal.confidence;
1307
+ if (signal.direction !== "HOLD") {
1308
+ const strategyContext = this.generateStrategyContext(strategy, signal, indicators, pair);
1309
+ entries.push({
1310
+ entry: {
1311
+ strategyId: strategy.id,
1312
+ strategyName: strategy.shortName,
1313
+ type: "STRATEGY",
1314
+ message: strategyContext,
1315
+ data: {
1316
+ strategy: strategy.name,
1317
+ riskTolerance: strategy.riskTolerance,
1318
+ primaryIndicators: strategy.primaryIndicators,
1319
+ signal: signal.direction,
1320
+ confidence: signal.confidence
1321
+ },
1322
+ importance: "high"
1323
+ },
1324
+ delay
1325
+ });
1326
+ delay += rand3(1500, 2500);
1327
+ entries.push({
1328
+ entry: {
1329
+ strategyId: strategy.id,
1330
+ strategyName: strategy.shortName,
1331
+ type: "SIGNAL",
1332
+ message: `${signal.direction} signal detected | Confidence: ${(signal.confidence * 100).toFixed(1)}% | ${signal.reason}`,
1333
+ data: { signal },
1334
+ importance: "high"
1335
+ },
1336
+ delay
1337
+ });
1338
+ delay += rand3(1200, 2e3);
1339
+ const decision = this.makeTradeDecision(strategy, signal, state);
1340
+ if (decision.execute) {
1341
+ entries.push({
1342
+ entry: {
1343
+ strategyId: strategy.id,
1344
+ strategyName: strategy.shortName,
1345
+ type: "DECISION",
1346
+ message: `Execute ${signal.direction} | Size: ${decision.positionSize.toFixed(1)}% | Leverage: ${decision.leverage}x | Risk/Reward: 1:${decision.riskReward.toFixed(1)}`,
1347
+ data: {
1348
+ strategyName: strategy.name,
1349
+ strategyId: strategy.id,
1350
+ riskTolerance: strategy.riskTolerance,
1351
+ signalReason: signal.reason,
1352
+ confidence: signal.confidence
1353
+ },
1354
+ importance: "high"
1355
+ },
1356
+ delay
1357
+ });
1358
+ delay += rand3(1e3, 1800);
1359
+ const orderId = `ORD_${Date.now().toString(36).toUpperCase()}`;
1360
+ const orderPrice = signal.direction === "LONG" ? price * (1 - rand3(1e-4, 5e-4)) : price * (1 + rand3(1e-4, 5e-4));
1361
+ entries.push({
1362
+ entry: {
1363
+ strategyId: strategy.id,
1364
+ strategyName: strategy.shortName,
1365
+ type: "ORDER",
1366
+ message: `Submitting ${signal.direction} order | ${pair} @ $${formatPrice(orderPrice)} on ${chainLabel} | ID: ${orderId}`,
1367
+ data: {
1368
+ orderId,
1369
+ pair,
1370
+ side: signal.direction,
1371
+ price: orderPrice,
1372
+ leverage: decision.leverage,
1373
+ chain,
1374
+ chainLabel,
1375
+ strategyName: strategy.name,
1376
+ strategyContext,
1377
+ signalReason: signal.reason
1378
+ },
1379
+ importance: "high"
1380
+ },
1381
+ delay
1382
+ });
1383
+ delay += rand3(2e3, 4e3);
1384
+ const fillPrice = orderPrice * (1 + rand3(-3e-4, 3e-4));
1385
+ const slippage = Math.abs(fillPrice - orderPrice) / orderPrice * 100;
1386
+ entries.push({
1387
+ entry: {
1388
+ strategyId: strategy.id,
1389
+ strategyName: strategy.shortName,
1390
+ type: "FILLED",
1391
+ message: `Order FILLED | ${pair} ${signal.direction} @ $${formatPrice(fillPrice)} on ${chainLabel} | Slippage: ${slippage.toFixed(4)}% | ID: ${orderId}`,
1392
+ data: {
1393
+ orderId,
1394
+ fillPrice,
1395
+ slippage,
1396
+ chain,
1397
+ chainLabel,
1398
+ strategyName: strategy.name,
1399
+ executedBy: strategy.id
1400
+ },
1401
+ importance: "high"
1402
+ },
1403
+ delay
1404
+ });
1405
+ const position = {
1406
+ id: orderId,
1407
+ pair,
1408
+ side: signal.direction,
1409
+ entryPrice: fillPrice,
1410
+ currentPrice: price,
1411
+ size: decision.positionSize,
1412
+ leverage: decision.leverage,
1413
+ pnl: 0,
1414
+ pnlPercent: 0
1415
+ };
1416
+ state.openPositions = [...state.openPositions.slice(-2), position];
1417
+ state.totalTrades++;
1418
+ } else {
1419
+ entries.push({
1420
+ entry: {
1421
+ strategyId: strategy.id,
1422
+ strategyName: strategy.shortName,
1423
+ type: "DECISION",
1424
+ message: `SKIP - ${decision.reason}`,
1425
+ importance: "medium"
1426
+ },
1427
+ delay
1428
+ });
1429
+ }
1430
+ }
1431
+ if (state.openPositions.length > 0 && Math.random() < 0.5) {
1432
+ delay += rand3(1500, 2500);
1433
+ let totalPositionPnl = 0;
1434
+ const pnlParts = [];
1435
+ for (const pos of state.openPositions) {
1436
+ pos.currentPrice = this.simulatePrice(pos.pair);
1437
+ const priceDiff = pos.side === "LONG" ? (pos.currentPrice - pos.entryPrice) / pos.entryPrice : (pos.entryPrice - pos.currentPrice) / pos.entryPrice;
1438
+ pos.pnlPercent = priceDiff * pos.leverage * 100;
1439
+ pos.pnl = priceDiff * pos.leverage * pos.size;
1440
+ totalPositionPnl += pos.pnl;
1441
+ pnlParts.push(`${pos.pair} ${pos.side}: ${pos.pnlPercent >= 0 ? "+" : ""}${pos.pnlPercent.toFixed(2)}%`);
1442
+ }
1443
+ state.totalPnl += totalPositionPnl * rand3(0.01, 0.05);
1444
+ if (state.openPositions.length > 1 && Math.random() < 0.3) {
1445
+ const closed = state.openPositions.shift();
1446
+ const finalPnl = closed.pnlPercent;
1447
+ if (finalPnl > 0) {
1448
+ state.winRate = state.winRate * 0.95 + 0.05;
1449
+ } else {
1450
+ state.winRate = state.winRate * 0.95;
1451
+ }
1452
+ state.winRate = clamp(state.winRate, 0.35, 0.75);
1453
+ pnlParts.push(`CLOSED ${closed.pair}: ${finalPnl >= 0 ? "+" : ""}${finalPnl.toFixed(2)}%`);
1454
+ }
1455
+ entries.push({
1456
+ entry: {
1457
+ strategyId: strategy.id,
1458
+ strategyName: strategy.shortName,
1459
+ type: "PNL",
1460
+ message: pnlParts.join(" | "),
1461
+ data: { totalPnl: state.totalPnl, positions: state.openPositions.length },
1462
+ importance: "medium"
1463
+ },
1464
+ delay
1465
+ });
1466
+ }
1467
+ if (Math.random() < 0.2) {
1468
+ delay += rand3(1e3, 2e3);
1469
+ const exposure = state.openPositions.reduce((sum, p) => sum + p.size * p.leverage, 0);
1470
+ const maxDrawdown = rand3(2, 12);
1471
+ entries.push({
1472
+ entry: {
1473
+ strategyId: strategy.id,
1474
+ strategyName: strategy.shortName,
1475
+ type: "RISK",
1476
+ message: `Portfolio exposure: ${exposure.toFixed(1)}% | Max drawdown: ${maxDrawdown.toFixed(1)}% | Open positions: ${state.openPositions.length} | Win rate: ${(state.winRate * 100).toFixed(1)}%`,
1477
+ importance: exposure > 80 ? "high" : "low"
1478
+ },
1479
+ delay
1480
+ });
1481
+ }
1482
+ for (const { entry, delay: d } of entries) {
1483
+ setTimeout(() => {
1484
+ if (this.running) {
1485
+ this.emit({
1486
+ ...entry,
1487
+ id: genId3(),
1488
+ timestamp: Date.now()
1489
+ });
1490
+ }
1491
+ }, d);
1492
+ }
1493
+ }
1494
+ simulatePrice(pair) {
1495
+ const current = this.priceState.get(pair) || PAIR_PRICES[pair] || 5e4;
1496
+ const volatility = pair.includes("DOGE") ? 5e-3 : pair.includes("BTC") ? 2e-3 : 3e-3;
1497
+ const drift = rand3(-volatility, volatility);
1498
+ const newPrice = current * (1 + drift);
1499
+ this.priceState.set(pair, newPrice);
1500
+ return newPrice;
1501
+ }
1502
+ generateIndicators(strategy, price) {
1503
+ const prev = this.indicatorState.get(strategy.id);
1504
+ const prevRsi = prev?.rsi ?? strategy.rsiBias;
1505
+ const rsiMean = strategy.rsiBias;
1506
+ const rsiDrift = rand3(-8, 8);
1507
+ const rsiReversion = (rsiMean - prevRsi) * 0.15;
1508
+ const rsi = clamp(prevRsi + rsiDrift + rsiReversion, 8, 95);
1509
+ const macdBias = rsi > 65 ? 0.3 : rsi < 35 ? -0.3 : 0;
1510
+ const prevHist = prev?.macd.histogram ?? 0;
1511
+ const histogram = clamp(prevHist * 0.7 + rand3(-0.5, 0.5) + macdBias, -2, 2);
1512
+ const macdValue = histogram * rand3(0.8, 1.5);
1513
+ const macdSignal = macdValue - histogram;
1514
+ const prevShort = prev?.ema.short ?? price;
1515
+ const prevLong = prev?.ema.long ?? price;
1516
+ const emaShort = prevShort * 0.9 + price * 0.1;
1517
+ const emaLong = prevLong * 0.95 + price * 0.05;
1518
+ let crossover = "none";
1519
+ if (prevShort <= prevLong && emaShort > emaLong) crossover = "golden";
1520
+ else if (prevShort >= prevLong && emaShort < emaLong) crossover = "death";
1521
+ const bbMiddle = price;
1522
+ const bbWidth = price * rand3(0.01, 0.04);
1523
+ const bbUpper = bbMiddle + bbWidth;
1524
+ const bbLower = bbMiddle - bbWidth;
1525
+ const bbPosition = (price - bbLower) / (bbUpper - bbLower) * 100;
1526
+ const volRatio = rand3(0.3, 2.5);
1527
+ const volCurrent = rand3(1e5, 5e6);
1528
+ return {
1529
+ rsi,
1530
+ macd: { value: macdValue, signal: macdSignal, histogram },
1531
+ ema: { short: emaShort, long: emaLong, crossover },
1532
+ bollinger: { upper: bbUpper, middle: bbMiddle, lower: bbLower, width: bbWidth / price, position: bbPosition },
1533
+ volume: { current: volCurrent, average: volCurrent / volRatio, ratio: volRatio }
1534
+ };
1535
+ }
1536
+ generateThinkingProcess(strategy, pair, price) {
1537
+ const thoughts = [];
1538
+ const pairBase = pair.split("/")[0];
1539
+ const thinkingTemplates = [
1540
+ `Analyzing ${pairBase} market structure...`,
1541
+ `Checking ${strategy.primaryIndicators.join(", ")} confluence...`,
1542
+ `Evaluating risk parameters for ${strategy.riskTolerance} tolerance...`,
1543
+ `Scanning order book depth at $${formatPrice(price)}...`,
1544
+ `Cross-referencing with historical patterns...`,
1545
+ `Calculating optimal entry zone...`,
1546
+ `Assessing market sentiment indicators...`,
1547
+ `Monitoring whale activity on ${pairBase}...`,
1548
+ `Comparing momentum across timeframes...`,
1549
+ `Validating support/resistance levels...`
1550
+ ];
1551
+ const numThoughts = randInt3(1, 3);
1552
+ const shuffled = [...thinkingTemplates].sort(() => Math.random() - 0.5);
1553
+ for (let i = 0; i < numThoughts; i++) {
1554
+ thoughts.push(shuffled[i]);
1555
+ }
1556
+ return thoughts;
1557
+ }
1558
+ generateStrategyContext(strategy, signal, indicators, pair) {
1559
+ const contexts = [];
1560
+ contexts.push(`[${strategy.name}]`);
1561
+ const riskLevel = strategy.riskTolerance === "high" ? "aggressive" : strategy.riskTolerance === "low" ? "conservative" : "balanced";
1562
+ contexts.push(`Risk: ${riskLevel}`);
1563
+ if (indicators.rsi < 35 || indicators.rsi > 65) {
1564
+ contexts.push(`RSI ${indicators.rsi < 35 ? "oversold" : "overbought"} (${indicators.rsi.toFixed(1)})`);
1565
+ }
1566
+ if (indicators.ema.crossover !== "none") {
1567
+ contexts.push(`EMA ${indicators.ema.crossover} cross`);
1568
+ }
1569
+ if (Math.abs(indicators.macd.histogram) > 0.3) {
1570
+ contexts.push(`MACD ${indicators.macd.histogram > 0 ? "bullish" : "bearish"} momentum`);
1571
+ }
1572
+ const confLevel = signal.confidence > 0.7 ? "HIGH" : signal.confidence > 0.5 ? "MEDIUM" : "LOW";
1573
+ contexts.push(`Confidence: ${confLevel}`);
1574
+ return contexts.join(" | ");
1575
+ }
1576
+ generateAnalysis(strategy, indicators, pair) {
1577
+ const analyses = [];
1578
+ if (indicators.rsi > 70) {
1579
+ analyses.push(`RSI at ${indicators.rsi.toFixed(1)} - overbought territory, watching for reversal`);
1580
+ } else if (indicators.rsi < 30) {
1581
+ analyses.push(`RSI at ${indicators.rsi.toFixed(1)} - oversold, potential bounce setup`);
1582
+ } else if (indicators.rsi > 55) {
1583
+ analyses.push(`RSI trending bullish at ${indicators.rsi.toFixed(1)}`);
1584
+ } else {
1585
+ analyses.push(`RSI neutral at ${indicators.rsi.toFixed(1)}, no clear direction`);
1586
+ }
1587
+ if (indicators.macd.histogram > 0.5) {
1588
+ analyses.push("MACD histogram expanding positive - momentum building");
1589
+ } else if (indicators.macd.histogram < -0.5) {
1590
+ analyses.push("MACD histogram expanding negative - bearish pressure");
1591
+ }
1592
+ if (indicators.ema.crossover === "golden") {
1593
+ analyses.push("EMA golden cross detected - strong bullish signal");
1594
+ } else if (indicators.ema.crossover === "death") {
1595
+ analyses.push("EMA death cross detected - bearish warning");
1596
+ }
1597
+ if (indicators.bollinger.position > 90) {
1598
+ analyses.push(`Price near upper Bollinger band (${indicators.bollinger.position.toFixed(0)}%) - potential resistance`);
1599
+ } else if (indicators.bollinger.position < 10) {
1600
+ analyses.push(`Price near lower Bollinger band (${indicators.bollinger.position.toFixed(0)}%) - potential support`);
1601
+ }
1602
+ if (indicators.volume.ratio > 1.8) {
1603
+ analyses.push(`Volume spike ${indicators.volume.ratio.toFixed(1)}x average - high activity`);
1604
+ }
1605
+ return analyses.length > 0 ? analyses.join(" | ") : `${pair} consolidating - waiting for clearer setup`;
1606
+ }
1607
+ evaluateSignal(strategy, indicators) {
1608
+ let bullScore = 0;
1609
+ let bearScore = 0;
1610
+ const reasons = [];
1611
+ if (indicators.rsi < 30) {
1612
+ bullScore += 2;
1613
+ reasons.push("RSI oversold");
1614
+ } else if (indicators.rsi < 40) {
1615
+ bullScore += 1;
1616
+ reasons.push("RSI low");
1617
+ } else if (indicators.rsi > 70) {
1618
+ bearScore += 2;
1619
+ reasons.push("RSI overbought");
1620
+ } else if (indicators.rsi > 60) {
1621
+ bearScore += 1;
1622
+ reasons.push("RSI high");
1623
+ }
1624
+ if (indicators.macd.histogram > 0.3) {
1625
+ bullScore += 1.5;
1626
+ reasons.push("MACD bullish");
1627
+ } else if (indicators.macd.histogram < -0.3) {
1628
+ bearScore += 1.5;
1629
+ reasons.push("MACD bearish");
1630
+ }
1631
+ if (indicators.ema.crossover === "golden") {
1632
+ bullScore += 2.5;
1633
+ reasons.push("Golden cross");
1634
+ } else if (indicators.ema.crossover === "death") {
1635
+ bearScore += 2.5;
1636
+ reasons.push("Death cross");
1637
+ } else if (indicators.ema.short > indicators.ema.long) {
1638
+ bullScore += 0.5;
1639
+ } else {
1640
+ bearScore += 0.5;
1641
+ }
1642
+ if (indicators.bollinger.position < 15) {
1643
+ bullScore += 1;
1644
+ reasons.push("BB support");
1645
+ } else if (indicators.bollinger.position > 85) {
1646
+ bearScore += 1;
1647
+ reasons.push("BB resistance");
1648
+ }
1649
+ if (indicators.volume.ratio > 1.5) {
1650
+ if (bullScore > bearScore) bullScore += 1;
1651
+ else bearScore += 1;
1652
+ reasons.push("Volume confirms");
1653
+ }
1654
+ const netScore = bullScore - bearScore;
1655
+ const confidence = Math.min(Math.abs(netScore) / 6, 0.95);
1656
+ const threshold = strategy.riskTolerance === "high" ? 1.5 : strategy.riskTolerance === "medium" ? 2 : 2.5;
1657
+ if (Math.random() > strategy.tradeFrequency) {
1658
+ return { direction: "HOLD", confidence: 0, reason: "Cycle skip" };
1659
+ }
1660
+ if (netScore > threshold) {
1661
+ return { direction: "LONG", confidence, reason: reasons.slice(0, 3).join(", ") };
1662
+ } else if (netScore < -threshold) {
1663
+ return { direction: "SHORT", confidence, reason: reasons.slice(0, 3).join(", ") };
1664
+ }
1665
+ return { direction: "HOLD", confidence: 0, reason: "No clear signal" };
1666
+ }
1667
+ makeTradeDecision(strategy, signal, state) {
1668
+ if (state.openPositions.length >= 3) {
1669
+ return { execute: false, positionSize: 0, leverage: 0, riskReward: 0, reason: "Max positions reached (3)" };
1670
+ }
1671
+ const minConfidence = strategy.riskTolerance === "high" ? 0.3 : strategy.riskTolerance === "medium" ? 0.45 : 0.6;
1672
+ if (signal.confidence < minConfidence) {
1673
+ return { execute: false, positionSize: 0, leverage: 0, riskReward: 0, reason: `Confidence too low (${(signal.confidence * 100).toFixed(0)}% < ${(minConfidence * 100).toFixed(0)}%)` };
1674
+ }
1675
+ const positionSize = rand3(strategy.positionSizeMin, strategy.positionSizeMax);
1676
+ const leverage = randInt3(strategy.leverageMin, strategy.leverageMax);
1677
+ const riskReward = rand3(1.2, 3.5);
1678
+ return { execute: true, positionSize, leverage, riskReward, reason: "" };
1679
+ }
1680
+ };
1681
+ botSimulationEngine = new BotSimulationEngine();
1682
+ }
1683
+ });
3
1684
  function getConfig() {
4
1685
  {
5
1686
  throw new Error("ONE SDK not initialized. Call initOneSDK() first.");
@@ -1693,7 +3374,1529 @@ function useAITrading() {
1693
3374
  error
1694
3375
  };
1695
3376
  }
3377
+ function useAIAgents(includeInactive = false) {
3378
+ const [agents, setAgents] = useState([]);
3379
+ const [shareRates, setShareRates] = useState({});
3380
+ const [isLoading, setIsLoading] = useState(true);
3381
+ const [error, setError] = useState(null);
3382
+ const fetchAgents = useCallback(async () => {
3383
+ setIsLoading(true);
3384
+ setError(null);
3385
+ try {
3386
+ const result = await getClient().getAgentConfigs({ includeInactive });
3387
+ if (result.success && result.data) {
3388
+ setAgents(result.data.agents || []);
3389
+ setShareRates(result.data.shareRates || {});
3390
+ } else {
3391
+ setError(result.error?.message || "Failed to fetch agents");
3392
+ }
3393
+ } catch (err) {
3394
+ setError(err instanceof Error ? err.message : "Unknown error");
3395
+ } finally {
3396
+ setIsLoading(false);
3397
+ }
3398
+ }, [includeInactive]);
3399
+ useEffect(() => {
3400
+ fetchAgents();
3401
+ }, [fetchAgents]);
3402
+ return { agents, shareRates, isLoading, error, refresh: fetchAgents };
3403
+ }
3404
+ function useAIAgent(agentId) {
3405
+ const [agent, setAgent] = useState(null);
3406
+ const [params, setParams] = useState(null);
3407
+ const [isLoading, setIsLoading] = useState(true);
3408
+ const [error, setError] = useState(null);
3409
+ const fetchAgent = useCallback(async () => {
3410
+ if (!agentId) {
3411
+ setIsLoading(false);
3412
+ return;
3413
+ }
3414
+ setIsLoading(true);
3415
+ setError(null);
3416
+ try {
3417
+ const result = await getClient().getAgentConfigs({ agentId });
3418
+ if (result.success && result.data?.agent) {
3419
+ setAgent(result.data.agent);
3420
+ } else {
3421
+ setError(result.error?.message || "Agent not found");
3422
+ }
3423
+ } catch (err) {
3424
+ setError(err instanceof Error ? err.message : "Unknown error");
3425
+ } finally {
3426
+ setIsLoading(false);
3427
+ }
3428
+ }, [agentId]);
3429
+ useEffect(() => {
3430
+ fetchAgent();
3431
+ }, [fetchAgent]);
3432
+ const calculateParams = useCallback(async (amount, cycleDays) => {
3433
+ if (!agentId) return null;
3434
+ try {
3435
+ const result = await getClient().calculateAgentParams({ agentId, amount, cycleDays });
3436
+ if (result.success && result.data) {
3437
+ setParams(result.data);
3438
+ return result.data;
3439
+ }
3440
+ return null;
3441
+ } catch (err) {
3442
+ setError(err instanceof Error ? err.message : "Failed to calculate params");
3443
+ return null;
3444
+ }
3445
+ }, [agentId]);
3446
+ return { agent, params, isLoading, error, refresh: fetchAgent, calculateParams };
3447
+ }
3448
+ function useAIAgentSubscription() {
3449
+ const [isLoading, setIsLoading] = useState(false);
3450
+ const [error, setError] = useState(null);
3451
+ const subscribe = useCallback(async (agentId, amount, cycleDays, txHash) => {
3452
+ setIsLoading(true);
3453
+ setError(null);
3454
+ try {
3455
+ const result = await getClient().createAIOrder({
3456
+ strategyId: agentId,
3457
+ amount,
3458
+ lockPeriodDays: cycleDays,
3459
+ txHashDeposit: txHash
3460
+ });
3461
+ if (!result.success) {
3462
+ setError(result.error?.message || "Failed to subscribe");
3463
+ }
3464
+ return result;
3465
+ } catch (err) {
3466
+ const errorMsg = err instanceof Error ? err.message : "Subscription failed";
3467
+ setError(errorMsg);
3468
+ return { success: false, error: { code: "SUBSCRIPTION_ERROR", message: errorMsg } };
3469
+ } finally {
3470
+ setIsLoading(false);
3471
+ }
3472
+ }, []);
3473
+ return { subscribe, isLoading, error };
3474
+ }
3475
+
3476
+ // src/hooks/useForexTrading.ts
3477
+ init_forex();
3478
+ var _forexAccessToken = null;
3479
+ var _forexEngineUrl = "https://api.one23.io";
3480
+ function setForexAccessToken(token) {
3481
+ _forexAccessToken = token;
3482
+ }
3483
+ function clearForexAccessToken() {
3484
+ _forexAccessToken = null;
3485
+ }
3486
+ function setForexEngineUrl(url) {
3487
+ _forexEngineUrl = url;
3488
+ }
3489
+ async function forexApi(path, options) {
3490
+ try {
3491
+ const headers = {
3492
+ "Content-Type": "application/json"
3493
+ };
3494
+ if (_forexAccessToken) {
3495
+ headers["Authorization"] = `Bearer ${_forexAccessToken}`;
3496
+ }
3497
+ const res = await fetch(`${_forexEngineUrl}${path}`, { ...options, headers });
3498
+ if (!res.ok) return null;
3499
+ const json = await res.json();
3500
+ return json?.data ?? json;
3501
+ } catch {
3502
+ return null;
3503
+ }
3504
+ }
3505
+ function useForexPools(options) {
3506
+ const [pools, setPools] = useState(FOREX_POOL_DEFAULTS);
3507
+ const [isLoading, setIsLoading] = useState(false);
3508
+ const [error, setError] = useState(null);
3509
+ const fetchPools = useCallback(async () => {
3510
+ setIsLoading(true);
3511
+ try {
3512
+ const data = await forexApi("/api/forex/pools");
3513
+ if (data?.pools) {
3514
+ setPools(data.pools.map((p) => ({
3515
+ id: p.type ?? p.id,
3516
+ nameKey: `forex.pool_${p.type ?? p.id}`,
3517
+ descriptionKey: `forex.pool_${p.type ?? p.id}_desc`,
3518
+ allocation: p.allocation ?? (p.type === "clearing" ? 0.5 : p.type === "hedging" ? 0.3 : 0.2),
3519
+ totalSize: p.totalSize ?? p.total_size ?? 0,
3520
+ utilization: p.utilization ?? 0,
3521
+ color: p.type === "clearing" ? "#3B82F6" : p.type === "hedging" ? "#F59E0B" : "#10B981",
3522
+ apy7d: p.apy7d ?? 0,
3523
+ apy30d: p.apy30d ?? 0,
3524
+ netFlow24h: p.netFlow24h ?? 0,
3525
+ txCount24h: p.txCount24h ?? 0,
3526
+ txCountTotal: p.txCountTotal ?? 0,
3527
+ totalDeposits: p.totalDeposits ?? 0,
3528
+ totalWithdrawals: p.totalWithdrawals ?? 0,
3529
+ profitDistributed: p.profitDistributed ?? 0,
3530
+ lastUpdated: p.lastUpdated ?? Date.now()
3531
+ })));
3532
+ }
3533
+ setError(null);
3534
+ } catch (err) {
3535
+ setError(err instanceof Error ? err.message : "Failed to fetch pools");
3536
+ } finally {
3537
+ setIsLoading(false);
3538
+ }
3539
+ }, []);
3540
+ useEffect(() => {
3541
+ fetchPools();
3542
+ if (options?.refreshInterval) {
3543
+ const timer = setInterval(fetchPools, options.refreshInterval);
3544
+ return () => clearInterval(timer);
3545
+ }
3546
+ }, [fetchPools, options?.refreshInterval]);
3547
+ return { pools, isLoading, error, refresh: fetchPools };
3548
+ }
3549
+ function useForexInvestments(options) {
3550
+ const [investments, setInvestments] = useState([]);
3551
+ const [isLoading, setIsLoading] = useState(false);
3552
+ const [error, setError] = useState(null);
3553
+ const fetchInvestments = useCallback(async () => {
3554
+ setIsLoading(true);
3555
+ try {
3556
+ const data = await forexApi("/api/forex/investments");
3557
+ if (data?.investments) {
3558
+ setInvestments(data.investments.map(mapInvestment));
3559
+ }
3560
+ setError(null);
3561
+ } catch {
3562
+ setError("Failed to fetch investments");
3563
+ } finally {
3564
+ setIsLoading(false);
3565
+ }
3566
+ }, []);
3567
+ const createInvestment = useCallback(async (params) => {
3568
+ setIsLoading(true);
3569
+ try {
3570
+ const data = await forexApi("/api/forex/investments", {
3571
+ method: "POST",
3572
+ body: JSON.stringify(params)
3573
+ });
3574
+ if (data?.investment) {
3575
+ const inv2 = mapInvestment(data.investment);
3576
+ setInvestments((prev) => [inv2, ...prev]);
3577
+ return inv2;
3578
+ }
3579
+ const inv = createLocalInvestment(params);
3580
+ setInvestments((prev) => [inv, ...prev]);
3581
+ return inv;
3582
+ } catch {
3583
+ const inv = createLocalInvestment(params);
3584
+ setInvestments((prev) => [inv, ...prev]);
3585
+ return inv;
3586
+ } finally {
3587
+ setIsLoading(false);
3588
+ }
3589
+ }, []);
3590
+ const redeemInvestment = useCallback(async (investmentId) => {
3591
+ try {
3592
+ await forexApi(`/api/forex/investments/${investmentId}/redeem`, { method: "POST" });
3593
+ setInvestments((prev) => prev.map(
3594
+ (inv) => inv.id === investmentId ? { ...inv, status: "redeemed" } : inv
3595
+ ));
3596
+ return true;
3597
+ } catch {
3598
+ return false;
3599
+ }
3600
+ }, []);
3601
+ useEffect(() => {
3602
+ fetchInvestments();
3603
+ if (options?.refreshInterval) {
3604
+ const timer = setInterval(fetchInvestments, options.refreshInterval);
3605
+ return () => clearInterval(timer);
3606
+ }
3607
+ }, [fetchInvestments, options?.refreshInterval]);
3608
+ const portfolioSummary = useMemo(() => {
3609
+ const active = investments.filter((i) => i.status === "active");
3610
+ return {
3611
+ totalInvested: active.reduce((s, i) => s + i.amount, 0),
3612
+ totalValue: active.reduce((s, i) => s + i.currentValue, 0),
3613
+ totalProfit: active.reduce((s, i) => s + i.profit, 0),
3614
+ activeCount: active.length
3615
+ };
3616
+ }, [investments]);
3617
+ return { investments, isLoading, error, createInvestment, redeemInvestment, refresh: fetchInvestments, portfolioSummary };
3618
+ }
3619
+ function useForexSimulation(options) {
3620
+ const maxLogs = options?.maxLogs ?? 500;
3621
+ const [logs, setLogs] = useState([]);
3622
+ const [poolTxs, setPoolTxs] = useState([]);
3623
+ const [isRunning, setIsRunning] = useState(false);
3624
+ const [stats, setStats] = useState({ totalPnl: 0, totalTrades: 0, totalPips: 0, totalLots: 0 });
3625
+ const engineRef = useRef(null);
3626
+ const getEngine = useCallback(() => {
3627
+ if (!engineRef.current) {
3628
+ try {
3629
+ const { forexSimulationEngine: forexSimulationEngine2 } = (init_ForexSimulationEngine(), __toCommonJS(ForexSimulationEngine_exports));
3630
+ engineRef.current = forexSimulationEngine2;
3631
+ } catch {
3632
+ }
3633
+ }
3634
+ return engineRef.current;
3635
+ }, []);
3636
+ const start = useCallback(() => {
3637
+ const engine = getEngine();
3638
+ if (!engine) return;
3639
+ if (!engine.isRunning()) engine.start();
3640
+ setIsRunning(true);
3641
+ }, [getEngine]);
3642
+ const stop = useCallback(() => {
3643
+ const engine = getEngine();
3644
+ if (engine) engine.stop();
3645
+ setIsRunning(false);
3646
+ }, [getEngine]);
3647
+ const clearLogs = useCallback(() => {
3648
+ setLogs([]);
3649
+ setPoolTxs([]);
3650
+ }, []);
3651
+ useEffect(() => {
3652
+ const engine = getEngine();
3653
+ if (!engine) return;
3654
+ const unsubLog = engine.onLog((entry) => {
3655
+ setLogs((prev) => {
3656
+ const next = [...prev, entry];
3657
+ return next.length > maxLogs ? next.slice(-maxLogs) : next;
3658
+ });
3659
+ const s = engine.getStats();
3660
+ setStats({ totalPnl: s.totalPnl, totalTrades: s.totalTrades, totalPips: s.totalPips, totalLots: s.totalLots });
3661
+ });
3662
+ const unsubTx = engine.onPoolTransaction((tx) => {
3663
+ setPoolTxs((prev) => [...prev.slice(-999), tx]);
3664
+ });
3665
+ return () => {
3666
+ unsubLog();
3667
+ unsubTx();
3668
+ };
3669
+ }, [getEngine, maxLogs]);
3670
+ return { logs, poolTransactions: poolTxs, isRunning, stats, start, stop, clearLogs };
3671
+ }
3672
+ function useForexPoolData() {
3673
+ const [snapshots, setSnapshots] = useState({ clearing: [], hedging: [], insurance: [] });
3674
+ const [transactions, setTransactions] = useState([]);
3675
+ const [isInitialized, setIsInitialized] = useState(false);
3676
+ const initialize = useCallback(() => {
3677
+ if (isInitialized) return;
3678
+ try {
3679
+ const { ForexPoolDataGenerator: ForexPoolDataGenerator2 } = (init_ForexPoolDataGenerator(), __toCommonJS(ForexPoolDataGenerator_exports));
3680
+ const gen = ForexPoolDataGenerator2.getInstance();
3681
+ setSnapshots(gen.generateAllSnapshots());
3682
+ setTransactions(gen.generateAllTransactions());
3683
+ setIsInitialized(true);
3684
+ } catch {
3685
+ }
3686
+ }, [isInitialized]);
3687
+ return { snapshots, transactions, isInitialized, initialize };
3688
+ }
3689
+ function useForexTrading(options) {
3690
+ const pools = useForexPools({ refreshInterval: options?.poolRefreshInterval });
3691
+ const investments = useForexInvestments({ refreshInterval: options?.investmentRefreshInterval });
3692
+ const simulation = useForexSimulation();
3693
+ const poolData = useForexPoolData();
3694
+ return {
3695
+ pools,
3696
+ investments,
3697
+ simulation,
3698
+ poolData,
3699
+ capitalSplit: FOREX_CAPITAL_SPLIT,
3700
+ agent: FOREX_AGENT,
3701
+ currencyPairs: (init_forex(), __toCommonJS(forex_exports)).FOREX_CURRENCY_PAIRS,
3702
+ cycleOptions: (init_forex(), __toCommonJS(forex_exports)).FOREX_CYCLE_OPTIONS,
3703
+ computePoolAllocations,
3704
+ estimateProfit: estimateForexProfit
3705
+ };
3706
+ }
3707
+ function mapInvestment(raw) {
3708
+ const cycleDays = raw.cycleDays ?? raw.cycle_days ?? 90;
3709
+ const cycleOption = FOREX_CYCLE_OPTIONS.find((c) => c.days === cycleDays) || FOREX_CYCLE_OPTIONS[2];
3710
+ const amount = typeof raw.amount === "string" ? parseFloat(raw.amount) : raw.amount ?? 0;
3711
+ const allocs = computePoolAllocations(amount);
3712
+ return {
3713
+ id: raw.id,
3714
+ userId: raw.userId ?? raw.user_id,
3715
+ amount,
3716
+ currentValue: raw.currentValue ?? raw.current_value ?? amount,
3717
+ profit: raw.profit ?? 0,
3718
+ status: raw.status ?? "active",
3719
+ selectedPairs: raw.selectedPairs ?? raw.selected_pairs ?? [],
3720
+ cycleDays,
3721
+ cycleOption,
3722
+ feeRate: raw.feeRate ?? cycleOption.feeRate,
3723
+ commissionRate: raw.commissionRate ?? cycleOption.commissionRate,
3724
+ startDate: raw.startDate ?? raw.start_date ?? (/* @__PURE__ */ new Date()).toISOString(),
3725
+ endDate: raw.endDate ?? raw.end_date ?? "",
3726
+ tradingCapital: raw.tradingCapital ?? allocs.tradingCapital,
3727
+ totalPoolReserves: raw.totalPoolReserves ?? allocs.totalPoolReserves,
3728
+ poolAllocations: raw.poolAllocations ?? {
3729
+ clearing: allocs.clearing,
3730
+ hedging: allocs.hedging,
3731
+ insurance: allocs.insurance
3732
+ },
3733
+ tradeWeight: raw.tradeWeight ?? 0,
3734
+ totalLots: raw.totalLots ?? 0,
3735
+ totalPips: raw.totalPips ?? 0,
3736
+ totalTrades: raw.totalTrades ?? 0,
3737
+ positions: raw.positions ?? [],
3738
+ tradeHistory: raw.tradeHistory ?? [],
3739
+ redeemedAt: raw.redeemedAt,
3740
+ createdAt: raw.createdAt,
3741
+ updatedAt: raw.updatedAt
3742
+ };
3743
+ }
3744
+ function createLocalInvestment(params) {
3745
+ const { amount, selectedPairs, cycleDays } = params;
3746
+ const cycleOption = FOREX_CYCLE_OPTIONS.find((c) => c.days === cycleDays) || FOREX_CYCLE_OPTIONS[2];
3747
+ const allocs = computePoolAllocations(amount);
3748
+ const now = /* @__PURE__ */ new Date();
3749
+ const endDate = new Date(now);
3750
+ endDate.setDate(endDate.getDate() + cycleDays);
3751
+ return {
3752
+ id: `fx_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
3753
+ amount,
3754
+ currentValue: amount,
3755
+ profit: 0,
3756
+ status: "active",
3757
+ selectedPairs,
3758
+ cycleDays,
3759
+ cycleOption,
3760
+ startDate: now.toISOString(),
3761
+ endDate: endDate.toISOString(),
3762
+ tradingCapital: allocs.tradingCapital,
3763
+ totalPoolReserves: allocs.totalPoolReserves,
3764
+ poolAllocations: { clearing: allocs.clearing, hedging: allocs.hedging, insurance: allocs.insurance },
3765
+ tradeWeight: 0,
3766
+ totalLots: 0,
3767
+ totalPips: 0,
3768
+ totalTrades: 0,
3769
+ positions: [],
3770
+ tradeHistory: []
3771
+ };
3772
+ }
3773
+ function useBotSimulation(options) {
3774
+ const maxLogs = options?.maxLogs ?? 500;
3775
+ const [logs, setLogs] = useState([]);
3776
+ const [isRunning, setIsRunning] = useState(false);
3777
+ const [strategies, setStrategies] = useState([]);
3778
+ const [botStatesMap, setBotStatesMap] = useState(/* @__PURE__ */ new Map());
3779
+ const engineRef = useRef(null);
3780
+ const unsubRef = useRef(null);
3781
+ const getEngine = useCallback(() => {
3782
+ if (!engineRef.current) {
3783
+ try {
3784
+ const { botSimulationEngine: botSimulationEngine2 } = (init_BotSimulationEngine(), __toCommonJS(BotSimulationEngine_exports));
3785
+ engineRef.current = botSimulationEngine2;
3786
+ setStrategies(botSimulationEngine2.getStrategies());
3787
+ } catch {
3788
+ }
3789
+ }
3790
+ return engineRef.current;
3791
+ }, []);
3792
+ const logsByStrategy = useMemo(() => {
3793
+ const grouped = /* @__PURE__ */ new Map();
3794
+ for (const log of logs) {
3795
+ const existing = grouped.get(log.strategyId) || [];
3796
+ grouped.set(log.strategyId, [...existing, log]);
3797
+ }
3798
+ return grouped;
3799
+ }, [logs]);
3800
+ const start = useCallback((strategyIds, userPairs, userChains) => {
3801
+ const engine = getEngine();
3802
+ if (!engine) return;
3803
+ const ids = strategyIds || options?.strategyIds;
3804
+ const pairs = userPairs || options?.userPairs;
3805
+ const chains = userChains || options?.userChains;
3806
+ if (!engine.isRunning()) {
3807
+ engine.start(ids, pairs, chains);
3808
+ }
3809
+ setIsRunning(true);
3810
+ }, [getEngine, options?.strategyIds, options?.userPairs, options?.userChains]);
3811
+ const stop = useCallback((strategyIds) => {
3812
+ const engine = getEngine();
3813
+ if (engine) {
3814
+ engine.stop(strategyIds);
3815
+ if (!strategyIds) {
3816
+ setIsRunning(false);
3817
+ }
3818
+ }
3819
+ }, [getEngine]);
3820
+ const clearLogs = useCallback(() => {
3821
+ setLogs([]);
3822
+ }, []);
3823
+ const emitBootSequence = useCallback(() => {
3824
+ const engine = getEngine();
3825
+ if (engine) {
3826
+ engine.emitBootSequence();
3827
+ }
3828
+ }, [getEngine]);
3829
+ const getBotState = useCallback((strategyId) => {
3830
+ return botStatesMap.get(strategyId);
3831
+ }, [botStatesMap]);
3832
+ useEffect(() => {
3833
+ const engine = getEngine();
3834
+ if (!engine) return;
3835
+ setIsRunning(engine.isRunning());
3836
+ unsubRef.current = engine.onLog((entry) => {
3837
+ setLogs((prev) => {
3838
+ const next = [...prev, entry];
3839
+ return next.length > maxLogs ? next.slice(-maxLogs) : next;
3840
+ });
3841
+ const state = engine.getBotState(entry.strategyId);
3842
+ if (state) {
3843
+ setBotStatesMap((prev) => {
3844
+ const next = new Map(prev);
3845
+ next.set(entry.strategyId, state);
3846
+ return next;
3847
+ });
3848
+ }
3849
+ });
3850
+ return () => {
3851
+ if (unsubRef.current) {
3852
+ unsubRef.current();
3853
+ unsubRef.current = null;
3854
+ }
3855
+ };
3856
+ }, [getEngine, maxLogs]);
3857
+ useEffect(() => {
3858
+ if (options?.autoStart) {
3859
+ const engine = getEngine();
3860
+ if (engine && !engine.isRunning()) {
3861
+ emitBootSequence();
3862
+ setTimeout(() => {
3863
+ start();
3864
+ }, 5500);
3865
+ }
3866
+ }
3867
+ }, [options?.autoStart, getEngine, emitBootSequence, start]);
3868
+ useEffect(() => {
3869
+ if (!isRunning) return;
3870
+ const interval = setInterval(() => {
3871
+ const engine = getEngine();
3872
+ if (engine) {
3873
+ const states = engine.getAllBotStates();
3874
+ if (states.size > 0) {
3875
+ setBotStatesMap(new Map(states));
3876
+ }
3877
+ }
3878
+ }, 1e3);
3879
+ return () => clearInterval(interval);
3880
+ }, [isRunning, getEngine]);
3881
+ return {
3882
+ logs,
3883
+ logsByStrategy,
3884
+ botStates: botStatesMap,
3885
+ isRunning,
3886
+ strategies,
3887
+ start,
3888
+ stop,
3889
+ clearLogs,
3890
+ emitBootSequence,
3891
+ getBotState
3892
+ };
3893
+ }
3894
+ var _consoleAccessToken = null;
3895
+ var _consoleEngineUrl = "https://api.one23.io";
3896
+ function setConsoleAccessToken(token) {
3897
+ _consoleAccessToken = token;
3898
+ }
3899
+ function clearConsoleAccessToken() {
3900
+ _consoleAccessToken = null;
3901
+ }
3902
+ function setConsoleEngineUrl(url) {
3903
+ _consoleEngineUrl = url;
3904
+ }
3905
+ async function consoleApi(path, options) {
3906
+ try {
3907
+ const headers = {
3908
+ "Content-Type": "application/json"
3909
+ };
3910
+ if (_consoleAccessToken) {
3911
+ headers["Authorization"] = `Bearer ${_consoleAccessToken}`;
3912
+ }
3913
+ const res = await fetch(`${_consoleEngineUrl}${path}`, { ...options, headers });
3914
+ if (!res.ok) return null;
3915
+ const json = await res.json();
3916
+ return json?.data ?? json;
3917
+ } catch {
3918
+ return null;
3919
+ }
3920
+ }
3921
+ function generateSimulatedPositions(strategyIds) {
3922
+ const strategies = [
3923
+ { id: "balanced-01", name: "Balanced Alpha", shortName: "BAL" },
3924
+ { id: "conservative-01", name: "Conservative Shield", shortName: "CON" },
3925
+ { id: "aggressive-01", name: "Aggressive Momentum", shortName: "AGG" }
3926
+ ];
3927
+ const pairs = ["BTC/USDT", "ETH/USDT", "SOL/USDT", "ARB/USDT", "AVAX/USDT"];
3928
+ const basePrices = {
3929
+ "BTC/USDT": 67500,
3930
+ "ETH/USDT": 3450,
3931
+ "SOL/USDT": 178,
3932
+ "ARB/USDT": 1.18,
3933
+ "AVAX/USDT": 38.5
3934
+ };
3935
+ const positions = [];
3936
+ const filteredStrategies = strategyIds ? strategies.filter((s) => strategyIds.includes(s.id)) : strategies;
3937
+ for (const strategy of filteredStrategies) {
3938
+ const numPositions = Math.floor(Math.random() * 4);
3939
+ for (let i = 0; i < numPositions; i++) {
3940
+ const pair = pairs[Math.floor(Math.random() * pairs.length)];
3941
+ const basePrice = basePrices[pair];
3942
+ const side = Math.random() > 0.5 ? "LONG" : "SHORT";
3943
+ const entryPrice = basePrice * (1 + (Math.random() - 0.5) * 0.02);
3944
+ const currentPrice = basePrice * (1 + (Math.random() - 0.5) * 0.03);
3945
+ const leverage = Math.floor(Math.random() * 10) + 2;
3946
+ const size = Math.floor(Math.random() * 1e3) + 100;
3947
+ const margin = size / leverage;
3948
+ const priceDiff = side === "LONG" ? (currentPrice - entryPrice) / entryPrice : (entryPrice - currentPrice) / entryPrice;
3949
+ const pnlPercent = priceDiff * leverage * 100;
3950
+ const pnl = size * priceDiff * leverage;
3951
+ positions.push({
3952
+ id: `pos_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
3953
+ strategyId: strategy.id,
3954
+ strategyName: strategy.name,
3955
+ pair,
3956
+ side,
3957
+ entryPrice,
3958
+ currentPrice,
3959
+ size,
3960
+ leverage,
3961
+ margin,
3962
+ pnl,
3963
+ pnlPercent,
3964
+ status: "open",
3965
+ stopLoss: entryPrice * (side === "LONG" ? 0.95 : 1.05),
3966
+ takeProfit: entryPrice * (side === "LONG" ? 1.1 : 0.9),
3967
+ liquidationPrice: entryPrice * (side === "LONG" ? 1 - 1 / leverage : 1 + 1 / leverage),
3968
+ openTime: Date.now() - Math.floor(Math.random() * 864e5),
3969
+ chain: ["ethereum", "arbitrum", "base"][Math.floor(Math.random() * 3)],
3970
+ aiConfidence: Math.random() * 0.4 + 0.5,
3971
+ aiReasoning: `${side === "LONG" ? "Bullish" : "Bearish"} momentum detected on ${pair}`
3972
+ });
3973
+ }
3974
+ }
3975
+ return positions;
3976
+ }
3977
+ function useAIPositions(options) {
3978
+ const [positions, setPositions] = useState([]);
3979
+ const [isLoading, setIsLoading] = useState(false);
3980
+ const [error, setError] = useState(null);
3981
+ const fetchPositions = useCallback(async () => {
3982
+ setIsLoading(true);
3983
+ setError(null);
3984
+ try {
3985
+ if (options?.simulation) {
3986
+ const simulated = generateSimulatedPositions(options?.strategyIds);
3987
+ setPositions(simulated);
3988
+ } else {
3989
+ let path = "/api/v1/ai-quant/positions";
3990
+ const params = new URLSearchParams();
3991
+ if (options?.strategyId) {
3992
+ params.append("strategyId", options.strategyId);
3993
+ }
3994
+ if (options?.strategyIds?.length) {
3995
+ params.append("strategyIds", options.strategyIds.join(","));
3996
+ }
3997
+ if (options?.status) {
3998
+ const statuses = Array.isArray(options.status) ? options.status : [options.status];
3999
+ params.append("status", statuses.join(","));
4000
+ }
4001
+ if (params.toString()) {
4002
+ path += `?${params.toString()}`;
4003
+ }
4004
+ const data = await consoleApi(path);
4005
+ if (data?.positions) {
4006
+ setPositions(data.positions.map(mapPosition));
4007
+ }
4008
+ }
4009
+ } catch (err) {
4010
+ setError(err instanceof Error ? err.message : "Failed to fetch positions");
4011
+ } finally {
4012
+ setIsLoading(false);
4013
+ }
4014
+ }, [options?.simulation, options?.strategyId, options?.strategyIds, options?.status]);
4015
+ const closePosition = useCallback(async (positionId) => {
4016
+ try {
4017
+ if (options?.simulation) {
4018
+ setPositions((prev) => prev.map(
4019
+ (p) => p.id === positionId ? { ...p, status: "closed", closeTime: Date.now() } : p
4020
+ ));
4021
+ return true;
4022
+ }
4023
+ await consoleApi(`/api/v1/ai-quant/positions/${positionId}/close`, { method: "POST" });
4024
+ setPositions((prev) => prev.map(
4025
+ (p) => p.id === positionId ? { ...p, status: "closed", closeTime: Date.now() } : p
4026
+ ));
4027
+ return true;
4028
+ } catch {
4029
+ return false;
4030
+ }
4031
+ }, [options?.simulation]);
4032
+ const updateStopLoss = useCallback(async (positionId, stopLoss) => {
4033
+ try {
4034
+ if (options?.simulation) {
4035
+ setPositions((prev) => prev.map(
4036
+ (p) => p.id === positionId ? { ...p, stopLoss } : p
4037
+ ));
4038
+ return true;
4039
+ }
4040
+ await consoleApi(`/api/v1/ai-quant/positions/${positionId}`, {
4041
+ method: "PATCH",
4042
+ body: JSON.stringify({ stopLoss })
4043
+ });
4044
+ setPositions((prev) => prev.map(
4045
+ (p) => p.id === positionId ? { ...p, stopLoss } : p
4046
+ ));
4047
+ return true;
4048
+ } catch {
4049
+ return false;
4050
+ }
4051
+ }, [options?.simulation]);
4052
+ const updateTakeProfit = useCallback(async (positionId, takeProfit) => {
4053
+ try {
4054
+ if (options?.simulation) {
4055
+ setPositions((prev) => prev.map(
4056
+ (p) => p.id === positionId ? { ...p, takeProfit } : p
4057
+ ));
4058
+ return true;
4059
+ }
4060
+ await consoleApi(`/api/v1/ai-quant/positions/${positionId}`, {
4061
+ method: "PATCH",
4062
+ body: JSON.stringify({ takeProfit })
4063
+ });
4064
+ setPositions((prev) => prev.map(
4065
+ (p) => p.id === positionId ? { ...p, takeProfit } : p
4066
+ ));
4067
+ return true;
4068
+ } catch {
4069
+ return false;
4070
+ }
4071
+ }, [options?.simulation]);
4072
+ useEffect(() => {
4073
+ fetchPositions();
4074
+ if (options?.pollInterval) {
4075
+ const timer = setInterval(fetchPositions, options.pollInterval);
4076
+ return () => clearInterval(timer);
4077
+ }
4078
+ }, [fetchPositions, options?.pollInterval]);
4079
+ const openPositions = useMemo(
4080
+ () => positions.filter((p) => p.status === "open"),
4081
+ [positions]
4082
+ );
4083
+ const closedPositions = useMemo(
4084
+ () => positions.filter((p) => p.status === "closed"),
4085
+ [positions]
4086
+ );
4087
+ const summary = useMemo(() => {
4088
+ const open = positions.filter((p) => p.status === "open");
4089
+ const byStrategy = {};
4090
+ for (const pos of open) {
4091
+ if (!byStrategy[pos.strategyId]) {
4092
+ byStrategy[pos.strategyId] = { count: 0, pnl: 0, exposure: 0 };
4093
+ }
4094
+ byStrategy[pos.strategyId].count++;
4095
+ byStrategy[pos.strategyId].pnl += pos.pnl;
4096
+ byStrategy[pos.strategyId].exposure += pos.size;
4097
+ }
4098
+ const totalExposure = open.reduce((sum, p) => sum + p.size, 0);
4099
+ const totalPnl = positions.reduce((sum, p) => sum + p.pnl, 0);
4100
+ const unrealizedPnl = open.reduce((sum, p) => sum + p.pnl, 0);
4101
+ const avgLeverage = open.length > 0 ? open.reduce((sum, p) => sum + p.leverage, 0) / open.length : 0;
4102
+ return {
4103
+ totalPositions: positions.length,
4104
+ openCount: open.length,
4105
+ totalExposure,
4106
+ totalPnl,
4107
+ unrealizedPnl,
4108
+ avgLeverage,
4109
+ byStrategy
4110
+ };
4111
+ }, [positions]);
4112
+ return {
4113
+ positions,
4114
+ openPositions,
4115
+ closedPositions,
4116
+ isLoading,
4117
+ error,
4118
+ refresh: fetchPositions,
4119
+ closePosition,
4120
+ updateStopLoss,
4121
+ updateTakeProfit,
4122
+ summary
4123
+ };
4124
+ }
4125
+ function mapPosition(raw) {
4126
+ return {
4127
+ id: raw.id,
4128
+ strategyId: raw.strategyId ?? raw.strategy_id,
4129
+ strategyName: raw.strategyName ?? raw.strategy_name ?? "",
4130
+ pair: raw.pair,
4131
+ side: raw.side,
4132
+ entryPrice: raw.entryPrice ?? raw.entry_price ?? 0,
4133
+ currentPrice: raw.currentPrice ?? raw.current_price ?? 0,
4134
+ size: raw.size ?? 0,
4135
+ leverage: raw.leverage ?? 1,
4136
+ margin: raw.margin ?? raw.size / (raw.leverage ?? 1),
4137
+ pnl: raw.pnl ?? 0,
4138
+ pnlPercent: raw.pnlPercent ?? raw.pnl_percent ?? 0,
4139
+ status: raw.status ?? "open",
4140
+ stopLoss: raw.stopLoss ?? raw.stop_loss,
4141
+ takeProfit: raw.takeProfit ?? raw.take_profit,
4142
+ liquidationPrice: raw.liquidationPrice ?? raw.liquidation_price,
4143
+ openTime: raw.openTime ?? raw.open_time ?? Date.now(),
4144
+ closeTime: raw.closeTime ?? raw.close_time,
4145
+ chain: raw.chain,
4146
+ orderId: raw.orderId ?? raw.order_id,
4147
+ aiConfidence: raw.aiConfidence ?? raw.ai_confidence,
4148
+ aiReasoning: raw.aiReasoning ?? raw.ai_reasoning
4149
+ };
4150
+ }
4151
+ function generateSimulatedDecisions(strategyIds, limit = 50) {
4152
+ const strategies = [
4153
+ { id: "balanced-01", name: "Balanced Alpha" },
4154
+ { id: "conservative-01", name: "Conservative Shield" },
4155
+ { id: "aggressive-01", name: "Aggressive Momentum" }
4156
+ ];
4157
+ const pairs = ["BTC/USDT", "ETH/USDT", "SOL/USDT", "ARB/USDT", "AVAX/USDT"];
4158
+ const actions = ["OPEN_LONG", "OPEN_SHORT", "CLOSE_LONG", "CLOSE_SHORT", "HOLD", "SKIP"];
4159
+ const reasonings = {
4160
+ OPEN_LONG: [
4161
+ "RSI oversold with MACD bullish crossover",
4162
+ "Golden cross detected on EMA, volume confirming",
4163
+ "Support level held, momentum building",
4164
+ "Bullish divergence on RSI, trend reversal likely"
4165
+ ],
4166
+ OPEN_SHORT: [
4167
+ "RSI overbought with MACD bearish crossover",
4168
+ "Death cross on EMA, volume increasing",
4169
+ "Resistance level rejected, bearish pressure",
4170
+ "Bearish divergence detected, reversal expected"
4171
+ ],
4172
+ CLOSE_LONG: [
4173
+ "Take profit target reached",
4174
+ "Momentum weakening, securing profits",
4175
+ "Risk management triggered"
4176
+ ],
4177
+ CLOSE_SHORT: [
4178
+ "Take profit target reached",
4179
+ "Bearish momentum exhausted",
4180
+ "Stop loss proximity warning"
4181
+ ],
4182
+ HOLD: [
4183
+ "No clear signal, waiting for confirmation",
4184
+ "Consolidation phase, insufficient momentum",
4185
+ "Mixed indicators, patience advised"
4186
+ ],
4187
+ SKIP: [
4188
+ "Confidence below threshold",
4189
+ "Risk parameters exceeded",
4190
+ "Position limit reached"
4191
+ ]
4192
+ };
4193
+ const filteredStrategies = strategyIds ? strategies.filter((s) => strategyIds.includes(s.id)) : strategies;
4194
+ const decisions = [];
4195
+ const now = Date.now();
4196
+ for (let i = 0; i < limit; i++) {
4197
+ const strategy = filteredStrategies[Math.floor(Math.random() * filteredStrategies.length)];
4198
+ const pair = pairs[Math.floor(Math.random() * pairs.length)];
4199
+ const action = actions[Math.floor(Math.random() * actions.length)];
4200
+ const confidence = Math.random() * 0.5 + 0.3;
4201
+ const executed = action !== "HOLD" && action !== "SKIP" && confidence > 0.5;
4202
+ const reasoningList = reasonings[action];
4203
+ decisions.push({
4204
+ id: `dec_${now - i * 6e4}_${Math.random().toString(36).slice(2, 8)}`,
4205
+ timestamp: now - i * (Math.random() * 3e5 + 6e4),
4206
+ strategyId: strategy.id,
4207
+ strategyName: strategy.name,
4208
+ pair,
4209
+ action,
4210
+ confidence,
4211
+ reasoning: reasoningList[Math.floor(Math.random() * reasoningList.length)],
4212
+ indicators: {
4213
+ rsi: Math.random() * 100,
4214
+ macd: (Math.random() - 0.5) * 2,
4215
+ ema: Math.random() > 0.5 ? "bullish" : "bearish",
4216
+ volume: Math.random() * 2 + 0.5,
4217
+ bollinger: Math.random() > 0.5 ? "upper" : "lower"
4218
+ },
4219
+ signals: [
4220
+ `RSI ${Math.random() > 0.5 ? "oversold" : "overbought"}`,
4221
+ `MACD ${Math.random() > 0.5 ? "bullish" : "bearish"}`
4222
+ ],
4223
+ executed,
4224
+ positionId: executed ? `pos_${Date.now()}_${Math.random().toString(36).slice(2, 6)}` : void 0,
4225
+ price: 5e4 * (1 + (Math.random() - 0.5) * 0.1),
4226
+ size: executed ? Math.floor(Math.random() * 1e3) + 100 : void 0,
4227
+ leverage: executed ? Math.floor(Math.random() * 10) + 2 : void 0
4228
+ });
4229
+ }
4230
+ return decisions.sort((a, b) => b.timestamp - a.timestamp);
4231
+ }
4232
+ function useAIDecisions(options) {
4233
+ const limit = options?.limit ?? 100;
4234
+ const [decisions, setDecisions] = useState([]);
4235
+ const [isLoading, setIsLoading] = useState(false);
4236
+ const [error, setError] = useState(null);
4237
+ const fetchDecisions = useCallback(async () => {
4238
+ setIsLoading(true);
4239
+ setError(null);
4240
+ try {
4241
+ if (options?.simulation) {
4242
+ const simulated = generateSimulatedDecisions(options?.strategyIds, limit);
4243
+ setDecisions(simulated);
4244
+ } else {
4245
+ let path = "/api/v1/ai-quant/decisions";
4246
+ const params = new URLSearchParams();
4247
+ if (options?.strategyId) {
4248
+ params.append("strategyId", options.strategyId);
4249
+ }
4250
+ if (options?.strategyIds?.length) {
4251
+ params.append("strategyIds", options.strategyIds.join(","));
4252
+ }
4253
+ if (options?.actions?.length) {
4254
+ params.append("actions", options.actions.join(","));
4255
+ }
4256
+ params.append("limit", limit.toString());
4257
+ if (params.toString()) {
4258
+ path += `?${params.toString()}`;
4259
+ }
4260
+ const res = await fetch(`https://api.one23.io${path}`);
4261
+ if (res.ok) {
4262
+ const data = await res.json();
4263
+ if (data?.decisions) {
4264
+ setDecisions(data.decisions.map(mapDecision));
4265
+ }
4266
+ }
4267
+ }
4268
+ } catch (err) {
4269
+ setError(err instanceof Error ? err.message : "Failed to fetch decisions");
4270
+ } finally {
4271
+ setIsLoading(false);
4272
+ }
4273
+ }, [options?.simulation, options?.strategyId, options?.strategyIds, options?.actions, limit]);
4274
+ useEffect(() => {
4275
+ fetchDecisions();
4276
+ if (options?.pollInterval) {
4277
+ const timer = setInterval(fetchDecisions, options.pollInterval);
4278
+ return () => clearInterval(timer);
4279
+ }
4280
+ }, [fetchDecisions, options?.pollInterval]);
4281
+ const getByStrategy = useCallback(
4282
+ (strategyId) => decisions.filter((d) => d.strategyId === strategyId),
4283
+ [decisions]
4284
+ );
4285
+ const getByAction = useCallback(
4286
+ (action) => decisions.filter((d) => d.action === action),
4287
+ [decisions]
4288
+ );
4289
+ const recentDecisions = useMemo(
4290
+ () => decisions.slice(0, 10),
4291
+ [decisions]
4292
+ );
4293
+ const executedDecisions = useMemo(
4294
+ () => decisions.filter((d) => d.executed),
4295
+ [decisions]
4296
+ );
4297
+ const stats = useMemo(() => {
4298
+ const executed = decisions.filter((d) => d.executed);
4299
+ const byAction = {
4300
+ OPEN_LONG: 0,
4301
+ OPEN_SHORT: 0,
4302
+ CLOSE_LONG: 0,
4303
+ CLOSE_SHORT: 0,
4304
+ HOLD: 0,
4305
+ SKIP: 0
4306
+ };
4307
+ const byStrategy = {};
4308
+ for (const d of decisions) {
4309
+ byAction[d.action]++;
4310
+ byStrategy[d.strategyId] = (byStrategy[d.strategyId] || 0) + 1;
4311
+ }
4312
+ const avgConfidence = decisions.length > 0 ? decisions.reduce((sum, d) => sum + d.confidence, 0) / decisions.length : 0;
4313
+ return {
4314
+ totalDecisions: decisions.length,
4315
+ executedCount: executed.length,
4316
+ executionRate: decisions.length > 0 ? executed.length / decisions.length : 0,
4317
+ byAction,
4318
+ byStrategy,
4319
+ avgConfidence
4320
+ };
4321
+ }, [decisions]);
4322
+ return {
4323
+ decisions,
4324
+ recentDecisions,
4325
+ executedDecisions,
4326
+ isLoading,
4327
+ error,
4328
+ refresh: fetchDecisions,
4329
+ getByStrategy,
4330
+ getByAction,
4331
+ stats
4332
+ };
4333
+ }
4334
+ function mapDecision(raw) {
4335
+ return {
4336
+ id: raw.id,
4337
+ timestamp: raw.timestamp ?? Date.now(),
4338
+ strategyId: raw.strategyId ?? raw.strategy_id,
4339
+ strategyName: raw.strategyName ?? raw.strategy_name ?? "",
4340
+ pair: raw.pair,
4341
+ action: raw.action,
4342
+ confidence: raw.confidence ?? 0,
4343
+ reasoning: raw.reasoning ?? "",
4344
+ indicators: raw.indicators ?? {},
4345
+ signals: raw.signals ?? [],
4346
+ executed: raw.executed ?? false,
4347
+ positionId: raw.positionId ?? raw.position_id,
4348
+ price: raw.price,
4349
+ size: raw.size,
4350
+ leverage: raw.leverage
4351
+ };
4352
+ }
4353
+
4354
+ // src/types/console.ts
4355
+ var DEFAULT_RISK_STATUS = {
4356
+ timestamp: Date.now(),
4357
+ totalExposure: 0,
4358
+ maxExposure: 1e5,
4359
+ exposurePercent: 0,
4360
+ dailyPnl: 0,
4361
+ dailyPnlLimit: 5e3,
4362
+ dailyPnlPercent: 0,
4363
+ dailyTradeCount: 0,
4364
+ dailyTradeLimit: 50,
4365
+ currentDrawdown: 0,
4366
+ maxDrawdown: 15,
4367
+ drawdownPercent: 0,
4368
+ openPositions: 0,
4369
+ maxPositions: 10,
4370
+ riskLevel: "low",
4371
+ tradingStatus: "active",
4372
+ warnings: []
4373
+ };
4374
+ function calculateRiskLevel(exposurePercent, drawdownPercent, dailyPnlPercent) {
4375
+ const worstMetric = Math.max(exposurePercent, drawdownPercent, Math.abs(dailyPnlPercent));
4376
+ if (worstMetric >= 90) return "critical";
4377
+ if (worstMetric >= 70) return "high";
4378
+ if (worstMetric >= 40) return "medium";
4379
+ return "low";
4380
+ }
4381
+
4382
+ // src/hooks/useAIRiskStatus.ts
4383
+ function generateSimulatedRiskStatus() {
4384
+ const totalExposure = Math.random() * 8e4 + 1e4;
4385
+ const maxExposure = 1e5;
4386
+ const exposurePercent = totalExposure / maxExposure * 100;
4387
+ const dailyPnl = (Math.random() - 0.3) * 3e3;
4388
+ const dailyPnlLimit = 5e3;
4389
+ const dailyPnlPercent = Math.abs(dailyPnl) / dailyPnlLimit * 100;
4390
+ const currentDrawdown = Math.random() * 10;
4391
+ const maxDrawdown = 15;
4392
+ const drawdownPercent = currentDrawdown / maxDrawdown * 100;
4393
+ const openPositions = Math.floor(Math.random() * 8);
4394
+ const maxPositions = 10;
4395
+ const dailyTradeCount = Math.floor(Math.random() * 30);
4396
+ const dailyTradeLimit = 50;
4397
+ const riskLevel = calculateRiskLevel(exposurePercent, drawdownPercent, dailyPnlPercent);
4398
+ const warnings = [];
4399
+ if (exposurePercent > 70) warnings.push("High portfolio exposure");
4400
+ if (drawdownPercent > 60) warnings.push("Approaching max drawdown");
4401
+ if (dailyPnlPercent > 80 && dailyPnl < 0) warnings.push("Daily loss limit warning");
4402
+ if (openPositions >= maxPositions - 1) warnings.push("Position limit nearly reached");
4403
+ let tradingStatus = "active";
4404
+ if (riskLevel === "critical") tradingStatus = "stopped";
4405
+ else if (riskLevel === "high" && warnings.length > 1) tradingStatus = "paused";
4406
+ const strategyRisks = {
4407
+ "balanced-01": {
4408
+ exposure: Math.random() * 3e4,
4409
+ drawdown: Math.random() * 5,
4410
+ riskLevel: Math.random() > 0.7 ? "medium" : "low"
4411
+ },
4412
+ "conservative-01": {
4413
+ exposure: Math.random() * 2e4,
4414
+ drawdown: Math.random() * 3,
4415
+ riskLevel: "low"
4416
+ },
4417
+ "aggressive-01": {
4418
+ exposure: Math.random() * 4e4,
4419
+ drawdown: Math.random() * 8,
4420
+ riskLevel: Math.random() > 0.5 ? "high" : "medium"
4421
+ }
4422
+ };
4423
+ return {
4424
+ timestamp: Date.now(),
4425
+ totalExposure,
4426
+ maxExposure,
4427
+ exposurePercent,
4428
+ dailyPnl,
4429
+ dailyPnlLimit,
4430
+ dailyPnlPercent,
4431
+ dailyTradeCount,
4432
+ dailyTradeLimit,
4433
+ currentDrawdown,
4434
+ maxDrawdown,
4435
+ drawdownPercent,
4436
+ openPositions,
4437
+ maxPositions,
4438
+ riskLevel,
4439
+ tradingStatus,
4440
+ warnings,
4441
+ strategyRisks
4442
+ };
4443
+ }
4444
+ function useAIRiskStatus(options) {
4445
+ const [riskStatus, setRiskStatus] = useState(DEFAULT_RISK_STATUS);
4446
+ const [isLoading, setIsLoading] = useState(false);
4447
+ const [error, setError] = useState(null);
4448
+ const fetchRiskStatus = useCallback(async () => {
4449
+ setIsLoading(true);
4450
+ setError(null);
4451
+ try {
4452
+ if (options?.simulation) {
4453
+ const simulated = generateSimulatedRiskStatus();
4454
+ setRiskStatus(simulated);
4455
+ } else {
4456
+ let path = "/api/v1/ai-quant/risk-status";
4457
+ if (options?.strategyId) {
4458
+ path += `?strategyId=${options.strategyId}`;
4459
+ }
4460
+ const res = await fetch(`https://api.one23.io${path}`);
4461
+ if (res.ok) {
4462
+ const data = await res.json();
4463
+ if (data) {
4464
+ setRiskStatus(mapRiskStatus(data));
4465
+ }
4466
+ }
4467
+ }
4468
+ } catch (err) {
4469
+ setError(err instanceof Error ? err.message : "Failed to fetch risk status");
4470
+ } finally {
4471
+ setIsLoading(false);
4472
+ }
4473
+ }, [options?.simulation, options?.strategyId]);
4474
+ useEffect(() => {
4475
+ fetchRiskStatus();
4476
+ if (options?.pollInterval) {
4477
+ const timer = setInterval(fetchRiskStatus, options.pollInterval);
4478
+ return () => clearInterval(timer);
4479
+ }
4480
+ }, [fetchRiskStatus, options?.pollInterval]);
4481
+ const pauseTrading = useCallback(async () => {
4482
+ try {
4483
+ if (options?.simulation) {
4484
+ setRiskStatus((prev) => ({ ...prev, tradingStatus: "paused" }));
4485
+ return true;
4486
+ }
4487
+ const res = await fetch("https://api.one23.io/api/v1/ai-quant/trading/pause", {
4488
+ method: "POST"
4489
+ });
4490
+ if (res.ok) {
4491
+ setRiskStatus((prev) => ({ ...prev, tradingStatus: "paused" }));
4492
+ return true;
4493
+ }
4494
+ return false;
4495
+ } catch {
4496
+ return false;
4497
+ }
4498
+ }, [options?.simulation]);
4499
+ const resumeTrading = useCallback(async () => {
4500
+ try {
4501
+ if (options?.simulation) {
4502
+ setRiskStatus((prev) => ({ ...prev, tradingStatus: "active" }));
4503
+ return true;
4504
+ }
4505
+ const res = await fetch("https://api.one23.io/api/v1/ai-quant/trading/resume", {
4506
+ method: "POST"
4507
+ });
4508
+ if (res.ok) {
4509
+ setRiskStatus((prev) => ({ ...prev, tradingStatus: "active" }));
4510
+ return true;
4511
+ }
4512
+ return false;
4513
+ } catch {
4514
+ return false;
4515
+ }
4516
+ }, [options?.simulation]);
4517
+ const resetDailyLimits = useCallback(async () => {
4518
+ try {
4519
+ if (options?.simulation) {
4520
+ setRiskStatus((prev) => ({
4521
+ ...prev,
4522
+ dailyPnl: 0,
4523
+ dailyPnlPercent: 0,
4524
+ dailyTradeCount: 0,
4525
+ warnings: prev.warnings.filter((w) => !w.includes("Daily"))
4526
+ }));
4527
+ return true;
4528
+ }
4529
+ const res = await fetch("https://api.one23.io/api/v1/ai-quant/risk/reset-daily", {
4530
+ method: "POST"
4531
+ });
4532
+ return res.ok;
4533
+ } catch {
4534
+ return false;
4535
+ }
4536
+ }, [options?.simulation]);
4537
+ const isWithinLimits = useMemo(() => {
4538
+ return riskStatus.exposurePercent < 90 && riskStatus.drawdownPercent < 90 && riskStatus.dailyPnlPercent < 90 && riskStatus.openPositions < riskStatus.maxPositions;
4539
+ }, [riskStatus]);
4540
+ const canTrade = useMemo(() => {
4541
+ return riskStatus.tradingStatus === "active" && isWithinLimits;
4542
+ }, [riskStatus.tradingStatus, isWithinLimits]);
4543
+ return {
4544
+ riskStatus,
4545
+ isLoading,
4546
+ error,
4547
+ refresh: fetchRiskStatus,
4548
+ isWithinLimits,
4549
+ canTrade,
4550
+ riskLevel: riskStatus.riskLevel,
4551
+ tradingStatus: riskStatus.tradingStatus,
4552
+ warnings: riskStatus.warnings,
4553
+ pauseTrading,
4554
+ resumeTrading,
4555
+ resetDailyLimits
4556
+ };
4557
+ }
4558
+ function mapRiskStatus(raw) {
4559
+ const exposurePercent = raw.maxExposure > 0 ? raw.totalExposure / raw.maxExposure * 100 : 0;
4560
+ const dailyPnlPercent = raw.dailyPnlLimit > 0 ? Math.abs(raw.dailyPnl) / raw.dailyPnlLimit * 100 : 0;
4561
+ const drawdownPercent = raw.maxDrawdown > 0 ? raw.currentDrawdown / raw.maxDrawdown * 100 : 0;
4562
+ return {
4563
+ timestamp: raw.timestamp ?? Date.now(),
4564
+ totalExposure: raw.totalExposure ?? raw.total_exposure ?? 0,
4565
+ maxExposure: raw.maxExposure ?? raw.max_exposure ?? 1e5,
4566
+ exposurePercent,
4567
+ dailyPnl: raw.dailyPnl ?? raw.daily_pnl ?? 0,
4568
+ dailyPnlLimit: raw.dailyPnlLimit ?? raw.daily_pnl_limit ?? 5e3,
4569
+ dailyPnlPercent,
4570
+ dailyTradeCount: raw.dailyTradeCount ?? raw.daily_trade_count ?? 0,
4571
+ dailyTradeLimit: raw.dailyTradeLimit ?? raw.daily_trade_limit ?? 50,
4572
+ currentDrawdown: raw.currentDrawdown ?? raw.current_drawdown ?? 0,
4573
+ maxDrawdown: raw.maxDrawdown ?? raw.max_drawdown ?? 15,
4574
+ drawdownPercent,
4575
+ openPositions: raw.openPositions ?? raw.open_positions ?? 0,
4576
+ maxPositions: raw.maxPositions ?? raw.max_positions ?? 10,
4577
+ riskLevel: raw.riskLevel ?? raw.risk_level ?? calculateRiskLevel(exposurePercent, drawdownPercent, dailyPnlPercent),
4578
+ tradingStatus: raw.tradingStatus ?? raw.trading_status ?? "active",
4579
+ warnings: raw.warnings ?? [],
4580
+ strategyRisks: raw.strategyRisks ?? raw.strategy_risks
4581
+ };
4582
+ }
4583
+
4584
+ // src/hooks/useAIQuantConsole.ts
4585
+ function useAIQuantConsole(options) {
4586
+ const simulation = options?.simulation ?? true;
4587
+ const pollInterval = options?.pollInterval ?? 5e3;
4588
+ const maxLogs = options?.maxLogs ?? 500;
4589
+ const strategyIds = options?.strategyIds;
4590
+ const botSim = useBotSimulation({
4591
+ maxLogs,
4592
+ strategyIds,
4593
+ autoStart: false
4594
+ });
4595
+ const positionsHook = useAIPositions({
4596
+ strategyIds,
4597
+ pollInterval,
4598
+ simulation
4599
+ });
4600
+ const decisionsHook = useAIDecisions({
4601
+ strategyIds,
4602
+ pollInterval,
4603
+ simulation,
4604
+ limit: 100
4605
+ });
4606
+ const riskHook = useAIRiskStatus({
4607
+ pollInterval,
4608
+ simulation
4609
+ });
4610
+ const agents = useMemo(() => {
4611
+ const agentList = [];
4612
+ for (const strategy of botSim.strategies) {
4613
+ const state = botSim.botStates.get(strategy.id);
4614
+ const strategyPositions = positionsHook.positions.filter((p) => p.strategyId === strategy.id);
4615
+ decisionsHook.decisions.filter((d) => d.strategyId === strategy.id);
4616
+ const openPos = strategyPositions.filter((p) => p.status === "open");
4617
+ const totalPnl = strategyPositions.reduce((sum, p) => sum + p.pnl, 0);
4618
+ const exposure = openPos.reduce((sum, p) => sum + p.size, 0);
4619
+ const winCount = strategyPositions.filter((p) => p.pnl > 0).length;
4620
+ const totalTrades = strategyPositions.length;
4621
+ let riskLevel = "low";
4622
+ if (strategy.riskTolerance === "high") riskLevel = "medium";
4623
+ if (exposure > 5e4) riskLevel = "high";
4624
+ if (state && state.openPositions.length >= 3) riskLevel = "high";
4625
+ agentList.push({
4626
+ id: strategy.id,
4627
+ strategyId: strategy.id,
4628
+ name: strategy.name,
4629
+ shortName: strategy.shortName,
4630
+ color: strategy.color,
4631
+ status: state?.isRunning ? "active" : botSim.isRunning ? "idle" : "paused",
4632
+ totalPnl: state?.totalPnl ?? totalPnl,
4633
+ pnlToday: totalPnl * 0.3,
4634
+ // Simulated
4635
+ winRate: state?.winRate ?? (totalTrades > 0 ? winCount / totalTrades : 0.5),
4636
+ totalTrades: state?.totalTrades ?? totalTrades,
4637
+ tradesToday: Math.floor((state?.totalTrades ?? totalTrades) * 0.2),
4638
+ currentPair: state?.currentPair,
4639
+ currentPrice: state?.currentPrice,
4640
+ lastSignal: state?.lastSignal,
4641
+ lastSignalConfidence: state?.lastSignalConfidence,
4642
+ lastActivity: state ? Date.now() : void 0,
4643
+ openPositions: openPos.length,
4644
+ totalExposure: exposure,
4645
+ riskLevel,
4646
+ drawdown: Math.random() * 5,
4647
+ // Simulated
4648
+ riskTolerance: strategy.riskTolerance,
4649
+ primaryIndicators: strategy.primaryIndicators,
4650
+ preferredPairs: strategy.preferredPairs,
4651
+ leverageRange: [strategy.leverageMin, strategy.leverageMax]
4652
+ });
4653
+ }
4654
+ return agentList;
4655
+ }, [botSim.strategies, botSim.botStates, botSim.isRunning, positionsHook.positions, decisionsHook.decisions]);
4656
+ const metrics = useMemo(() => {
4657
+ const positions = positionsHook.positions;
4658
+ const openPos = positions.filter((p) => p.status === "open");
4659
+ const closedPos = positions.filter((p) => p.status === "closed");
4660
+ const totalPnl = positions.reduce((sum, p) => sum + p.pnl, 0);
4661
+ const unrealizedPnl = openPos.reduce((sum, p) => sum + p.pnl, 0);
4662
+ const realizedPnl = closedPos.reduce((sum, p) => sum + p.pnl, 0);
4663
+ const wins = positions.filter((p) => p.pnl > 0);
4664
+ const losses = positions.filter((p) => p.pnl < 0);
4665
+ const avgWin = wins.length > 0 ? wins.reduce((sum, p) => sum + p.pnl, 0) / wins.length : 0;
4666
+ const avgLoss = losses.length > 0 ? Math.abs(losses.reduce((sum, p) => sum + p.pnl, 0)) / losses.length : 0;
4667
+ const profitFactor = avgLoss > 0 ? avgWin / avgLoss : avgWin > 0 ? Infinity : 0;
4668
+ const totalExposure = openPos.reduce((sum, p) => sum + p.size, 0);
4669
+ const avgLeverage = openPos.length > 0 ? openPos.reduce((sum, p) => sum + p.leverage, 0) / openPos.length : 0;
4670
+ const strategyMetrics = {};
4671
+ for (const agent of agents) {
4672
+ const strategyPos = positions.filter((p) => p.strategyId === agent.strategyId);
4673
+ const strategyOpen = strategyPos.filter((p) => p.status === "open");
4674
+ const strategyWins = strategyPos.filter((p) => p.pnl > 0);
4675
+ strategyMetrics[agent.strategyId] = {
4676
+ pnl: strategyPos.reduce((sum, p) => sum + p.pnl, 0),
4677
+ trades: strategyPos.length,
4678
+ winRate: strategyPos.length > 0 ? strategyWins.length / strategyPos.length : 0,
4679
+ exposure: strategyOpen.reduce((sum, p) => sum + p.size, 0)
4680
+ };
4681
+ }
4682
+ return {
4683
+ nav: 1e5 + totalPnl,
4684
+ navChange24h: totalPnl * 0.3,
4685
+ navChangePercent24h: totalPnl * 0.3 / 1e5 * 100,
4686
+ totalPnl,
4687
+ realizedPnl,
4688
+ unrealizedPnl,
4689
+ pnlToday: totalPnl * 0.3,
4690
+ pnl7d: totalPnl * 0.7,
4691
+ pnl30d: totalPnl,
4692
+ totalTrades: positions.length,
4693
+ tradesToday: Math.floor(positions.length * 0.2),
4694
+ winRate: positions.length > 0 ? wins.length / positions.length : 0,
4695
+ winCount: wins.length,
4696
+ lossCount: losses.length,
4697
+ avgWin,
4698
+ avgLoss,
4699
+ profitFactor,
4700
+ openPositions: openPos.length,
4701
+ totalExposure,
4702
+ avgLeverage,
4703
+ strategyMetrics
4704
+ };
4705
+ }, [positionsHook.positions, agents]);
4706
+ const start = useCallback((ids) => {
4707
+ botSim.start(ids || strategyIds);
4708
+ }, [botSim, strategyIds]);
4709
+ const stop = useCallback((ids) => {
4710
+ botSim.stop(ids);
4711
+ }, [botSim]);
4712
+ const clearLogs = useCallback(() => {
4713
+ botSim.clearLogs();
4714
+ }, [botSim]);
4715
+ const refresh = useCallback(async () => {
4716
+ await Promise.all([
4717
+ positionsHook.refresh(),
4718
+ decisionsHook.refresh(),
4719
+ riskHook.refresh()
4720
+ ]);
4721
+ }, [positionsHook, decisionsHook, riskHook]);
4722
+ const getAgent = useCallback(
4723
+ (strategyId) => agents.find((a) => a.strategyId === strategyId),
4724
+ [agents]
4725
+ );
4726
+ const getAgentLogs = useCallback(
4727
+ (strategyId) => botSim.logsByStrategy.get(strategyId) || [],
4728
+ [botSim.logsByStrategy]
4729
+ );
4730
+ const getAgentPositions = useCallback(
4731
+ (strategyId) => positionsHook.positions.filter((p) => p.strategyId === strategyId),
4732
+ [positionsHook.positions]
4733
+ );
4734
+ const getAgentDecisions = useCallback(
4735
+ (strategyId) => decisionsHook.decisions.filter((d) => d.strategyId === strategyId),
4736
+ [decisionsHook.decisions]
4737
+ );
4738
+ const isLoading = positionsHook.isLoading || decisionsHook.isLoading || riskHook.isLoading;
4739
+ const error = positionsHook.error || decisionsHook.error || riskHook.error;
4740
+ return {
4741
+ strategies: botSim.strategies,
4742
+ agents,
4743
+ logs: botSim.logs,
4744
+ logsByStrategy: botSim.logsByStrategy,
4745
+ botStates: botSim.botStates,
4746
+ positions: positionsHook.positions,
4747
+ openPositions: positionsHook.openPositions,
4748
+ decisions: decisionsHook.decisions,
4749
+ recentDecisions: decisionsHook.recentDecisions,
4750
+ riskStatus: riskHook.riskStatus,
4751
+ metrics,
4752
+ isRunning: botSim.isRunning,
4753
+ isLoading,
4754
+ error,
4755
+ start,
4756
+ stop,
4757
+ clearLogs,
4758
+ emitBootSequence: botSim.emitBootSequence,
4759
+ refresh,
4760
+ getAgent,
4761
+ getAgentLogs,
4762
+ getAgentPositions,
4763
+ getAgentDecisions
4764
+ };
4765
+ }
4766
+
4767
+ // src/hooks/useTradingConsole.ts
4768
+ function useTradingConsole(options) {
4769
+ const simulation = options?.simulation ?? true;
4770
+ const pollInterval = options?.pollInterval ?? 5e3;
4771
+ const maxLogs = options?.maxLogs ?? 500;
4772
+ const strategyIds = options?.strategyIds;
4773
+ const autoStart = options?.autoStart ?? false;
4774
+ const aiConsole = useAIQuantConsole({
4775
+ simulation,
4776
+ pollInterval,
4777
+ maxLogs,
4778
+ strategyIds
4779
+ });
4780
+ const forexSim = useForexSimulation({ maxLogs });
4781
+ const forexPools = useForexPools({ refreshInterval: pollInterval });
4782
+ const forexInvestments = useForexInvestments({ refreshInterval: pollInterval });
4783
+ const combinedLogs = useMemo(() => {
4784
+ const combined = [];
4785
+ for (const log of aiConsole.logs) {
4786
+ combined.push({
4787
+ id: log.id,
4788
+ timestamp: log.timestamp,
4789
+ source: "ai",
4790
+ strategyId: log.strategyId,
4791
+ strategyName: log.strategyName,
4792
+ type: log.type,
4793
+ message: log.message,
4794
+ data: log.data,
4795
+ importance: log.importance
4796
+ });
4797
+ }
4798
+ for (const log of forexSim.logs) {
4799
+ combined.push({
4800
+ id: log.id,
4801
+ timestamp: log.timestamp,
4802
+ source: "forex",
4803
+ type: log.type,
4804
+ message: log.message,
4805
+ data: log.data,
4806
+ importance: log.importance
4807
+ });
4808
+ }
4809
+ return combined.sort((a, b) => b.timestamp - a.timestamp).slice(0, maxLogs);
4810
+ }, [aiConsole.logs, forexSim.logs, maxLogs]);
4811
+ const combinedMetrics = useMemo(() => {
4812
+ const aiMetrics = aiConsole.metrics;
4813
+ return {
4814
+ ...aiMetrics,
4815
+ totalPnl: aiMetrics.totalPnl + forexSim.stats.totalPnl,
4816
+ totalTrades: aiMetrics.totalTrades + forexSim.stats.totalTrades
4817
+ };
4818
+ }, [aiConsole.metrics, forexSim.stats]);
4819
+ const controls = useMemo(() => ({
4820
+ startAISimulation: (ids) => {
4821
+ aiConsole.emitBootSequence();
4822
+ setTimeout(() => aiConsole.start(ids), 5500);
4823
+ },
4824
+ stopAISimulation: (ids) => {
4825
+ aiConsole.stop(ids);
4826
+ },
4827
+ startForexSimulation: () => {
4828
+ forexSim.start();
4829
+ },
4830
+ stopForexSimulation: () => {
4831
+ forexSim.stop();
4832
+ },
4833
+ startAll: () => {
4834
+ aiConsole.emitBootSequence();
4835
+ setTimeout(() => {
4836
+ aiConsole.start();
4837
+ forexSim.start();
4838
+ }, 5500);
4839
+ },
4840
+ stopAll: () => {
4841
+ aiConsole.stop();
4842
+ forexSim.stop();
4843
+ },
4844
+ clearLogs: () => {
4845
+ aiConsole.clearLogs();
4846
+ forexSim.clearLogs();
4847
+ },
4848
+ emitBootSequence: () => {
4849
+ aiConsole.emitBootSequence();
4850
+ },
4851
+ refreshAll: async () => {
4852
+ await Promise.all([
4853
+ aiConsole.refresh(),
4854
+ forexPools.refresh(),
4855
+ forexInvestments.refresh()
4856
+ ]);
4857
+ }
4858
+ }), [aiConsole, forexSim, forexPools, forexInvestments]);
4859
+ const state = useMemo(() => ({
4860
+ isAISimulationRunning: aiConsole.isRunning,
4861
+ isForexSimulationRunning: forexSim.isRunning,
4862
+ isAnyRunning: aiConsole.isRunning || forexSim.isRunning,
4863
+ isLoading: aiConsole.isLoading || forexPools.isLoading || forexInvestments.isLoading,
4864
+ error: aiConsole.error || forexPools.error || forexInvestments.error
4865
+ }), [aiConsole.isRunning, aiConsole.isLoading, aiConsole.error, forexSim.isRunning, forexPools, forexInvestments]);
4866
+ useEffect(() => {
4867
+ if (autoStart) {
4868
+ controls.startAll();
4869
+ }
4870
+ }, [autoStart, controls]);
4871
+ return {
4872
+ ai: {
4873
+ strategies: aiConsole.strategies,
4874
+ agents: aiConsole.agents,
4875
+ positions: aiConsole.positions,
4876
+ decisions: aiConsole.decisions,
4877
+ riskStatus: aiConsole.riskStatus,
4878
+ simulationLogs: aiConsole.logs,
4879
+ logsByStrategy: aiConsole.logsByStrategy,
4880
+ botStates: aiConsole.botStates
4881
+ },
4882
+ forex: {
4883
+ logs: forexSim.logs,
4884
+ poolTransactions: forexSim.poolTransactions,
4885
+ pools: forexPools.pools,
4886
+ investments: forexInvestments.investments,
4887
+ stats: forexSim.stats
4888
+ },
4889
+ combinedLogs,
4890
+ metrics: combinedMetrics,
4891
+ controls,
4892
+ state,
4893
+ getAgent: aiConsole.getAgent,
4894
+ getAgentLogs: aiConsole.getAgentLogs,
4895
+ getAgentPositions: aiConsole.getAgentPositions,
4896
+ getAgentDecisions: aiConsole.getAgentDecisions
4897
+ };
4898
+ }
1696
4899
 
1697
- export { clearAITradingAccessToken, setAITradingAccessToken, useAIMarketData, useAIOrders, useAIPortfolio, useAIStrategies, useAIStrategy, useAITrading, useTokenPrice, useTokenPrices, useWalletBalance };
4900
+ export { clearAITradingAccessToken, clearConsoleAccessToken, clearForexAccessToken, setAITradingAccessToken, setConsoleAccessToken, setConsoleEngineUrl, setForexAccessToken, setForexEngineUrl, useAIAgent, useAIAgentSubscription, useAIAgents, useAIDecisions, useAIMarketData, useAIOrders, useAIPortfolio, useAIPositions, useAIQuantConsole, useAIRiskStatus, useAIStrategies, useAIStrategy, useAITrading, useBotSimulation, useForexInvestments, useForexPoolData, useForexPools, useForexSimulation, useForexTrading, useTokenPrice, useTokenPrices, useTradingConsole, useWalletBalance };
1698
4901
  //# sourceMappingURL=index.mjs.map
1699
4902
  //# sourceMappingURL=index.mjs.map