-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathserver.ts
More file actions
7125 lines (6595 loc) · 267 KB
/
Copy pathserver.ts
File metadata and controls
7125 lines (6595 loc) · 267 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from "express";
import { createServer as createViteServer } from "vite";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import fsp from "fs/promises";
import net from "net";
import crypto from "crypto";
// @ts-ignore Node 24 ships node:sqlite; TypeScript typings may lag behind.
import { DatabaseSync } from "node:sqlite";
import ccxt from "ccxt";
import axios from "axios";
import dotenv from "dotenv";
import nodemailer from "nodemailer";
import { HttpsProxyAgent } from "https-proxy-agent";
import { fetchMacroData, type MacroData } from "./src/services/macroService";
import { calculateRSI, calculateSMA, calculateStandardDeviation } from "./src/lib/indicators";
import { evaluateMacroGate, runStrategyAnalysis as evaluateStrategy } from "./src/lib/strategyEngine";
import {
AUTO_TRADING_ALLOWED_SYMBOLS,
AUTO_TRADING_ALLOWED_TIMEFRAMES,
DEFAULT_AUTO_TRADING_RISK_CONFIG,
buildMarketRuntimeContext,
calculateRiskManagedAmount,
createDefaultMarketAnalysis,
deriveMacroRiskScoreFromIndicators,
estimateShadowExecution,
normalizeDisplaySymbol,
normalizeTicker,
type AutoTradingRiskConfig,
type OrderBook as RuntimeOrderBook,
type Ticker as RuntimeTicker,
} from "./src/lib/tradingRuntime";
import {
buildPortfolioReturnAnalytics,
type PortfolioReturnBillInput,
type PortfolioReturnMode,
type PortfolioReturnRange,
} from "./src/lib/portfolioReturns";
import {
buildStrictFactorAudit,
buildValidationSlice,
createWalkForwardWindows,
groupWalkForwardRounds,
normalizeBacktestSymbols,
normalizeInitialEquity,
normalizePositiveNumber,
normalizeStrategyIds,
summarizeWalkForwardRounds,
} from "./src/lib/walkForwardBacktest";
import {
calculateOhlcvStartSince,
nextOhlcvSince,
normalizeOhlcvHistory,
} from "./src/lib/ohlcvHistory";
import {
buildHigherTimeframeTrend,
calculateRiskSizedQuantity,
categorizeNoEntryReason,
classifyValidationStatus,
createBacktestDiagnostics,
normalizeMinTrainTrades,
normalizeRiskPerTradePct,
} from "./src/lib/backtestValidation";
import {
OKX_AUTO_DATA_REQUEST_TIMEOUT_MS,
createReconnectSchedule,
getDataRetryDelayMs,
isExchangeConnectivityErrorDetails,
} from "./src/lib/exchangeReconnect";
import {
PORTFOLIO_RETURNS_CACHE_TTL_MS,
PORTFOLIO_RETURNS_STALE_MAX_AGE_MS,
PORTFOLIO_RETURNS_TIMEOUT_MS,
createPortfolioReturnRequestKey,
createPortfolioReturnStaleStatus,
isFreshPortfolioReturnCache,
isUsableStalePortfolioReturnCache,
withPortfolioReturnSourceStatus,
withTimeout,
type PortfolioReturnCacheEntry,
} from "./src/lib/portfolioReturnStability";
dotenv.config();
// Global Error Handlers
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
});
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DATA_DIR = path.join(__dirname, "data");
const AUDIT_FILE = path.join(DATA_DIR, "audit-store.json");
const APP_STORE_FILE = path.join(DATA_DIR, "app-store.json");
const TRADING_DB_FILE = path.join(DATA_DIR, "trading.sqlite");
const CREDENTIALS_FILE = path.join(DATA_DIR, "credentials.enc.json");
const LOCAL_SECRET_FILE = path.join(DATA_DIR, ".local-secret");
const LOCAL_ADMIN_PASSWORD_FILE = path.join(DATA_DIR, ".admin-password");
const EXCHANGE_PROXY_URL = process.env.EXCHANGE_PROXY_URL || "";
const EXCHANGE_PROXY_MATCH_TOKENS = (() => {
const tokens = new Set<string>();
if (EXCHANGE_PROXY_URL) tokens.add(EXCHANGE_PROXY_URL);
try {
if (EXCHANGE_PROXY_URL) {
const parsed = new URL(EXCHANGE_PROXY_URL);
if (parsed.host) tokens.add(parsed.host);
if (parsed.hostname) tokens.add(parsed.hostname);
if (parsed.port) tokens.add(parsed.port);
}
} catch {}
return Array.from(tokens).filter(Boolean);
})();
let exchangeProxyBypassed = false;
let exchangeProxyAvailability: Promise<boolean> | null = null;
type ExchangeProxyStatus = {
configured: boolean;
url: string | null;
local: boolean;
reachable: boolean | null;
bypassed: boolean;
reason?: string | null;
};
type ExchangeConnectivityStatus = {
checkedAt: number | null;
lastCheckedAt: number | null;
okxPublic: boolean | null;
okxPrivate: boolean | null;
error: string | null;
lastError: string | null;
nextRetryAt: number | null;
consecutiveFailures: number;
proxy: ExchangeProxyStatus;
};
let lastExchangeConnectivityStatus: ExchangeConnectivityStatus | null = null;
function redactProxyUrlForStatus(url: string) {
if (!url) return null;
try {
const parsed = new URL(url);
if (parsed.username) parsed.username = "***";
if (parsed.password) parsed.password = "***";
return parsed.toString();
} catch {
return url;
}
}
function getExchangeProxyStatus(reachable: boolean | null = null, reason: string | null = null): ExchangeProxyStatus {
return {
configured: Boolean(EXCHANGE_PROXY_URL),
url: redactProxyUrlForStatus(EXCHANGE_PROXY_URL),
local: Boolean(EXCHANGE_PROXY_URL && isLocalProxyUrl()),
reachable,
bypassed: exchangeProxyBypassed,
reason,
};
}
function getExchangeConnectivityStatus() {
return lastExchangeConnectivityStatus || {
checkedAt: null,
lastCheckedAt: null,
okxPublic: null,
okxPrivate: null,
error: null,
lastError: null,
nextRetryAt: null,
consecutiveFailures: 0,
proxy: getExchangeProxyStatus(),
};
}
function updateExchangeConnectivityStatus(patch: Partial<ExchangeConnectivityStatus>) {
const previous = getExchangeConnectivityStatus();
const checkedAt = patch.checkedAt ?? Date.now();
lastExchangeConnectivityStatus = {
...previous,
...patch,
checkedAt,
lastCheckedAt: patch.lastCheckedAt ?? checkedAt,
proxy: patch.proxy ?? previous.proxy ?? getExchangeProxyStatus(),
};
return lastExchangeConnectivityStatus;
}
function markExchangeConnectivitySuccess(patch: Partial<Pick<ExchangeConnectivityStatus, "okxPublic" | "okxPrivate" | "proxy">> = {}) {
return updateExchangeConnectivityStatus({
...patch,
error: null,
lastError: null,
nextRetryAt: null,
consecutiveFailures: 0,
});
}
function markExchangeConnectivityFailure(error: any, patch: Partial<Pick<ExchangeConnectivityStatus, "okxPublic" | "okxPrivate" | "proxy">> = {}) {
const previous = getExchangeConnectivityStatus();
const message = formatExchangeConnectivityError(error);
const consecutiveFailures = Math.max(1, Number(previous.consecutiveFailures || 0) + 1);
const schedule = createReconnectSchedule(consecutiveFailures);
return updateExchangeConnectivityStatus({
...patch,
error: message,
lastError: message,
consecutiveFailures,
nextRetryAt: schedule.nextRetryAt,
});
}
function applyExchangeProxy(exchange: any) {
if (!EXCHANGE_PROXY_URL || exchangeProxyBypassed) return;
if (EXCHANGE_PROXY_URL.startsWith("socks")) {
exchange.socksProxy = EXCHANGE_PROXY_URL;
exchange.wsSocksProxy = EXCHANGE_PROXY_URL;
} else if (EXCHANGE_PROXY_URL.startsWith("http://") || EXCHANGE_PROXY_URL.startsWith("https://")) {
exchange.httpsProxy = EXCHANGE_PROXY_URL;
exchange.wssProxy = EXCHANGE_PROXY_URL;
} else {
console.warn(`[Proxy] Unsupported EXCHANGE_PROXY_URL format: ${EXCHANGE_PROXY_URL}`);
}
}
const exchangeProxyReady = new WeakMap<object, Promise<void>>();
function clearExchangeProxy(exchange: any) {
if (!exchange) return;
for (const key of ["httpProxy", "httpsProxy", "socksProxy", "wsProxy", "wssProxy", "wsSocksProxy"]) {
if (key in exchange) {
exchange[key] = undefined;
}
}
}
function isLocalProxyUrl() {
try {
const parsed = new URL(EXCHANGE_PROXY_URL);
return ["127.0.0.1", "localhost", "::1"].includes(parsed.hostname);
} catch {
return false;
}
}
async function canConnectToProxy(host: string, port: number, timeoutMs = 800) {
return await new Promise<boolean>((resolve) => {
const socket = new net.Socket();
let settled = false;
const finish = (result: boolean) => {
if (settled) return;
settled = true;
socket.destroy();
resolve(result);
};
socket.setTimeout(timeoutMs);
socket.once("connect", () => finish(true));
socket.once("timeout", () => finish(false));
socket.once("error", () => finish(false));
socket.connect(port, host);
});
}
function isProxyConnectivityError(error: any) {
if (!EXCHANGE_PROXY_URL || exchangeProxyBypassed) return false;
const details = [
error?.message,
error?.cause?.message,
error?.stack,
error?.cause?.stack,
].filter(Boolean).join(" ");
if (!details) return false;
if (isExchangeConnectivityErrorDetails(details)) return true;
return EXCHANGE_PROXY_MATCH_TOKENS.some(token => details.includes(token));
}
function disableExchangeProxy(error?: any) {
if (!EXCHANGE_PROXY_URL || exchangeProxyBypassed) return;
exchangeProxyBypassed = true;
exchangeProxyAvailability = Promise.resolve(false);
clearExchangeProxy(publicExchange);
for (const exchange of privateExchanges.values()) {
clearExchangeProxy(exchange);
}
const message = error?.cause?.message || error?.message || String(error || "unknown proxy error");
console.warn(`[Proxy] ${EXCHANGE_PROXY_URL} unavailable, falling back to direct OKX requests. ${message}`);
}
function restoreExchangeProxy(reason?: string) {
if (!EXCHANGE_PROXY_URL || !exchangeProxyBypassed) return;
exchangeProxyBypassed = false;
exchangeProxyAvailability = null;
applyExchangeProxy(publicExchange);
for (const exchange of privateExchanges.values()) {
applyExchangeProxy(exchange);
}
console.warn(
`[Proxy] ${redactProxyUrlForStatus(EXCHANGE_PROXY_URL)} restored${reason ? `: ${reason}` : ""}`
);
}
async function ensureExchangeProxyAvailable() {
if (!EXCHANGE_PROXY_URL || exchangeProxyBypassed) return false;
if (!isLocalProxyUrl()) return true;
if (!exchangeProxyAvailability) {
exchangeProxyAvailability = (async () => {
try {
const parsed = new URL(EXCHANGE_PROXY_URL);
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
const reachable = await canConnectToProxy(parsed.hostname, port);
if (!reachable) {
disableExchangeProxy(`Proxy listener ${parsed.host} is not reachable`);
return false;
}
return true;
} catch {
return true;
}
})();
}
return await exchangeProxyAvailability;
}
async function prepareExchange(exchange: any) {
if (!EXCHANGE_PROXY_URL || exchangeProxyBypassed || typeof exchange.loadProxyModules !== "function") return;
if (!(await ensureExchangeProxyAvailable())) {
clearExchangeProxy(exchange);
return;
}
if (!exchangeProxyReady.has(exchange)) {
exchangeProxyReady.set(exchange, exchange.loadProxyModules().then(() => {
console.log(`[Proxy] Exchange traffic routed through ${EXCHANGE_PROXY_URL}`);
}));
}
await exchangeProxyReady.get(exchange);
}
async function runWithExchangeProxyFallback<T>(exchange: any, operation: () => Promise<T>): Promise<T> {
try {
return await operation();
} catch (error: any) {
if (!isProxyConnectivityError(error)) throw error;
disableExchangeProxy(error);
clearExchangeProxy(exchange);
return await operation();
}
}
function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function restoreLocalExchangeProxyIfReachable(reason: string) {
if (!EXCHANGE_PROXY_URL || !exchangeProxyBypassed || !isLocalProxyUrl()) return;
try {
const parsed = new URL(EXCHANGE_PROXY_URL);
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
const reachable = await canConnectToProxy(parsed.hostname, port);
if (reachable) {
restoreExchangeProxy(reason);
}
} catch {}
}
async function withAutoTradingDataRetry<T>(label: string, operation: () => Promise<T>): Promise<T> {
let lastError: any;
for (let attempt = 0; attempt <= 3; attempt += 1) {
try {
await restoreLocalExchangeProxyIfReachable(`retrying ${label}`);
return await operation();
} catch (error: any) {
lastError = error;
if (!isExchangeConnectivityFailure(error) || attempt >= 3) throw error;
const delayMs = getDataRetryDelayMs(attempt);
pushAutoTradingLog(`${label} connection failed, retrying in ${Math.round(delayMs / 1000)}s: ${error?.message || String(error)}`);
await sleep(delayMs);
}
}
throw lastError;
}
const publicMarketCache = new Map<string, { expiresAt: number; data: any }>();
const fileWriteQueue = new Map<string, Promise<void>>();
async function cachedPublicMarket<T>(key: string, ttlMs: number, fetcher: () => Promise<T>): Promise<T> {
const now = Date.now();
const cached = publicMarketCache.get(key);
if (cached && cached.expiresAt > now) return cached.data as T;
const data = await fetcher();
publicMarketCache.set(key, { data, expiresAt: now + ttlMs });
return data;
}
async function writeFileAtomic(filePath: string, contents: string, options?: { mode?: number }) {
const previous = fileWriteQueue.get(filePath) || Promise.resolve();
const next = previous
.catch(() => undefined)
.then(async () => {
await fsp.mkdir(path.dirname(filePath), { recursive: true });
const tmpFile = `${filePath}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`;
await fsp.writeFile(tmpFile, contents, options);
await fsp.rename(tmpFile, filePath);
});
fileWriteQueue.set(filePath, next);
try {
await next;
} finally {
if (fileWriteQueue.get(filePath) === next) {
fileWriteQueue.delete(filePath);
}
}
}
// --- Global Exchange Instances (for reuse) ---
function getPrivateExchange(apiKey: string, secret: string, password: string, sandbox: boolean) {
const key = `${apiKey}_${secret}_${password}_${sandbox}`;
if (!privateExchanges.has(key)) {
const exchange = new (ccxt as any).okx({
apiKey,
secret,
password,
enableRateLimit: true,
timeout: OKX_AUTO_DATA_REQUEST_TIMEOUT_MS,
options: {
defaultType: "swap",
fetchMarkets: { types: ["swap", "spot"] },
},
});
applyExchangeProxy(exchange);
if (sandbox) {
try {
exchange.setSandboxMode(true);
} catch (e) {}
exchange.headers = { ...(exchange.headers || {}), 'x-simulated-trading': '1' };
exchange.options.defaultHeaders = { ...(exchange.options.defaultHeaders || {}), 'x-simulated-trading': '1' };
}
privateExchanges.set(key, exchange);
}
return privateExchanges.get(key)!;
}
// --- Utility: Retry Wrapper ---
async function retry<T>(fn: () => Promise<T>, retries = 3, delay = 1000): Promise<T> {
try {
return await fn();
} catch (error: any) {
if (retries <= 0) throw error;
// Don't retry on certain errors (e.g. Insufficient Funds)
if (error.message.includes('Insufficient funds') || error.message.includes('Invalid order')) {
throw error;
}
console.warn(`Operation failed, retrying... (${retries} left). Error: ${error.message}`);
await new Promise(resolve => setTimeout(resolve, delay));
return retry(fn, retries - 1, delay * 2);
}
}
// --- Utility: Symbol Converter ---
function toCcxtSymbol(symbol: string): string {
if (!symbol) return "BTC/USDT:USDT";
let s = String(symbol).toUpperCase();
// If it's already a CCXT unified symbol for swap (contains :)
if (s.includes(':')) return s;
if (s.endsWith("-SWAP")) {
// Convert OKX native ID (e.g. BTC-USDT-SWAP) to CCXT unified symbol (e.g. BTC/USDT:USDT)
const base = s.replace("-SWAP", "");
const parts = base.split("-");
if (parts.length >= 2) {
return `${parts[0]}/${parts[1]}:USDT`;
}
return base.replace("-", "/") + ":USDT";
}
// This app trades USDT-margined perpetual swaps by default.
const unified = s.replace("-", "/");
const [base, quote = "USDT"] = unified.split("/");
return `${base}/${quote}:${quote}`;
}
function toOkxSwapInstId(symbol: string): string {
if (!symbol) return "BTC-USDT-SWAP";
const upper = String(symbol).toUpperCase();
if (upper.endsWith("-SWAP")) return upper;
const clean = upper.includes(":") ? upper.split(":")[0] : upper;
return `${clean.replace("/", "-")}-SWAP`;
}
function toCcxtLikeSwapSymbol(instId: string): string {
const [base, quote] = String(instId || "BTC-USDT-SWAP").replace("-SWAP", "").split("-");
return `${base}/${quote}:USDT`;
}
type OkxResolvedSwapMarket = {
requestedSymbol: string;
displaySymbol: string;
instId: string;
resolvedMarketId: string;
resolvedMarketSymbol: string;
base: string;
quote: string;
settleCcy: string;
ctVal: number;
lotSz: number;
minSz: number;
tickSz: number;
leverageCap: number | null;
state: string;
};
const okxSwapMarketCache = new Map<string, { expiresAt: number; value: OkxResolvedSwapMarket }>();
const OKX_SWAP_MARKET_CACHE_TTL_MS = 5 * 60 * 1000;
function ceilToStep(value: number, step: number) {
if (!Number.isFinite(value) || value <= 0) return 0;
if (!Number.isFinite(step) || step <= 0) return value;
const decimals = Math.max(0, (String(step).split(".")[1] || "").length);
return Number((Math.ceil(value / step) * step).toFixed(decimals));
}
function formatToStepString(value: number, step: number) {
const decimals = Math.max(0, (String(step).split(".")[1] || "").length);
return Number(value).toFixed(decimals);
}
function findLoadedOkxSwapMarket(exchange: any, instId: string, displaySymbol: string) {
const markets = Object.values(exchange?.markets || {}) as any[];
return markets.find((market) => {
const marketDisplaySymbol = normalizeDisplaySymbol(String(market?.symbol || market?.id || ""));
const marketInstId = String(market?.id || market?.info?.instId || "").toUpperCase();
const settle = String(market?.settle || market?.info?.settleCcy || "").toUpperCase();
return (
marketInstId === instId.toUpperCase() ||
(
marketDisplaySymbol === displaySymbol &&
(market?.swap || market?.type === "swap" || marketInstId.endsWith("-SWAP")) &&
(!settle || settle === "USDT")
)
);
}) || null;
}
async function resolveOkxSwapMarket(symbol: string, exchange?: any): Promise<OkxResolvedSwapMarket> {
const requestedSymbol = String(symbol || "BTC/USDT");
const displaySymbol = normalizeDisplaySymbol(requestedSymbol);
const instId = toOkxSwapInstId(displaySymbol);
const cached = okxSwapMarketCache.get(instId);
if (cached && cached.expiresAt > Date.now()) return cached.value;
const loadedMarket = findLoadedOkxSwapMarket(exchange, instId, displaySymbol);
const [base = "BTC", quote = "USDT"] = displaySymbol.split("/");
const rawMarket = loadedMarket
? loadedMarket.info || {}
: (await okxPublicGet("/api/v5/public/instruments", { instType: "SWAP", instId }))[0];
if (!rawMarket) {
throw requestError(400, `Resolved OKX swap instrument ${instId} not found`, {
error: `Resolved OKX swap instrument ${instId} not found`,
requestedSymbol,
displaySymbol,
instId,
});
}
const resolved: OkxResolvedSwapMarket = {
requestedSymbol,
displaySymbol,
instId: String(rawMarket.instId || loadedMarket?.id || instId),
resolvedMarketId: String(rawMarket.instId || loadedMarket?.id || instId),
resolvedMarketSymbol: normalizeDisplaySymbol(String(loadedMarket?.symbol || rawMarket.instId || displaySymbol)),
base: String(rawMarket.baseCcy || base || "BTC").toUpperCase(),
quote: String(rawMarket.quoteCcy || quote || "USDT").toUpperCase(),
settleCcy: String(rawMarket.settleCcy || loadedMarket?.settle || "USDT").toUpperCase(),
ctVal: firstNumber(rawMarket.ctVal, loadedMarket?.contractSize, 1),
lotSz: firstNumber(rawMarket.lotSz, loadedMarket?.info?.lotSz, loadedMarket?.limits?.amount?.min, 0.01),
minSz: firstNumber(rawMarket.minSz, loadedMarket?.limits?.amount?.min, rawMarket.lotSz, 0.01),
tickSz: firstNumber(rawMarket.tickSz, loadedMarket?.precision?.price, 0.1),
leverageCap: firstNumber(rawMarket.lever, null),
state: String(rawMarket.state || "live"),
};
okxSwapMarketCache.set(instId, {
value: resolved,
expiresAt: Date.now() + OKX_SWAP_MARKET_CACHE_TTL_MS,
});
return resolved;
}
function normalizeOkxOrderStatus(state: string | undefined | null) {
const normalized = String(state || "").toLowerCase();
if (normalized === "filled") return "closed";
if (normalized === "canceled" || normalized === "cancelled" || normalized === "mmp_canceled") return "canceled";
if (normalized === "partially_filled" || normalized === "live" || normalized === "effective") return "open";
return normalized || "unknown";
}
function normalizeOkxRawOrder(rawOrder: any, resolvedMarket: OkxResolvedSwapMarket) {
const amount = firstNumber(rawOrder?.sz);
const filled = firstNumber(rawOrder?.accFillSz, rawOrder?.fillSz);
const price = firstNumber(rawOrder?.px, rawOrder?.avgPx);
const average = firstNumber(rawOrder?.avgPx, rawOrder?.fillPx, price);
const remaining = Number.isFinite(amount) && Number.isFinite(filled)
? Math.max(0, amount - filled)
: undefined;
const feeCost = firstNumber(rawOrder?.fee);
return {
id: String(rawOrder?.ordId || rawOrder?.algoId || rawOrder?.clOrdId || "").trim() || undefined,
clientOrderId: String(rawOrder?.clOrdId || "").trim() || undefined,
symbol: resolvedMarket.displaySymbol,
instId: resolvedMarket.instId,
type: rawOrder?.ordType || "market",
side: rawOrder?.side,
price,
average,
amount,
filled,
remaining,
status: normalizeOkxOrderStatus(rawOrder?.state),
fee: feeCost !== null ? {
currency: rawOrder?.feeCcy || resolvedMarket.settleCcy,
cost: Math.abs(feeCost),
} : undefined,
info: rawOrder,
};
}
function normalizeOkxHistoryOrder(rawOrder: any, resolvedMarket: OkxResolvedSwapMarket) {
const normalized = normalizeOkxRawOrder(rawOrder, resolvedMarket);
const timestamp = firstNumber(rawOrder?.uTime, rawOrder?.cTime, rawOrder?.fillTime, Date.now());
const lastTradeTimestamp = firstNumber(rawOrder?.fillTime, rawOrder?.uTime, rawOrder?.cTime);
const average = firstNumber(normalized.average, normalized.price);
const filled = firstNumber(normalized.filled);
const cost = average > 0 && filled > 0 ? average * filled : undefined;
return {
...normalized,
timestamp,
datetime: new Date(timestamp).toISOString(),
lastTradeTimestamp: lastTradeTimestamp > 0 ? lastTradeTimestamp : undefined,
cost,
};
}
function unwrapOkxApiRow(response: any) {
const code = String(response?.code ?? "0");
if (code !== "0") {
throw requestError(502, response?.msg || "OKX request failed", {
error: response?.msg || "OKX request failed",
code,
response,
});
}
return Array.isArray(response?.data) ? response.data[0] || null : null;
}
function unwrapOkxApiRows(response: any) {
const code = String(response?.code ?? "0");
if (code !== "0") {
throw requestError(502, response?.msg || "OKX request failed", {
error: response?.msg || "OKX request failed",
code,
response,
});
}
return Array.isArray(response?.data) ? response.data : [];
}
async function fetchOkxTradeOrderRaw(
exchange: any,
exchangeCall: <T>(fn: () => Promise<T>) => Promise<T>,
instId: string,
identifiers: { ordId?: string | null; clOrdId?: string | null }
) {
const request: Record<string, any> = { instId };
if (identifiers.ordId) request.ordId = identifiers.ordId;
else if (identifiers.clOrdId) request.clOrdId = identifiers.clOrdId;
else throw new Error("Main order identifier is unavailable");
return unwrapOkxApiRow(await retry(() => exchangeCall(() => (exchange as any).privateGetTradeOrder(request))));
}
function buildOkxAttachAlgoOrds(options: { tpPrice?: any; slPrice?: any }) {
const attachAlgo: Record<string, any> = {};
if (options.tpPrice !== undefined && options.tpPrice !== null && String(options.tpPrice).trim() !== "") {
attachAlgo.tpTriggerPx = String(options.tpPrice);
attachAlgo.tpOrdPx = "-1";
attachAlgo.tpTriggerPxType = "last";
}
if (options.slPrice !== undefined && options.slPrice !== null && String(options.slPrice).trim() !== "") {
attachAlgo.slTriggerPx = String(options.slPrice);
attachAlgo.slOrdPx = "-1";
attachAlgo.slTriggerPxType = "last";
}
if (!attachAlgo.tpTriggerPx && !attachAlgo.slTriggerPx) return [];
attachAlgo.attachAlgoClOrdId = `tp${Date.now().toString(36)}${crypto.randomBytes(4).toString("hex")}`.slice(0, 32);
return [attachAlgo];
}
function parseOkxErrorDetails(errorOrResponse: any) {
const candidates = [
errorOrResponse?.response?.data,
errorOrResponse?.response,
errorOrResponse?.payload?.response,
errorOrResponse,
];
const message = String(errorOrResponse?.message || errorOrResponse?.msg || "");
const jsonStart = message.indexOf("{");
const jsonEnd = message.lastIndexOf("}");
if (jsonStart >= 0 && jsonEnd > jsonStart) {
try {
candidates.push(JSON.parse(message.slice(jsonStart, jsonEnd + 1)));
} catch {}
}
for (const candidate of candidates) {
if (!candidate || typeof candidate !== "object") continue;
const row = Array.isArray(candidate?.data) ? candidate.data[0] : candidate?.data;
const okxCode = candidate?.code !== undefined ? String(candidate.code) : undefined;
const okxMsg = candidate?.msg !== undefined ? String(candidate.msg) : undefined;
const okxSCode = row?.sCode !== undefined ? String(row.sCode) : undefined;
const okxSMsg = row?.sMsg !== undefined ? String(row.sMsg) : undefined;
if (okxCode || okxMsg || okxSCode || okxSMsg) {
return {
okxCode,
okxMsg,
okxSCode,
okxSMsg,
okxResponse: candidate,
};
}
}
return {
okxCode: undefined,
okxMsg: undefined,
okxSCode: undefined,
okxSMsg: undefined,
okxResponse: undefined,
};
}
function okxBar(timeframe: string) {
const normalized = String(timeframe || "1h").toLowerCase();
if (normalized === "1d") return "1D";
if (normalized === "1w") return "1W";
if (normalized === "4h") return "4H";
if (normalized === "15m") return "15m";
return "1H";
}
async function okxPublicGet(pathname: string, params: Record<string, any>) {
const request = async (useProxy: boolean) => axios.get(`https://www.okx.com${pathname}`, {
params,
timeout: 10000,
headers: { "User-Agent": "CryptoQuantAI/1.0" },
...(useProxy && EXCHANGE_PROXY_URL.startsWith("http")
? { httpsAgent: new HttpsProxyAgent(EXCHANGE_PROXY_URL), proxy: false }
: {}),
});
let response;
try {
const useProxy = Boolean(
EXCHANGE_PROXY_URL &&
!exchangeProxyBypassed &&
EXCHANGE_PROXY_URL.startsWith("http") &&
await ensureExchangeProxyAvailable()
);
response = await request(useProxy);
} catch (error: any) {
if (!isProxyConnectivityError(error)) throw error;
disableExchangeProxy(error);
response = await request(false);
}
if (response.data?.code && response.data.code !== "0") {
throw new Error(response.data?.msg || JSON.stringify(response.data));
}
return response.data?.data || [];
}
async function probeOkxPublicApiForAutoTrading() {
const requestOptions: any = {
timeout: 8000,
headers: { "User-Agent": "CryptoQuantAI/1.0" },
};
if (EXCHANGE_PROXY_URL && !exchangeProxyBypassed && EXCHANGE_PROXY_URL.startsWith("http")) {
requestOptions.httpsAgent = new HttpsProxyAgent(EXCHANGE_PROXY_URL);
requestOptions.proxy = false;
}
const response = await axios.get("https://www.okx.com/api/v5/public/time", requestOptions);
if (response.data?.code && String(response.data.code) !== "0") {
throw new Error(response.data?.msg || "OKX public API returned an error");
}
return true;
}
function formatExchangeConnectivityError(error: any) {
return error?.cause?.message || error?.message || String(error || "OKX connectivity check failed");
}
function isExchangeConnectivityFailure(error: any) {
const details = [
error?.message,
error?.cause?.message,
error?.stack,
error?.cause?.stack,
].filter(Boolean).join(" ");
return isExchangeConnectivityErrorDetails(details);
}
function buildAutoTradingPreflightPayload(message: string, code: string) {
return {
error: message,
code,
exchangeConnectivity: getExchangeConnectivityStatus(),
};
}
function failAutoTradingPreflight(message: string, code: string) {
updateAutoTradingStore({
state: "stopped",
nextRunAt: null,
lastError: message,
});
pushAutoTradingLog(`Auto-trading preflight failed: ${message}`);
throw requestError(503, message, buildAutoTradingPreflightPayload(message, code));
}
async function assertAutoTradingExchangeReady(credentials?: Required<OkxCredentials>, sandbox = false) {
let proxyReachable: boolean | null = null;
let proxyReason: string | null = null;
if (EXCHANGE_PROXY_URL && isLocalProxyUrl()) {
try {
const parsed = new URL(EXCHANGE_PROXY_URL);
const port = Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80));
proxyReachable = await canConnectToProxy(parsed.hostname, port);
if (!proxyReachable) {
proxyReason = `Proxy listener ${parsed.host} is not reachable`;
markExchangeConnectivityFailure(proxyReason, {
okxPublic: false,
okxPrivate: false,
proxy: getExchangeProxyStatus(false, proxyReason),
});
failAutoTradingPreflight(
`EXCHANGE_PROXY_URL points to ${redactProxyUrlForStatus(EXCHANGE_PROXY_URL)}, but that local proxy is not reachable. Start the proxy and try again, or clear EXCHANGE_PROXY_URL and restart this server.`,
"EXCHANGE_PROXY_UNREACHABLE"
);
}
restoreExchangeProxy("local proxy is reachable during auto-trading preflight");
} catch (error: any) {
if (error?.statusCode) throw error;
proxyReason = `Invalid EXCHANGE_PROXY_URL: ${formatExchangeConnectivityError(error)}`;
markExchangeConnectivityFailure(proxyReason, {
okxPublic: false,
okxPrivate: false,
proxy: getExchangeProxyStatus(false, proxyReason),
});
failAutoTradingPreflight(proxyReason, "EXCHANGE_PROXY_INVALID");
}
} else if (EXCHANGE_PROXY_URL && exchangeProxyBypassed) {
restoreExchangeProxy("retrying configured proxy during auto-trading preflight");
}
try {
await withAutoTradingDataRetry("OKX public API preflight", () => probeOkxPublicApiForAutoTrading());
markExchangeConnectivitySuccess({
okxPublic: true,
proxy: getExchangeProxyStatus(proxyReachable, proxyReason),
});
} catch (error: any) {
const reason = formatExchangeConnectivityError(error);
markExchangeConnectivityFailure(error, {
okxPublic: false,
okxPrivate: false,
proxy: getExchangeProxyStatus(proxyReachable, proxyReason),
});
failAutoTradingPreflight(
`OKX public API is not reachable before auto-trading start: ${reason}`,
"OKX_PUBLIC_UNREACHABLE"
);
}
if (!credentials) return;
try {
await fetchPrivateBalance(credentials, sandbox, true);
markExchangeConnectivitySuccess({
okxPublic: true,
okxPrivate: true,
proxy: getExchangeProxyStatus(proxyReachable, proxyReason),
});
} catch (error: any) {
const reason = formatExchangeConnectivityError(error);
markExchangeConnectivityFailure(error, {
okxPublic: true,
okxPrivate: false,
proxy: getExchangeProxyStatus(proxyReachable, proxyReason),
});
failAutoTradingPreflight(
`OKX private account API is not reachable before auto-trading start: ${reason}`,
"OKX_PRIVATE_UNREACHABLE"
);
}
}
// --- Audit & Monitoring Store ---
const STRATEGY_VERSION = "v2.1.0-reliability-risk-audit";
const auditStore = {
aiSnapshots: [] as any[],
orderReceipts: [] as any[],
riskEvents: [] as any[],
positionChanges: [] as any[],
};
// Helper to add to audit store with limit
function addToAudit<T>(list: T[], item: T, limit = 100) {
list.unshift({ ...item, timestamp: Date.now() });
if (list.length > limit) list.pop();
persistAuditStore().catch(error => console.error("[Audit] Persist failed:", error));
}
async function loadAuditStore() {
try {
await fsp.mkdir(DATA_DIR, { recursive: true });
if (!fs.existsSync(AUDIT_FILE)) return;
const raw = await fsp.readFile(AUDIT_FILE, "utf-8");
const parsed = JSON.parse(raw);
for (const key of Object.keys(auditStore) as Array<keyof typeof auditStore>) {
if (Array.isArray(parsed[key])) {
auditStore[key] = parsed[key].slice(0, 500);
}
}
console.log("[Audit] Persistent audit store loaded.");
} catch (error) {
console.warn("[Audit] Failed to load persistent audit store:", error);
}
}
async function persistAuditStore() {
await writeFileAtomic(AUDIT_FILE, JSON.stringify(auditStore, null, 2));
}
// --- Local Operations Store: auth sessions, security events, order lifecycle ---
type OperatorSession = {
tokenHash: string;
username: string;
role: "admin";
createdAt: number;
expiresAt: number;
lastSeenAt: number;
};
type SecurityEvent = {
id: string;
type: string;
username?: string;
path?: string;
method?: string;
ip?: string;
userAgent?: string;
details?: any;
timestamp: number;
};
type OrderLifecycleEvent = {
id: string;
requestId: string;
clientOrderId?: string;
orderId?: string;
symbol?: string;
side?: string;
amount?: number;
amountType?: string;
status:
| "accepted"
| "prepared"
| "submitted"
| "verified"
| "failed"
| "tp_managed"
| "tp_amended"
| "tp_skipped"
| "tp_failed"
| "tp_closed";
source?: string;
strategyId?: string;
sandbox?: boolean;
operator?: string;
details?: any;
timestamp: number;
};
type PersistentRiskState = {
date: string;
dailyPnL: number;