@tradejs/infra 1.0.9 → 1.0.10
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.
- package/dist/ai.d.mts +39 -3
- package/dist/ai.d.ts +39 -3
- package/dist/ai.js +404 -28
- package/dist/ai.mjs +372 -24
- package/dist/backtestArtifacts.d.mts +57 -0
- package/dist/backtestArtifacts.d.ts +57 -0
- package/dist/backtestArtifacts.js +255 -0
- package/dist/backtestArtifacts.mjs +211 -0
- package/dist/{chunk-MLVWC2I2.mjs → chunk-DXG2UDNA.mjs} +60 -5
- package/dist/{chunk-KVEZORMS.mjs → chunk-RQP5VSTH.mjs} +54 -3
- package/dist/ml.d.mts +1 -1
- package/dist/ml.d.ts +1 -1
- package/dist/ml.js +55 -3
- package/dist/ml.mjs +3 -1
- package/dist/{mlDatasetFile-sRGWgR_o.d.mts → mlDatasetFile-Czx__g9M.d.mts} +7 -1
- package/dist/{mlDatasetFile-sRGWgR_o.d.ts → mlDatasetFile-Czx__g9M.d.ts} +7 -1
- package/dist/redis.d.mts +21 -3
- package/dist/redis.d.ts +21 -3
- package/dist/redis.js +63 -5
- package/dist/redis.mjs +7 -1
- package/dist/timescale.d.mts +220 -5
- package/dist/timescale.d.ts +220 -5
- package/dist/timescale.js +1983 -93
- package/dist/timescale.mjs +1955 -93
- package/dist/tradingAccounts.d.mts +20 -0
- package/dist/tradingAccounts.d.ts +20 -0
- package/dist/tradingAccounts.js +556 -0
- package/dist/tradingAccounts.mjs +190 -0
- package/dist/userSettings.d.mts +2 -0
- package/dist/userSettings.d.ts +2 -0
- package/dist/userSettings.js +24 -5
- package/dist/userSettings.mjs +2 -1
- package/package.json +13 -3
package/dist/timescale.mjs
CHANGED
|
@@ -7,23 +7,88 @@ var getPool = () => {
|
|
|
7
7
|
const user = process.env.PG_USER || "app";
|
|
8
8
|
const password = String(process.env.PG_PASSWORD ?? "app");
|
|
9
9
|
const database = process.env.PG_DATABASE || process.env.PG_DB || "app";
|
|
10
|
+
const max = Number(process.env.PG_POOL_MAX ?? 10);
|
|
11
|
+
const connectionTimeoutMillis = Number(
|
|
12
|
+
process.env.PG_CONNECTION_TIMEOUT_MS ?? 3e4
|
|
13
|
+
);
|
|
10
14
|
global.__pgPool__ = new Pool({
|
|
11
15
|
host,
|
|
12
16
|
port,
|
|
13
17
|
user,
|
|
14
18
|
password,
|
|
15
19
|
database,
|
|
16
|
-
max: 10,
|
|
20
|
+
max: Number.isFinite(max) && max > 0 ? Math.floor(max) : 10,
|
|
17
21
|
idleTimeoutMillis: 3e4,
|
|
18
|
-
connectionTimeoutMillis:
|
|
22
|
+
connectionTimeoutMillis: Number.isFinite(connectionTimeoutMillis) && connectionTimeoutMillis > 0 ? Math.floor(connectionTimeoutMillis) : 3e4
|
|
19
23
|
});
|
|
20
24
|
}
|
|
21
25
|
return global.__pgPool__;
|
|
22
26
|
};
|
|
27
|
+
var candlesSchemaReady = false;
|
|
23
28
|
var derivativesSchemaReady = false;
|
|
24
29
|
var spreadSchemaReady = false;
|
|
30
|
+
var binanceMarketSchemaReady = false;
|
|
31
|
+
var candlesSchemaReadyPromise = null;
|
|
32
|
+
var derivativesSchemaReadyPromise = null;
|
|
33
|
+
var spreadSchemaReadyPromise = null;
|
|
34
|
+
var binanceMarketSchemaReadyPromise = null;
|
|
35
|
+
var closeTimescalePool = async () => {
|
|
36
|
+
const pool = global.__pgPool__;
|
|
37
|
+
if (!pool) {
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
global.__pgPool__ = void 0;
|
|
41
|
+
candlesSchemaReady = false;
|
|
42
|
+
derivativesSchemaReady = false;
|
|
43
|
+
spreadSchemaReady = false;
|
|
44
|
+
binanceMarketSchemaReady = false;
|
|
45
|
+
candlesSchemaReadyPromise = null;
|
|
46
|
+
derivativesSchemaReadyPromise = null;
|
|
47
|
+
spreadSchemaReadyPromise = null;
|
|
48
|
+
binanceMarketSchemaReadyPromise = null;
|
|
49
|
+
await pool.end();
|
|
50
|
+
};
|
|
51
|
+
var CANDLES_SCHEMA_LOCK_KEY = 61e4;
|
|
52
|
+
var DERIVATIVES_SCHEMA_LOCK_KEY = 610001;
|
|
53
|
+
var SPREAD_SCHEMA_LOCK_KEY = 610002;
|
|
54
|
+
var BINANCE_MARKET_SCHEMA_LOCK_KEY = 610003;
|
|
55
|
+
var PG_SAFE_MAX_BIND_PARAMS = 3e4;
|
|
25
56
|
var normalizeCandleProvider = (provider) => String(provider || "").trim().toLowerCase();
|
|
26
57
|
var normalizeCandleSymbol = (symbol) => String(symbol || "").trim().toUpperCase();
|
|
58
|
+
var getSafeBulkInsertRows = (columnsCount) => Math.max(1, Math.floor(PG_SAFE_MAX_BIND_PARAMS / columnsCount));
|
|
59
|
+
var withSchemaLock = async (lockKey, work) => {
|
|
60
|
+
const pool = getPool();
|
|
61
|
+
await pool.query("SELECT pg_advisory_lock($1)", [lockKey]);
|
|
62
|
+
try {
|
|
63
|
+
await work();
|
|
64
|
+
} finally {
|
|
65
|
+
await pool.query("SELECT pg_advisory_unlock($1)", [lockKey]);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
var ensureCandlesSchema = async () => {
|
|
69
|
+
if (candlesSchemaReady) return;
|
|
70
|
+
if (candlesSchemaReadyPromise) {
|
|
71
|
+
await candlesSchemaReadyPromise;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
candlesSchemaReadyPromise = withSchemaLock(
|
|
75
|
+
CANDLES_SCHEMA_LOCK_KEY,
|
|
76
|
+
async () => {
|
|
77
|
+
const pool = getPool();
|
|
78
|
+
await pool.query(`
|
|
79
|
+
ALTER TABLE candles
|
|
80
|
+
ADD COLUMN IF NOT EXISTS taker_buy_base_volume double precision,
|
|
81
|
+
ADD COLUMN IF NOT EXISTS taker_buy_quote_volume double precision,
|
|
82
|
+
ADD COLUMN IF NOT EXISTS taker_sell_base_volume double precision,
|
|
83
|
+
ADD COLUMN IF NOT EXISTS taker_sell_quote_volume double precision
|
|
84
|
+
`);
|
|
85
|
+
candlesSchemaReady = true;
|
|
86
|
+
}
|
|
87
|
+
).finally(() => {
|
|
88
|
+
candlesSchemaReadyPromise = null;
|
|
89
|
+
});
|
|
90
|
+
await candlesSchemaReadyPromise;
|
|
91
|
+
};
|
|
27
92
|
var toRows = (provider, symbol, interval, data) => {
|
|
28
93
|
const normalizedProvider = normalizeCandleProvider(provider);
|
|
29
94
|
if (!normalizedProvider) {
|
|
@@ -41,11 +106,16 @@ var toRows = (provider, symbol, interval, data) => {
|
|
|
41
106
|
low: i.low,
|
|
42
107
|
close: i.close,
|
|
43
108
|
volume: i.volume ?? null,
|
|
44
|
-
turnover: i.turnover ?? null
|
|
109
|
+
turnover: i.turnover ?? null,
|
|
110
|
+
takerBuyBaseVolume: i.takerBuyBaseVolume ?? null,
|
|
111
|
+
takerBuyQuoteVolume: i.takerBuyQuoteVolume ?? null,
|
|
112
|
+
takerSellBaseVolume: i.takerSellBaseVolume ?? null,
|
|
113
|
+
takerSellQuoteVolume: i.takerSellQuoteVolume ?? null
|
|
45
114
|
}));
|
|
46
115
|
};
|
|
47
116
|
async function upsertCandles(rows) {
|
|
48
117
|
if (!rows.length) return;
|
|
118
|
+
await ensureCandlesSchema();
|
|
49
119
|
const pool = getPool();
|
|
50
120
|
const cols = [
|
|
51
121
|
"provider",
|
|
@@ -57,7 +127,11 @@ async function upsertCandles(rows) {
|
|
|
57
127
|
"low",
|
|
58
128
|
"close",
|
|
59
129
|
"volume",
|
|
60
|
-
"turnover"
|
|
130
|
+
"turnover",
|
|
131
|
+
"taker_buy_base_volume",
|
|
132
|
+
"taker_buy_quote_volume",
|
|
133
|
+
"taker_sell_base_volume",
|
|
134
|
+
"taker_sell_quote_volume"
|
|
61
135
|
];
|
|
62
136
|
const maxRows = Math.floor(65535 / cols.length);
|
|
63
137
|
if (rows.length > maxRows) {
|
|
@@ -79,7 +153,11 @@ async function upsertCandles(rows) {
|
|
|
79
153
|
r.low,
|
|
80
154
|
r.close,
|
|
81
155
|
r.volume ?? null,
|
|
82
|
-
r.turnover ?? null
|
|
156
|
+
r.turnover ?? null,
|
|
157
|
+
r.takerBuyBaseVolume ?? null,
|
|
158
|
+
r.takerBuyQuoteVolume ?? null,
|
|
159
|
+
r.takerSellBaseVolume ?? null,
|
|
160
|
+
r.takerSellQuoteVolume ?? null
|
|
83
161
|
]);
|
|
84
162
|
const sql = `
|
|
85
163
|
INSERT INTO candles (${cols.join(",")})
|
|
@@ -90,7 +168,11 @@ async function upsertCandles(rows) {
|
|
|
90
168
|
low = EXCLUDED.low,
|
|
91
169
|
close = EXCLUDED.close,
|
|
92
170
|
volume = COALESCE(EXCLUDED.volume, candles.volume),
|
|
93
|
-
turnover = COALESCE(EXCLUDED.turnover, candles.turnover)
|
|
171
|
+
turnover = COALESCE(EXCLUDED.turnover, candles.turnover),
|
|
172
|
+
taker_buy_base_volume = COALESCE(EXCLUDED.taker_buy_base_volume, candles.taker_buy_base_volume),
|
|
173
|
+
taker_buy_quote_volume = COALESCE(EXCLUDED.taker_buy_quote_volume, candles.taker_buy_quote_volume),
|
|
174
|
+
taker_sell_base_volume = COALESCE(EXCLUDED.taker_sell_base_volume, candles.taker_sell_base_volume),
|
|
175
|
+
taker_sell_quote_volume = COALESCE(EXCLUDED.taker_sell_quote_volume, candles.taker_sell_quote_volume)
|
|
94
176
|
`;
|
|
95
177
|
const client = await pool.connect();
|
|
96
178
|
try {
|
|
@@ -106,67 +188,389 @@ async function upsertCandles(rows) {
|
|
|
106
188
|
}
|
|
107
189
|
var ensureDerivativesSchema = async () => {
|
|
108
190
|
if (derivativesSchemaReady) return;
|
|
191
|
+
if (derivativesSchemaReadyPromise) {
|
|
192
|
+
await derivativesSchemaReadyPromise;
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
109
195
|
const pool = getPool();
|
|
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
|
-
|
|
196
|
+
derivativesSchemaReadyPromise = withSchemaLock(
|
|
197
|
+
DERIVATIVES_SCHEMA_LOCK_KEY,
|
|
198
|
+
async () => {
|
|
199
|
+
if (derivativesSchemaReady) return;
|
|
200
|
+
await pool.query("CREATE EXTENSION IF NOT EXISTS timescaledb");
|
|
201
|
+
await pool.query(`
|
|
202
|
+
CREATE TABLE IF NOT EXISTS derivatives_market (
|
|
203
|
+
symbol text NOT NULL,
|
|
204
|
+
interval text NOT NULL,
|
|
205
|
+
ts timestamptz NOT NULL,
|
|
206
|
+
open_interest double precision,
|
|
207
|
+
funding_rate double precision,
|
|
208
|
+
liq_long double precision,
|
|
209
|
+
liq_short double precision,
|
|
210
|
+
liq_total double precision,
|
|
211
|
+
source text,
|
|
212
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
213
|
+
PRIMARY KEY (symbol, interval, ts)
|
|
214
|
+
)
|
|
215
|
+
`);
|
|
216
|
+
await pool.query(`
|
|
217
|
+
SELECT create_hypertable(
|
|
218
|
+
'derivatives_market',
|
|
219
|
+
'ts',
|
|
220
|
+
if_not_exists => TRUE,
|
|
221
|
+
chunk_time_interval => interval '14 days'
|
|
222
|
+
)
|
|
223
|
+
`);
|
|
224
|
+
await pool.query(`
|
|
225
|
+
CREATE INDEX IF NOT EXISTS derivatives_market_symbol_tf_ts_idx
|
|
226
|
+
ON derivatives_market (symbol, interval, ts DESC)
|
|
227
|
+
`);
|
|
228
|
+
await pool.query(`
|
|
229
|
+
CREATE TABLE IF NOT EXISTS derivatives_backfill_coverage (
|
|
230
|
+
source text NOT NULL,
|
|
231
|
+
symbol text NOT NULL,
|
|
232
|
+
interval text NOT NULL,
|
|
233
|
+
from_ts timestamptz NOT NULL,
|
|
234
|
+
to_ts timestamptz NOT NULL,
|
|
235
|
+
rows_count integer NOT NULL DEFAULT 0,
|
|
236
|
+
checked_at timestamptz NOT NULL DEFAULT now(),
|
|
237
|
+
PRIMARY KEY (source, symbol, interval, from_ts, to_ts)
|
|
238
|
+
)
|
|
239
|
+
`);
|
|
240
|
+
await pool.query(`
|
|
241
|
+
CREATE INDEX IF NOT EXISTS derivatives_backfill_coverage_lookup_idx
|
|
242
|
+
ON derivatives_backfill_coverage (source, symbol, interval, from_ts, to_ts)
|
|
243
|
+
`);
|
|
244
|
+
derivativesSchemaReady = true;
|
|
245
|
+
}
|
|
246
|
+
).finally(() => {
|
|
247
|
+
derivativesSchemaReadyPromise = null;
|
|
248
|
+
});
|
|
249
|
+
await derivativesSchemaReadyPromise;
|
|
139
250
|
};
|
|
140
251
|
var ensureSpreadSchema = async () => {
|
|
141
252
|
if (spreadSchemaReady) return;
|
|
253
|
+
if (spreadSchemaReadyPromise) {
|
|
254
|
+
await spreadSchemaReadyPromise;
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
142
257
|
const pool = getPool();
|
|
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
|
-
|
|
258
|
+
spreadSchemaReadyPromise = withSchemaLock(
|
|
259
|
+
SPREAD_SCHEMA_LOCK_KEY,
|
|
260
|
+
async () => {
|
|
261
|
+
if (spreadSchemaReady) return;
|
|
262
|
+
await pool.query("CREATE EXTENSION IF NOT EXISTS timescaledb");
|
|
263
|
+
await pool.query(`
|
|
264
|
+
CREATE TABLE IF NOT EXISTS market_spread (
|
|
265
|
+
symbol text NOT NULL,
|
|
266
|
+
interval text NOT NULL,
|
|
267
|
+
ts timestamptz NOT NULL,
|
|
268
|
+
binance_price double precision,
|
|
269
|
+
coinbase_price double precision,
|
|
270
|
+
spread double precision,
|
|
271
|
+
source text,
|
|
272
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
273
|
+
PRIMARY KEY (symbol, interval, ts)
|
|
274
|
+
)
|
|
275
|
+
`);
|
|
276
|
+
await pool.query(`
|
|
277
|
+
SELECT create_hypertable(
|
|
278
|
+
'market_spread',
|
|
279
|
+
'ts',
|
|
280
|
+
if_not_exists => TRUE,
|
|
281
|
+
chunk_time_interval => interval '14 days'
|
|
282
|
+
)
|
|
283
|
+
`);
|
|
284
|
+
await pool.query(`
|
|
285
|
+
CREATE INDEX IF NOT EXISTS market_spread_symbol_tf_ts_idx
|
|
286
|
+
ON market_spread (symbol, interval, ts DESC)
|
|
287
|
+
`);
|
|
288
|
+
spreadSchemaReady = true;
|
|
289
|
+
}
|
|
290
|
+
).finally(() => {
|
|
291
|
+
spreadSchemaReadyPromise = null;
|
|
292
|
+
});
|
|
293
|
+
await spreadSchemaReadyPromise;
|
|
294
|
+
};
|
|
295
|
+
var ensureBinanceMarketSchema = async () => {
|
|
296
|
+
if (binanceMarketSchemaReady) return;
|
|
297
|
+
if (binanceMarketSchemaReadyPromise) {
|
|
298
|
+
await binanceMarketSchemaReadyPromise;
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const pool = getPool();
|
|
302
|
+
binanceMarketSchemaReadyPromise = withSchemaLock(
|
|
303
|
+
BINANCE_MARKET_SCHEMA_LOCK_KEY,
|
|
304
|
+
async () => {
|
|
305
|
+
if (binanceMarketSchemaReady) return;
|
|
306
|
+
await pool.query("CREATE EXTENSION IF NOT EXISTS timescaledb");
|
|
307
|
+
await pool.query(`
|
|
308
|
+
CREATE TABLE IF NOT EXISTS market_trade_flow (
|
|
309
|
+
symbol text NOT NULL,
|
|
310
|
+
interval text NOT NULL,
|
|
311
|
+
ts timestamptz NOT NULL,
|
|
312
|
+
trades integer NOT NULL,
|
|
313
|
+
buy_base_volume double precision,
|
|
314
|
+
sell_base_volume double precision,
|
|
315
|
+
buy_quote_volume double precision,
|
|
316
|
+
sell_quote_volume double precision,
|
|
317
|
+
net_base_delta double precision,
|
|
318
|
+
net_quote_delta double precision,
|
|
319
|
+
buy_pressure_pct double precision,
|
|
320
|
+
source text,
|
|
321
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
322
|
+
PRIMARY KEY (symbol, interval, ts)
|
|
323
|
+
)
|
|
324
|
+
`);
|
|
325
|
+
await pool.query(`
|
|
326
|
+
SELECT create_hypertable(
|
|
327
|
+
'market_trade_flow',
|
|
328
|
+
'ts',
|
|
329
|
+
if_not_exists => TRUE,
|
|
330
|
+
chunk_time_interval => interval '7 days'
|
|
331
|
+
)
|
|
332
|
+
`);
|
|
333
|
+
await pool.query(`
|
|
334
|
+
CREATE INDEX IF NOT EXISTS market_trade_flow_symbol_tf_ts_idx
|
|
335
|
+
ON market_trade_flow (symbol, interval, ts DESC)
|
|
336
|
+
`);
|
|
337
|
+
await pool.query(`
|
|
338
|
+
CREATE TABLE IF NOT EXISTS market_breadth (
|
|
339
|
+
universe text NOT NULL,
|
|
340
|
+
interval text NOT NULL,
|
|
341
|
+
ts timestamptz NOT NULL,
|
|
342
|
+
symbols_count integer NOT NULL,
|
|
343
|
+
advancers integer NOT NULL,
|
|
344
|
+
decliners integer NOT NULL,
|
|
345
|
+
unchanged integer NOT NULL,
|
|
346
|
+
advance_decline_ratio double precision,
|
|
347
|
+
pct_above_ma20 double precision,
|
|
348
|
+
pct_above_ma50 double precision,
|
|
349
|
+
equal_weighted_return double precision,
|
|
350
|
+
volume_weighted_return double precision,
|
|
351
|
+
dispersion double precision,
|
|
352
|
+
btc_return_1h double precision,
|
|
353
|
+
btc_return_4h double precision,
|
|
354
|
+
btc_return_24h double precision,
|
|
355
|
+
alt_basket_return_1h double precision,
|
|
356
|
+
alt_basket_return_4h double precision,
|
|
357
|
+
alt_basket_return_24h double precision,
|
|
358
|
+
btc_vs_alt_return_1h double precision,
|
|
359
|
+
btc_vs_alt_return_4h double precision,
|
|
360
|
+
btc_vs_alt_return_24h double precision,
|
|
361
|
+
btc_turnover_share_1h double precision,
|
|
362
|
+
btc_turnover_share_24h double precision,
|
|
363
|
+
btc_turnover_share_change_24h double precision,
|
|
364
|
+
alt_vol_to_btc_vol_24h double precision,
|
|
365
|
+
alt_dispersion_24h double precision,
|
|
366
|
+
btc_alt_regime text,
|
|
367
|
+
source text,
|
|
368
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
369
|
+
PRIMARY KEY (universe, interval, ts)
|
|
370
|
+
)
|
|
371
|
+
`);
|
|
372
|
+
await pool.query(`
|
|
373
|
+
ALTER TABLE market_breadth
|
|
374
|
+
ADD COLUMN IF NOT EXISTS btc_return_1h double precision,
|
|
375
|
+
ADD COLUMN IF NOT EXISTS btc_return_4h double precision,
|
|
376
|
+
ADD COLUMN IF NOT EXISTS btc_return_24h double precision,
|
|
377
|
+
ADD COLUMN IF NOT EXISTS alt_basket_return_1h double precision,
|
|
378
|
+
ADD COLUMN IF NOT EXISTS alt_basket_return_4h double precision,
|
|
379
|
+
ADD COLUMN IF NOT EXISTS alt_basket_return_24h double precision,
|
|
380
|
+
ADD COLUMN IF NOT EXISTS btc_vs_alt_return_1h double precision,
|
|
381
|
+
ADD COLUMN IF NOT EXISTS btc_vs_alt_return_4h double precision,
|
|
382
|
+
ADD COLUMN IF NOT EXISTS btc_vs_alt_return_24h double precision,
|
|
383
|
+
ADD COLUMN IF NOT EXISTS btc_turnover_share_1h double precision,
|
|
384
|
+
ADD COLUMN IF NOT EXISTS btc_turnover_share_24h double precision,
|
|
385
|
+
ADD COLUMN IF NOT EXISTS btc_turnover_share_change_24h double precision,
|
|
386
|
+
ADD COLUMN IF NOT EXISTS alt_vol_to_btc_vol_24h double precision,
|
|
387
|
+
ADD COLUMN IF NOT EXISTS alt_dispersion_24h double precision,
|
|
388
|
+
ADD COLUMN IF NOT EXISTS btc_alt_regime text
|
|
389
|
+
`);
|
|
390
|
+
await pool.query(`
|
|
391
|
+
SELECT create_hypertable(
|
|
392
|
+
'market_breadth',
|
|
393
|
+
'ts',
|
|
394
|
+
if_not_exists => TRUE,
|
|
395
|
+
chunk_time_interval => interval '14 days'
|
|
396
|
+
)
|
|
397
|
+
`);
|
|
398
|
+
await pool.query(`
|
|
399
|
+
CREATE INDEX IF NOT EXISTS market_breadth_universe_tf_ts_idx
|
|
400
|
+
ON market_breadth (universe, interval, ts DESC)
|
|
401
|
+
`);
|
|
402
|
+
await pool.query(`
|
|
403
|
+
CREATE TABLE IF NOT EXISTS market_global_context (
|
|
404
|
+
source text NOT NULL,
|
|
405
|
+
ts timestamptz NOT NULL,
|
|
406
|
+
updated_at_ts timestamptz,
|
|
407
|
+
active_cryptocurrencies integer,
|
|
408
|
+
active_exchanges integer,
|
|
409
|
+
active_market_pairs integer,
|
|
410
|
+
markets integer,
|
|
411
|
+
total_market_cap_usd double precision,
|
|
412
|
+
total_volume_usd double precision,
|
|
413
|
+
total_volume_reported_usd double precision,
|
|
414
|
+
btc_dominance_pct double precision,
|
|
415
|
+
eth_dominance_pct double precision,
|
|
416
|
+
alt_market_cap_usd double precision,
|
|
417
|
+
alt_volume_usd double precision,
|
|
418
|
+
alt_volume_reported_usd double precision,
|
|
419
|
+
btc_to_alt_market_cap_ratio double precision,
|
|
420
|
+
market_cap_change_pct_24h_usd double precision,
|
|
421
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
422
|
+
PRIMARY KEY (source, ts)
|
|
423
|
+
)
|
|
424
|
+
`);
|
|
425
|
+
await pool.query(`
|
|
426
|
+
SELECT create_hypertable(
|
|
427
|
+
'market_global_context',
|
|
428
|
+
'ts',
|
|
429
|
+
if_not_exists => TRUE,
|
|
430
|
+
chunk_time_interval => interval '30 days'
|
|
431
|
+
)
|
|
432
|
+
`);
|
|
433
|
+
await pool.query(`
|
|
434
|
+
CREATE INDEX IF NOT EXISTS market_global_context_source_ts_idx
|
|
435
|
+
ON market_global_context (source, ts DESC)
|
|
436
|
+
`);
|
|
437
|
+
await pool.query(`
|
|
438
|
+
ALTER TABLE market_global_context
|
|
439
|
+
ADD COLUMN IF NOT EXISTS active_exchanges integer,
|
|
440
|
+
ADD COLUMN IF NOT EXISTS active_market_pairs integer,
|
|
441
|
+
ADD COLUMN IF NOT EXISTS total_volume_reported_usd double precision,
|
|
442
|
+
ADD COLUMN IF NOT EXISTS alt_volume_usd double precision,
|
|
443
|
+
ADD COLUMN IF NOT EXISTS alt_volume_reported_usd double precision
|
|
444
|
+
`);
|
|
445
|
+
await pool.query(`
|
|
446
|
+
CREATE TABLE IF NOT EXISTS market_reference_asset_context (
|
|
447
|
+
source text NOT NULL,
|
|
448
|
+
symbol text NOT NULL,
|
|
449
|
+
cmc_id integer NOT NULL,
|
|
450
|
+
interval text NOT NULL,
|
|
451
|
+
ts timestamptz NOT NULL,
|
|
452
|
+
open_usd double precision,
|
|
453
|
+
high_usd double precision,
|
|
454
|
+
low_usd double precision,
|
|
455
|
+
close_usd double precision,
|
|
456
|
+
volume_usd double precision,
|
|
457
|
+
market_cap_usd double precision,
|
|
458
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
459
|
+
PRIMARY KEY (source, symbol, interval, ts)
|
|
460
|
+
)
|
|
461
|
+
`);
|
|
462
|
+
await pool.query(`
|
|
463
|
+
SELECT create_hypertable(
|
|
464
|
+
'market_reference_asset_context',
|
|
465
|
+
'ts',
|
|
466
|
+
if_not_exists => TRUE,
|
|
467
|
+
chunk_time_interval => interval '30 days'
|
|
468
|
+
)
|
|
469
|
+
`);
|
|
470
|
+
await pool.query(`
|
|
471
|
+
CREATE INDEX IF NOT EXISTS market_reference_asset_context_lookup_idx
|
|
472
|
+
ON market_reference_asset_context (source, symbol, interval, ts DESC)
|
|
473
|
+
`);
|
|
474
|
+
await pool.query(`
|
|
475
|
+
CREATE TABLE IF NOT EXISTS market_cmc_exchange_liquidity_context (
|
|
476
|
+
source text NOT NULL,
|
|
477
|
+
interval text NOT NULL,
|
|
478
|
+
ts timestamptz NOT NULL,
|
|
479
|
+
exchanges_count integer NOT NULL,
|
|
480
|
+
total_volume_usd double precision,
|
|
481
|
+
binance_volume_usd double precision,
|
|
482
|
+
binance_volume_share double precision,
|
|
483
|
+
top_exchange_volume_share double precision,
|
|
484
|
+
liquidity_regime text,
|
|
485
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
486
|
+
PRIMARY KEY (source, interval, ts)
|
|
487
|
+
)
|
|
488
|
+
`);
|
|
489
|
+
await pool.query(`
|
|
490
|
+
SELECT create_hypertable(
|
|
491
|
+
'market_cmc_exchange_liquidity_context',
|
|
492
|
+
'ts',
|
|
493
|
+
if_not_exists => TRUE,
|
|
494
|
+
chunk_time_interval => interval '30 days'
|
|
495
|
+
)
|
|
496
|
+
`);
|
|
497
|
+
await pool.query(`
|
|
498
|
+
CREATE INDEX IF NOT EXISTS market_cmc_exchange_liquidity_context_lookup_idx
|
|
499
|
+
ON market_cmc_exchange_liquidity_context (source, interval, ts DESC)
|
|
500
|
+
`);
|
|
501
|
+
await pool.query(`
|
|
502
|
+
CREATE TABLE IF NOT EXISTS market_cmc_fear_greed_context (
|
|
503
|
+
source text NOT NULL,
|
|
504
|
+
interval text NOT NULL,
|
|
505
|
+
ts timestamptz NOT NULL,
|
|
506
|
+
value integer NOT NULL,
|
|
507
|
+
classification text NOT NULL,
|
|
508
|
+
sentiment_regime text NOT NULL,
|
|
509
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
510
|
+
PRIMARY KEY (source, interval, ts)
|
|
511
|
+
)
|
|
512
|
+
`);
|
|
513
|
+
await pool.query(`
|
|
514
|
+
SELECT create_hypertable(
|
|
515
|
+
'market_cmc_fear_greed_context',
|
|
516
|
+
'ts',
|
|
517
|
+
if_not_exists => TRUE,
|
|
518
|
+
chunk_time_interval => interval '30 days'
|
|
519
|
+
)
|
|
520
|
+
`);
|
|
521
|
+
await pool.query(`
|
|
522
|
+
CREATE INDEX IF NOT EXISTS market_cmc_fear_greed_context_lookup_idx
|
|
523
|
+
ON market_cmc_fear_greed_context (source, interval, ts DESC)
|
|
524
|
+
`);
|
|
525
|
+
await pool.query(`
|
|
526
|
+
CREATE TABLE IF NOT EXISTS market_cmc_index_context (
|
|
527
|
+
source text NOT NULL,
|
|
528
|
+
index_slug text NOT NULL,
|
|
529
|
+
interval text NOT NULL,
|
|
530
|
+
ts timestamptz NOT NULL,
|
|
531
|
+
value double precision NOT NULL,
|
|
532
|
+
constituents_count integer,
|
|
533
|
+
top_constituent_symbol text,
|
|
534
|
+
top_constituent_weight_pct double precision,
|
|
535
|
+
constituents jsonb,
|
|
536
|
+
ingested_at timestamptz NOT NULL DEFAULT now(),
|
|
537
|
+
PRIMARY KEY (source, index_slug, interval, ts)
|
|
538
|
+
)
|
|
539
|
+
`);
|
|
540
|
+
await pool.query(`
|
|
541
|
+
SELECT create_hypertable(
|
|
542
|
+
'market_cmc_index_context',
|
|
543
|
+
'ts',
|
|
544
|
+
if_not_exists => TRUE,
|
|
545
|
+
chunk_time_interval => interval '30 days'
|
|
546
|
+
)
|
|
547
|
+
`);
|
|
548
|
+
await pool.query(`
|
|
549
|
+
CREATE INDEX IF NOT EXISTS market_cmc_index_context_lookup_idx
|
|
550
|
+
ON market_cmc_index_context (source, index_slug, interval, ts DESC)
|
|
551
|
+
`);
|
|
552
|
+
await pool.query(`
|
|
553
|
+
CREATE TABLE IF NOT EXISTS market_context_backfill_coverage (
|
|
554
|
+
source text NOT NULL,
|
|
555
|
+
scope text NOT NULL,
|
|
556
|
+
interval text NOT NULL,
|
|
557
|
+
from_ts timestamptz NOT NULL,
|
|
558
|
+
to_ts timestamptz NOT NULL,
|
|
559
|
+
rows_count integer NOT NULL DEFAULT 0,
|
|
560
|
+
checked_at timestamptz NOT NULL DEFAULT now(),
|
|
561
|
+
PRIMARY KEY (source, scope, interval, from_ts, to_ts)
|
|
562
|
+
)
|
|
563
|
+
`);
|
|
564
|
+
await pool.query(`
|
|
565
|
+
CREATE INDEX IF NOT EXISTS market_context_backfill_coverage_lookup_idx
|
|
566
|
+
ON market_context_backfill_coverage (source, scope, interval, from_ts, to_ts)
|
|
567
|
+
`);
|
|
568
|
+
binanceMarketSchemaReady = true;
|
|
569
|
+
}
|
|
570
|
+
).finally(() => {
|
|
571
|
+
binanceMarketSchemaReadyPromise = null;
|
|
572
|
+
});
|
|
573
|
+
await binanceMarketSchemaReadyPromise;
|
|
170
574
|
};
|
|
171
575
|
async function upsertDerivatives(rows) {
|
|
172
576
|
if (!rows.length) return;
|
|
@@ -268,6 +672,85 @@ async function getDerivativesDataEdgesForSymbols(symbols, interval) {
|
|
|
268
672
|
}
|
|
269
673
|
return edges;
|
|
270
674
|
}
|
|
675
|
+
async function getDerivativesBackfillCoverage(params) {
|
|
676
|
+
const normalizedSource = String(params.source || "").trim().toLowerCase();
|
|
677
|
+
const normalizedSymbols = [
|
|
678
|
+
...new Set(
|
|
679
|
+
params.symbols.map(
|
|
680
|
+
(symbol) => String(symbol || "").trim().toUpperCase()
|
|
681
|
+
).filter(Boolean)
|
|
682
|
+
)
|
|
683
|
+
];
|
|
684
|
+
if (!normalizedSource || !normalizedSymbols.length) {
|
|
685
|
+
return [];
|
|
686
|
+
}
|
|
687
|
+
await ensureDerivativesSchema();
|
|
688
|
+
const pool = getPool();
|
|
689
|
+
const res = await pool.query(
|
|
690
|
+
`
|
|
691
|
+
SELECT
|
|
692
|
+
symbol,
|
|
693
|
+
interval,
|
|
694
|
+
extract(epoch from from_ts)*1000 AS from_ms,
|
|
695
|
+
extract(epoch from to_ts)*1000 AS to_ms,
|
|
696
|
+
rows_count
|
|
697
|
+
FROM derivatives_backfill_coverage
|
|
698
|
+
WHERE source = $1
|
|
699
|
+
AND symbol = ANY($2)
|
|
700
|
+
AND interval = $3
|
|
701
|
+
AND from_ts <= to_timestamp($5/1000.0)
|
|
702
|
+
AND to_ts >= to_timestamp($4/1000.0)
|
|
703
|
+
`,
|
|
704
|
+
[
|
|
705
|
+
normalizedSource,
|
|
706
|
+
normalizedSymbols,
|
|
707
|
+
params.interval,
|
|
708
|
+
params.fromMs,
|
|
709
|
+
params.toMs
|
|
710
|
+
]
|
|
711
|
+
);
|
|
712
|
+
return res.rows.map((row) => ({
|
|
713
|
+
symbol: String(row.symbol).toUpperCase(),
|
|
714
|
+
interval: row.interval,
|
|
715
|
+
fromMs: Number(row.from_ms),
|
|
716
|
+
toMs: Number(row.to_ms),
|
|
717
|
+
rowsCount: Number(row.rows_count ?? 0)
|
|
718
|
+
}));
|
|
719
|
+
}
|
|
720
|
+
async function upsertDerivativesBackfillCoverage(rows) {
|
|
721
|
+
if (!rows.length) return;
|
|
722
|
+
await ensureDerivativesSchema();
|
|
723
|
+
const pool = getPool();
|
|
724
|
+
const cols = [
|
|
725
|
+
"source",
|
|
726
|
+
"symbol",
|
|
727
|
+
"interval",
|
|
728
|
+
"from_ts",
|
|
729
|
+
"to_ts",
|
|
730
|
+
"rows_count"
|
|
731
|
+
];
|
|
732
|
+
const valuesSql = rows.map(
|
|
733
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
734
|
+
).join(",");
|
|
735
|
+
const flat = rows.flatMap((row) => [
|
|
736
|
+
String(row.source || "").trim().toLowerCase(),
|
|
737
|
+
String(row.symbol || "").trim().toUpperCase(),
|
|
738
|
+
row.interval,
|
|
739
|
+
new Date(row.fromMs),
|
|
740
|
+
new Date(row.toMs),
|
|
741
|
+
Math.max(0, Math.trunc(row.rowsCount))
|
|
742
|
+
]);
|
|
743
|
+
await pool.query(
|
|
744
|
+
`
|
|
745
|
+
INSERT INTO derivatives_backfill_coverage (${cols.join(",")})
|
|
746
|
+
VALUES ${valuesSql}
|
|
747
|
+
ON CONFLICT (source, symbol, interval, from_ts, to_ts) DO UPDATE SET
|
|
748
|
+
rows_count = EXCLUDED.rows_count,
|
|
749
|
+
checked_at = now()
|
|
750
|
+
`,
|
|
751
|
+
flat
|
|
752
|
+
);
|
|
753
|
+
}
|
|
271
754
|
async function getDerivativesWindow(params) {
|
|
272
755
|
const { symbol, intervals, endMs, lookbackMs } = params;
|
|
273
756
|
const normalizedSymbol = String(symbol || "").trim().toUpperCase();
|
|
@@ -311,43 +794,114 @@ async function getDerivativesWindow(params) {
|
|
|
311
794
|
}
|
|
312
795
|
return rowsByInterval;
|
|
313
796
|
}
|
|
314
|
-
async function getDerivativesSummary(hours = 24, limit = 500) {
|
|
797
|
+
async function getDerivativesSummary(hours = 24, limit = 500, symbols) {
|
|
315
798
|
await ensureDerivativesSchema();
|
|
316
799
|
const pool = getPool();
|
|
317
|
-
const cappedHours = Math.max(1, Math.min(24 *
|
|
318
|
-
const cappedLimit = Math.max(
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
FROM derivatives_market
|
|
323
|
-
WHERE ts >= now() - ($1 || ' hours')::interval
|
|
324
|
-
ORDER BY ts DESC
|
|
325
|
-
LIMIT $2
|
|
326
|
-
`,
|
|
327
|
-
[String(cappedHours), cappedLimit]
|
|
328
|
-
);
|
|
329
|
-
const aggQ = await pool.query(
|
|
800
|
+
const cappedHours = Math.max(1, Math.min(24 * 90, hours));
|
|
801
|
+
const cappedLimit = Math.max(10, Math.min(1e3, limit));
|
|
802
|
+
const normalizedSymbols = Array.isArray(symbols) ? [...new Set(symbols.map(normalizeCandleSymbol).filter(Boolean))] : [];
|
|
803
|
+
const symbolsFilterSql = normalizedSymbols.length ? "AND symbol = ANY($3)" : "";
|
|
804
|
+
const summaryQ = await pool.query(
|
|
330
805
|
`
|
|
806
|
+
WITH filtered AS (
|
|
807
|
+
SELECT
|
|
808
|
+
symbol,
|
|
809
|
+
interval,
|
|
810
|
+
ts,
|
|
811
|
+
open_interest,
|
|
812
|
+
funding_rate,
|
|
813
|
+
liq_long,
|
|
814
|
+
liq_short,
|
|
815
|
+
liq_total
|
|
816
|
+
FROM derivatives_market
|
|
817
|
+
WHERE ts >= now() - ($1 || ' hours')::interval
|
|
818
|
+
${symbolsFilterSql}
|
|
819
|
+
),
|
|
820
|
+
latest AS (
|
|
821
|
+
SELECT DISTINCT ON (symbol, interval)
|
|
822
|
+
symbol,
|
|
823
|
+
interval,
|
|
824
|
+
ts AS last_ts,
|
|
825
|
+
open_interest AS latest_open_interest,
|
|
826
|
+
funding_rate AS latest_funding_rate
|
|
827
|
+
FROM filtered
|
|
828
|
+
ORDER BY symbol ASC, interval ASC, ts DESC
|
|
829
|
+
),
|
|
830
|
+
first AS (
|
|
831
|
+
SELECT DISTINCT ON (symbol, interval)
|
|
832
|
+
symbol,
|
|
833
|
+
interval,
|
|
834
|
+
ts AS first_ts,
|
|
835
|
+
open_interest AS first_open_interest,
|
|
836
|
+
funding_rate AS first_funding_rate
|
|
837
|
+
FROM filtered
|
|
838
|
+
ORDER BY symbol ASC, interval ASC, ts ASC
|
|
839
|
+
),
|
|
840
|
+
aggregated AS (
|
|
841
|
+
SELECT
|
|
842
|
+
symbol,
|
|
843
|
+
interval,
|
|
844
|
+
COUNT(*)::int AS points,
|
|
845
|
+
SUM(COALESCE(liq_long, 0)) AS sum_liq_long,
|
|
846
|
+
SUM(COALESCE(liq_short, 0)) AS sum_liq_short,
|
|
847
|
+
SUM(COALESCE(liq_total, 0)) AS sum_liq_total
|
|
848
|
+
FROM filtered
|
|
849
|
+
GROUP BY symbol, interval
|
|
850
|
+
)
|
|
331
851
|
SELECT
|
|
332
|
-
symbol,
|
|
333
|
-
interval,
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
852
|
+
aggregated.symbol,
|
|
853
|
+
aggregated.interval,
|
|
854
|
+
aggregated.points,
|
|
855
|
+
latest.last_ts,
|
|
856
|
+
first.first_ts,
|
|
857
|
+
latest.latest_open_interest,
|
|
858
|
+
first.first_open_interest,
|
|
859
|
+
latest.latest_funding_rate,
|
|
860
|
+
first.first_funding_rate,
|
|
861
|
+
aggregated.sum_liq_long,
|
|
862
|
+
aggregated.sum_liq_short,
|
|
863
|
+
aggregated.sum_liq_total
|
|
864
|
+
FROM aggregated
|
|
865
|
+
JOIN latest
|
|
866
|
+
ON latest.symbol = aggregated.symbol
|
|
867
|
+
AND latest.interval = aggregated.interval
|
|
868
|
+
JOIN first
|
|
869
|
+
ON first.symbol = aggregated.symbol
|
|
870
|
+
AND first.interval = aggregated.interval
|
|
871
|
+
ORDER BY aggregated.sum_liq_total DESC, aggregated.symbol ASC
|
|
872
|
+
LIMIT $2
|
|
344
873
|
`,
|
|
345
|
-
[String(cappedHours)]
|
|
874
|
+
normalizedSymbols.length ? [String(cappedHours), cappedLimit, normalizedSymbols] : [String(cappedHours), cappedLimit]
|
|
346
875
|
);
|
|
876
|
+
const items = summaryQ.rows.map((row) => {
|
|
877
|
+
const latestOpenInterest = row.latest_open_interest == null ? null : Number(row.latest_open_interest);
|
|
878
|
+
const firstOpenInterest = row.first_open_interest == null ? null : Number(row.first_open_interest);
|
|
879
|
+
const latestFundingRate = row.latest_funding_rate == null ? null : Number(row.latest_funding_rate);
|
|
880
|
+
const firstFundingRate = row.first_funding_rate == null ? null : Number(row.first_funding_rate);
|
|
881
|
+
const oiChange = latestOpenInterest != null && firstOpenInterest != null ? latestOpenInterest - firstOpenInterest : null;
|
|
882
|
+
const oiChangePct = oiChange != null && firstOpenInterest != null && Number.isFinite(firstOpenInterest) && Math.abs(firstOpenInterest) > 0 ? oiChange / Math.abs(firstOpenInterest) * 100 : null;
|
|
883
|
+
const fundingChange = latestFundingRate != null && firstFundingRate != null ? latestFundingRate - firstFundingRate : null;
|
|
884
|
+
return {
|
|
885
|
+
symbol: row.symbol,
|
|
886
|
+
interval: row.interval,
|
|
887
|
+
points: Number(row.points || 0),
|
|
888
|
+
last_ts: row.last_ts,
|
|
889
|
+
first_ts: row.first_ts,
|
|
890
|
+
latest_open_interest: latestOpenInterest,
|
|
891
|
+
first_open_interest: firstOpenInterest,
|
|
892
|
+
oi_change: oiChange,
|
|
893
|
+
oi_change_pct: oiChangePct,
|
|
894
|
+
latest_funding_rate: latestFundingRate,
|
|
895
|
+
first_funding_rate: firstFundingRate,
|
|
896
|
+
funding_change: fundingChange,
|
|
897
|
+
sum_liq_long: row.sum_liq_long == null ? null : Number(row.sum_liq_long),
|
|
898
|
+
sum_liq_short: row.sum_liq_short == null ? null : Number(row.sum_liq_short),
|
|
899
|
+
sum_liq_total: row.sum_liq_total == null ? null : Number(row.sum_liq_total)
|
|
900
|
+
};
|
|
901
|
+
});
|
|
347
902
|
return {
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
hours: cappedHours
|
|
903
|
+
hours: cappedHours,
|
|
904
|
+
items
|
|
351
905
|
};
|
|
352
906
|
}
|
|
353
907
|
async function upsertSpreadRows(rows) {
|
|
@@ -394,6 +948,1229 @@ async function upsertSpreadRows(rows) {
|
|
|
394
948
|
`;
|
|
395
949
|
await pool.query(sql, flat);
|
|
396
950
|
}
|
|
951
|
+
async function upsertMarketTradeFlowRows(rows) {
|
|
952
|
+
if (!rows.length) return;
|
|
953
|
+
await ensureBinanceMarketSchema();
|
|
954
|
+
const pool = getPool();
|
|
955
|
+
const cols = [
|
|
956
|
+
"symbol",
|
|
957
|
+
"interval",
|
|
958
|
+
"ts",
|
|
959
|
+
"trades",
|
|
960
|
+
"buy_base_volume",
|
|
961
|
+
"sell_base_volume",
|
|
962
|
+
"buy_quote_volume",
|
|
963
|
+
"sell_quote_volume",
|
|
964
|
+
"net_base_delta",
|
|
965
|
+
"net_quote_delta",
|
|
966
|
+
"buy_pressure_pct",
|
|
967
|
+
"source"
|
|
968
|
+
];
|
|
969
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
970
|
+
if (rows.length > maxRows) {
|
|
971
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
972
|
+
await upsertMarketTradeFlowRows(rows.slice(i, i + maxRows));
|
|
973
|
+
}
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
const valuesSql = rows.map(
|
|
977
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
978
|
+
).join(",");
|
|
979
|
+
const flat = rows.flatMap((row) => [
|
|
980
|
+
row.symbol,
|
|
981
|
+
row.interval,
|
|
982
|
+
row.ts,
|
|
983
|
+
row.trades,
|
|
984
|
+
row.buyBaseVolume ?? null,
|
|
985
|
+
row.sellBaseVolume ?? null,
|
|
986
|
+
row.buyQuoteVolume ?? null,
|
|
987
|
+
row.sellQuoteVolume ?? null,
|
|
988
|
+
row.netBaseDelta ?? null,
|
|
989
|
+
row.netQuoteDelta ?? null,
|
|
990
|
+
row.buyPressurePct ?? null,
|
|
991
|
+
row.source ?? null
|
|
992
|
+
]);
|
|
993
|
+
await pool.query(
|
|
994
|
+
`
|
|
995
|
+
INSERT INTO market_trade_flow (${cols.join(",")})
|
|
996
|
+
VALUES ${valuesSql}
|
|
997
|
+
ON CONFLICT (symbol, interval, ts) DO UPDATE SET
|
|
998
|
+
trades = EXCLUDED.trades,
|
|
999
|
+
buy_base_volume = COALESCE(EXCLUDED.buy_base_volume, market_trade_flow.buy_base_volume),
|
|
1000
|
+
sell_base_volume = COALESCE(EXCLUDED.sell_base_volume, market_trade_flow.sell_base_volume),
|
|
1001
|
+
buy_quote_volume = COALESCE(EXCLUDED.buy_quote_volume, market_trade_flow.buy_quote_volume),
|
|
1002
|
+
sell_quote_volume = COALESCE(EXCLUDED.sell_quote_volume, market_trade_flow.sell_quote_volume),
|
|
1003
|
+
net_base_delta = COALESCE(EXCLUDED.net_base_delta, market_trade_flow.net_base_delta),
|
|
1004
|
+
net_quote_delta = COALESCE(EXCLUDED.net_quote_delta, market_trade_flow.net_quote_delta),
|
|
1005
|
+
buy_pressure_pct = COALESCE(EXCLUDED.buy_pressure_pct, market_trade_flow.buy_pressure_pct),
|
|
1006
|
+
source = COALESCE(EXCLUDED.source, market_trade_flow.source),
|
|
1007
|
+
ingested_at = now()
|
|
1008
|
+
`,
|
|
1009
|
+
flat
|
|
1010
|
+
);
|
|
1011
|
+
}
|
|
1012
|
+
async function upsertMarketBreadthRows(rows) {
|
|
1013
|
+
if (!rows.length) return;
|
|
1014
|
+
await ensureBinanceMarketSchema();
|
|
1015
|
+
const pool = getPool();
|
|
1016
|
+
const cols = [
|
|
1017
|
+
"universe",
|
|
1018
|
+
"interval",
|
|
1019
|
+
"ts",
|
|
1020
|
+
"symbols_count",
|
|
1021
|
+
"advancers",
|
|
1022
|
+
"decliners",
|
|
1023
|
+
"unchanged",
|
|
1024
|
+
"advance_decline_ratio",
|
|
1025
|
+
"pct_above_ma20",
|
|
1026
|
+
"pct_above_ma50",
|
|
1027
|
+
"equal_weighted_return",
|
|
1028
|
+
"volume_weighted_return",
|
|
1029
|
+
"dispersion",
|
|
1030
|
+
"btc_return_1h",
|
|
1031
|
+
"btc_return_4h",
|
|
1032
|
+
"btc_return_24h",
|
|
1033
|
+
"alt_basket_return_1h",
|
|
1034
|
+
"alt_basket_return_4h",
|
|
1035
|
+
"alt_basket_return_24h",
|
|
1036
|
+
"btc_vs_alt_return_1h",
|
|
1037
|
+
"btc_vs_alt_return_4h",
|
|
1038
|
+
"btc_vs_alt_return_24h",
|
|
1039
|
+
"btc_turnover_share_1h",
|
|
1040
|
+
"btc_turnover_share_24h",
|
|
1041
|
+
"btc_turnover_share_change_24h",
|
|
1042
|
+
"alt_vol_to_btc_vol_24h",
|
|
1043
|
+
"alt_dispersion_24h",
|
|
1044
|
+
"btc_alt_regime",
|
|
1045
|
+
"source"
|
|
1046
|
+
];
|
|
1047
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1048
|
+
if (rows.length > maxRows) {
|
|
1049
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1050
|
+
await upsertMarketBreadthRows(rows.slice(i, i + maxRows));
|
|
1051
|
+
}
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
const valuesSql = rows.map(
|
|
1055
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1056
|
+
).join(",");
|
|
1057
|
+
const flat = rows.flatMap((row) => [
|
|
1058
|
+
row.universe,
|
|
1059
|
+
row.interval,
|
|
1060
|
+
row.ts,
|
|
1061
|
+
row.symbolsCount,
|
|
1062
|
+
row.advancers,
|
|
1063
|
+
row.decliners,
|
|
1064
|
+
row.unchanged,
|
|
1065
|
+
row.advanceDeclineRatio ?? null,
|
|
1066
|
+
row.pctAboveMa20 ?? null,
|
|
1067
|
+
row.pctAboveMa50 ?? null,
|
|
1068
|
+
row.equalWeightedReturn ?? null,
|
|
1069
|
+
row.volumeWeightedReturn ?? null,
|
|
1070
|
+
row.dispersion ?? null,
|
|
1071
|
+
row.btcReturn1h ?? null,
|
|
1072
|
+
row.btcReturn4h ?? null,
|
|
1073
|
+
row.btcReturn24h ?? null,
|
|
1074
|
+
row.altBasketReturn1h ?? null,
|
|
1075
|
+
row.altBasketReturn4h ?? null,
|
|
1076
|
+
row.altBasketReturn24h ?? null,
|
|
1077
|
+
row.btcVsAltReturn1h ?? null,
|
|
1078
|
+
row.btcVsAltReturn4h ?? null,
|
|
1079
|
+
row.btcVsAltReturn24h ?? null,
|
|
1080
|
+
row.btcTurnoverShare1h ?? null,
|
|
1081
|
+
row.btcTurnoverShare24h ?? null,
|
|
1082
|
+
row.btcTurnoverShareChange24h ?? null,
|
|
1083
|
+
row.altVolToBtcVol24h ?? null,
|
|
1084
|
+
row.altDispersion24h ?? null,
|
|
1085
|
+
row.btcAltRegime ?? null,
|
|
1086
|
+
row.source ?? null
|
|
1087
|
+
]);
|
|
1088
|
+
await pool.query(
|
|
1089
|
+
`
|
|
1090
|
+
INSERT INTO market_breadth (${cols.join(",")})
|
|
1091
|
+
VALUES ${valuesSql}
|
|
1092
|
+
ON CONFLICT (universe, interval, ts) DO UPDATE SET
|
|
1093
|
+
symbols_count = EXCLUDED.symbols_count,
|
|
1094
|
+
advancers = EXCLUDED.advancers,
|
|
1095
|
+
decliners = EXCLUDED.decliners,
|
|
1096
|
+
unchanged = EXCLUDED.unchanged,
|
|
1097
|
+
advance_decline_ratio = COALESCE(EXCLUDED.advance_decline_ratio, market_breadth.advance_decline_ratio),
|
|
1098
|
+
pct_above_ma20 = COALESCE(EXCLUDED.pct_above_ma20, market_breadth.pct_above_ma20),
|
|
1099
|
+
pct_above_ma50 = COALESCE(EXCLUDED.pct_above_ma50, market_breadth.pct_above_ma50),
|
|
1100
|
+
equal_weighted_return = COALESCE(EXCLUDED.equal_weighted_return, market_breadth.equal_weighted_return),
|
|
1101
|
+
volume_weighted_return = COALESCE(EXCLUDED.volume_weighted_return, market_breadth.volume_weighted_return),
|
|
1102
|
+
dispersion = COALESCE(EXCLUDED.dispersion, market_breadth.dispersion),
|
|
1103
|
+
btc_return_1h = COALESCE(EXCLUDED.btc_return_1h, market_breadth.btc_return_1h),
|
|
1104
|
+
btc_return_4h = COALESCE(EXCLUDED.btc_return_4h, market_breadth.btc_return_4h),
|
|
1105
|
+
btc_return_24h = COALESCE(EXCLUDED.btc_return_24h, market_breadth.btc_return_24h),
|
|
1106
|
+
alt_basket_return_1h = COALESCE(EXCLUDED.alt_basket_return_1h, market_breadth.alt_basket_return_1h),
|
|
1107
|
+
alt_basket_return_4h = COALESCE(EXCLUDED.alt_basket_return_4h, market_breadth.alt_basket_return_4h),
|
|
1108
|
+
alt_basket_return_24h = COALESCE(EXCLUDED.alt_basket_return_24h, market_breadth.alt_basket_return_24h),
|
|
1109
|
+
btc_vs_alt_return_1h = COALESCE(EXCLUDED.btc_vs_alt_return_1h, market_breadth.btc_vs_alt_return_1h),
|
|
1110
|
+
btc_vs_alt_return_4h = COALESCE(EXCLUDED.btc_vs_alt_return_4h, market_breadth.btc_vs_alt_return_4h),
|
|
1111
|
+
btc_vs_alt_return_24h = COALESCE(EXCLUDED.btc_vs_alt_return_24h, market_breadth.btc_vs_alt_return_24h),
|
|
1112
|
+
btc_turnover_share_1h = COALESCE(EXCLUDED.btc_turnover_share_1h, market_breadth.btc_turnover_share_1h),
|
|
1113
|
+
btc_turnover_share_24h = COALESCE(EXCLUDED.btc_turnover_share_24h, market_breadth.btc_turnover_share_24h),
|
|
1114
|
+
btc_turnover_share_change_24h = COALESCE(EXCLUDED.btc_turnover_share_change_24h, market_breadth.btc_turnover_share_change_24h),
|
|
1115
|
+
alt_vol_to_btc_vol_24h = COALESCE(EXCLUDED.alt_vol_to_btc_vol_24h, market_breadth.alt_vol_to_btc_vol_24h),
|
|
1116
|
+
alt_dispersion_24h = COALESCE(EXCLUDED.alt_dispersion_24h, market_breadth.alt_dispersion_24h),
|
|
1117
|
+
btc_alt_regime = COALESCE(EXCLUDED.btc_alt_regime, market_breadth.btc_alt_regime),
|
|
1118
|
+
source = COALESCE(EXCLUDED.source, market_breadth.source),
|
|
1119
|
+
ingested_at = now()
|
|
1120
|
+
`,
|
|
1121
|
+
flat
|
|
1122
|
+
);
|
|
1123
|
+
}
|
|
1124
|
+
async function upsertMarketGlobalContextRows(rows) {
|
|
1125
|
+
if (!rows.length) return;
|
|
1126
|
+
await ensureBinanceMarketSchema();
|
|
1127
|
+
const pool = getPool();
|
|
1128
|
+
const cols = [
|
|
1129
|
+
"source",
|
|
1130
|
+
"ts",
|
|
1131
|
+
"updated_at_ts",
|
|
1132
|
+
"active_cryptocurrencies",
|
|
1133
|
+
"active_exchanges",
|
|
1134
|
+
"active_market_pairs",
|
|
1135
|
+
"markets",
|
|
1136
|
+
"total_market_cap_usd",
|
|
1137
|
+
"total_volume_usd",
|
|
1138
|
+
"total_volume_reported_usd",
|
|
1139
|
+
"btc_dominance_pct",
|
|
1140
|
+
"eth_dominance_pct",
|
|
1141
|
+
"alt_market_cap_usd",
|
|
1142
|
+
"alt_volume_usd",
|
|
1143
|
+
"alt_volume_reported_usd",
|
|
1144
|
+
"btc_to_alt_market_cap_ratio",
|
|
1145
|
+
"market_cap_change_pct_24h_usd"
|
|
1146
|
+
];
|
|
1147
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1148
|
+
if (rows.length > maxRows) {
|
|
1149
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1150
|
+
await upsertMarketGlobalContextRows(rows.slice(i, i + maxRows));
|
|
1151
|
+
}
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
const valuesSql = rows.map(
|
|
1155
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1156
|
+
).join(",");
|
|
1157
|
+
const flat = rows.flatMap((row) => [
|
|
1158
|
+
row.source,
|
|
1159
|
+
row.ts,
|
|
1160
|
+
row.updatedAt ?? null,
|
|
1161
|
+
row.activeCryptocurrencies ?? null,
|
|
1162
|
+
row.activeExchanges ?? null,
|
|
1163
|
+
row.activeMarketPairs ?? null,
|
|
1164
|
+
row.markets ?? null,
|
|
1165
|
+
row.totalMarketCapUsd ?? null,
|
|
1166
|
+
row.totalVolumeUsd ?? null,
|
|
1167
|
+
row.totalVolumeReportedUsd ?? null,
|
|
1168
|
+
row.btcDominancePct ?? null,
|
|
1169
|
+
row.ethDominancePct ?? null,
|
|
1170
|
+
row.altMarketCapUsd ?? null,
|
|
1171
|
+
row.altVolumeUsd ?? null,
|
|
1172
|
+
row.altVolumeReportedUsd ?? null,
|
|
1173
|
+
row.btcToAltMarketCapRatio ?? null,
|
|
1174
|
+
row.marketCapChangePct24hUsd ?? null
|
|
1175
|
+
]);
|
|
1176
|
+
await pool.query(
|
|
1177
|
+
`
|
|
1178
|
+
INSERT INTO market_global_context (${cols.join(",")})
|
|
1179
|
+
VALUES ${valuesSql}
|
|
1180
|
+
ON CONFLICT (source, ts) DO UPDATE SET
|
|
1181
|
+
updated_at_ts = COALESCE(EXCLUDED.updated_at_ts, market_global_context.updated_at_ts),
|
|
1182
|
+
active_cryptocurrencies = COALESCE(EXCLUDED.active_cryptocurrencies, market_global_context.active_cryptocurrencies),
|
|
1183
|
+
active_exchanges = COALESCE(EXCLUDED.active_exchanges, market_global_context.active_exchanges),
|
|
1184
|
+
active_market_pairs = COALESCE(EXCLUDED.active_market_pairs, market_global_context.active_market_pairs),
|
|
1185
|
+
markets = COALESCE(EXCLUDED.markets, market_global_context.markets),
|
|
1186
|
+
total_market_cap_usd = COALESCE(EXCLUDED.total_market_cap_usd, market_global_context.total_market_cap_usd),
|
|
1187
|
+
total_volume_usd = COALESCE(EXCLUDED.total_volume_usd, market_global_context.total_volume_usd),
|
|
1188
|
+
total_volume_reported_usd = COALESCE(EXCLUDED.total_volume_reported_usd, market_global_context.total_volume_reported_usd),
|
|
1189
|
+
btc_dominance_pct = COALESCE(EXCLUDED.btc_dominance_pct, market_global_context.btc_dominance_pct),
|
|
1190
|
+
eth_dominance_pct = COALESCE(EXCLUDED.eth_dominance_pct, market_global_context.eth_dominance_pct),
|
|
1191
|
+
alt_market_cap_usd = COALESCE(EXCLUDED.alt_market_cap_usd, market_global_context.alt_market_cap_usd),
|
|
1192
|
+
alt_volume_usd = COALESCE(EXCLUDED.alt_volume_usd, market_global_context.alt_volume_usd),
|
|
1193
|
+
alt_volume_reported_usd = COALESCE(EXCLUDED.alt_volume_reported_usd, market_global_context.alt_volume_reported_usd),
|
|
1194
|
+
btc_to_alt_market_cap_ratio = COALESCE(EXCLUDED.btc_to_alt_market_cap_ratio, market_global_context.btc_to_alt_market_cap_ratio),
|
|
1195
|
+
market_cap_change_pct_24h_usd = COALESCE(EXCLUDED.market_cap_change_pct_24h_usd, market_global_context.market_cap_change_pct_24h_usd),
|
|
1196
|
+
ingested_at = now()
|
|
1197
|
+
`,
|
|
1198
|
+
flat
|
|
1199
|
+
);
|
|
1200
|
+
}
|
|
1201
|
+
async function upsertMarketReferenceAssetContextRows(rows) {
|
|
1202
|
+
if (!rows.length) return;
|
|
1203
|
+
await ensureBinanceMarketSchema();
|
|
1204
|
+
const pool = getPool();
|
|
1205
|
+
const cols = [
|
|
1206
|
+
"source",
|
|
1207
|
+
"symbol",
|
|
1208
|
+
"cmc_id",
|
|
1209
|
+
"interval",
|
|
1210
|
+
"ts",
|
|
1211
|
+
"open_usd",
|
|
1212
|
+
"high_usd",
|
|
1213
|
+
"low_usd",
|
|
1214
|
+
"close_usd",
|
|
1215
|
+
"volume_usd",
|
|
1216
|
+
"market_cap_usd"
|
|
1217
|
+
];
|
|
1218
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1219
|
+
if (rows.length > maxRows) {
|
|
1220
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1221
|
+
await upsertMarketReferenceAssetContextRows(rows.slice(i, i + maxRows));
|
|
1222
|
+
}
|
|
1223
|
+
return;
|
|
1224
|
+
}
|
|
1225
|
+
const valuesSql = rows.map(
|
|
1226
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1227
|
+
).join(",");
|
|
1228
|
+
const flat = rows.flatMap((row) => [
|
|
1229
|
+
row.source,
|
|
1230
|
+
row.symbol.trim().toUpperCase(),
|
|
1231
|
+
Math.trunc(row.cmcId),
|
|
1232
|
+
row.interval,
|
|
1233
|
+
row.ts,
|
|
1234
|
+
row.openUsd ?? null,
|
|
1235
|
+
row.highUsd ?? null,
|
|
1236
|
+
row.lowUsd ?? null,
|
|
1237
|
+
row.closeUsd ?? null,
|
|
1238
|
+
row.volumeUsd ?? null,
|
|
1239
|
+
row.marketCapUsd ?? null
|
|
1240
|
+
]);
|
|
1241
|
+
await pool.query(
|
|
1242
|
+
`
|
|
1243
|
+
INSERT INTO market_reference_asset_context (${cols.join(",")})
|
|
1244
|
+
VALUES ${valuesSql}
|
|
1245
|
+
ON CONFLICT (source, symbol, interval, ts) DO UPDATE SET
|
|
1246
|
+
cmc_id = EXCLUDED.cmc_id,
|
|
1247
|
+
open_usd = COALESCE(EXCLUDED.open_usd, market_reference_asset_context.open_usd),
|
|
1248
|
+
high_usd = COALESCE(EXCLUDED.high_usd, market_reference_asset_context.high_usd),
|
|
1249
|
+
low_usd = COALESCE(EXCLUDED.low_usd, market_reference_asset_context.low_usd),
|
|
1250
|
+
close_usd = COALESCE(EXCLUDED.close_usd, market_reference_asset_context.close_usd),
|
|
1251
|
+
volume_usd = COALESCE(EXCLUDED.volume_usd, market_reference_asset_context.volume_usd),
|
|
1252
|
+
market_cap_usd = COALESCE(EXCLUDED.market_cap_usd, market_reference_asset_context.market_cap_usd),
|
|
1253
|
+
ingested_at = now()
|
|
1254
|
+
`,
|
|
1255
|
+
flat
|
|
1256
|
+
);
|
|
1257
|
+
}
|
|
1258
|
+
async function upsertMarketCmcExchangeLiquidityContextRows(rows) {
|
|
1259
|
+
if (!rows.length) return;
|
|
1260
|
+
await ensureBinanceMarketSchema();
|
|
1261
|
+
const pool = getPool();
|
|
1262
|
+
const cols = [
|
|
1263
|
+
"source",
|
|
1264
|
+
"interval",
|
|
1265
|
+
"ts",
|
|
1266
|
+
"exchanges_count",
|
|
1267
|
+
"total_volume_usd",
|
|
1268
|
+
"binance_volume_usd",
|
|
1269
|
+
"binance_volume_share",
|
|
1270
|
+
"top_exchange_volume_share",
|
|
1271
|
+
"liquidity_regime"
|
|
1272
|
+
];
|
|
1273
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1274
|
+
if (rows.length > maxRows) {
|
|
1275
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1276
|
+
await upsertMarketCmcExchangeLiquidityContextRows(
|
|
1277
|
+
rows.slice(i, i + maxRows)
|
|
1278
|
+
);
|
|
1279
|
+
}
|
|
1280
|
+
return;
|
|
1281
|
+
}
|
|
1282
|
+
const valuesSql = rows.map(
|
|
1283
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1284
|
+
).join(",");
|
|
1285
|
+
const flat = rows.flatMap((row) => [
|
|
1286
|
+
row.source,
|
|
1287
|
+
row.interval,
|
|
1288
|
+
row.ts,
|
|
1289
|
+
Math.trunc(row.exchangesCount),
|
|
1290
|
+
row.totalVolumeUsd ?? null,
|
|
1291
|
+
row.binanceVolumeUsd ?? null,
|
|
1292
|
+
row.binanceVolumeShare ?? null,
|
|
1293
|
+
row.topExchangeVolumeShare ?? null,
|
|
1294
|
+
row.liquidityRegime ?? null
|
|
1295
|
+
]);
|
|
1296
|
+
await pool.query(
|
|
1297
|
+
`
|
|
1298
|
+
INSERT INTO market_cmc_exchange_liquidity_context (${cols.join(",")})
|
|
1299
|
+
VALUES ${valuesSql}
|
|
1300
|
+
ON CONFLICT (source, interval, ts) DO UPDATE SET
|
|
1301
|
+
exchanges_count = EXCLUDED.exchanges_count,
|
|
1302
|
+
total_volume_usd = COALESCE(EXCLUDED.total_volume_usd, market_cmc_exchange_liquidity_context.total_volume_usd),
|
|
1303
|
+
binance_volume_usd = COALESCE(EXCLUDED.binance_volume_usd, market_cmc_exchange_liquidity_context.binance_volume_usd),
|
|
1304
|
+
binance_volume_share = COALESCE(EXCLUDED.binance_volume_share, market_cmc_exchange_liquidity_context.binance_volume_share),
|
|
1305
|
+
top_exchange_volume_share = COALESCE(EXCLUDED.top_exchange_volume_share, market_cmc_exchange_liquidity_context.top_exchange_volume_share),
|
|
1306
|
+
liquidity_regime = COALESCE(EXCLUDED.liquidity_regime, market_cmc_exchange_liquidity_context.liquidity_regime),
|
|
1307
|
+
ingested_at = now()
|
|
1308
|
+
`,
|
|
1309
|
+
flat
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
async function upsertMarketCmcFearGreedContextRows(rows) {
|
|
1313
|
+
if (!rows.length) return;
|
|
1314
|
+
await ensureBinanceMarketSchema();
|
|
1315
|
+
const pool = getPool();
|
|
1316
|
+
const cols = [
|
|
1317
|
+
"source",
|
|
1318
|
+
"interval",
|
|
1319
|
+
"ts",
|
|
1320
|
+
"value",
|
|
1321
|
+
"classification",
|
|
1322
|
+
"sentiment_regime"
|
|
1323
|
+
];
|
|
1324
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1325
|
+
if (rows.length > maxRows) {
|
|
1326
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1327
|
+
await upsertMarketCmcFearGreedContextRows(rows.slice(i, i + maxRows));
|
|
1328
|
+
}
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
const valuesSql = rows.map(
|
|
1332
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1333
|
+
).join(",");
|
|
1334
|
+
const flat = rows.flatMap((row) => [
|
|
1335
|
+
row.source,
|
|
1336
|
+
row.interval,
|
|
1337
|
+
row.ts,
|
|
1338
|
+
Math.trunc(row.value),
|
|
1339
|
+
row.classification,
|
|
1340
|
+
row.sentimentRegime
|
|
1341
|
+
]);
|
|
1342
|
+
await pool.query(
|
|
1343
|
+
`
|
|
1344
|
+
INSERT INTO market_cmc_fear_greed_context (${cols.join(",")})
|
|
1345
|
+
VALUES ${valuesSql}
|
|
1346
|
+
ON CONFLICT (source, interval, ts) DO UPDATE SET
|
|
1347
|
+
value = EXCLUDED.value,
|
|
1348
|
+
classification = EXCLUDED.classification,
|
|
1349
|
+
sentiment_regime = EXCLUDED.sentiment_regime,
|
|
1350
|
+
ingested_at = now()
|
|
1351
|
+
`,
|
|
1352
|
+
flat
|
|
1353
|
+
);
|
|
1354
|
+
}
|
|
1355
|
+
async function upsertMarketCmcIndexContextRows(rows) {
|
|
1356
|
+
if (!rows.length) return;
|
|
1357
|
+
await ensureBinanceMarketSchema();
|
|
1358
|
+
const pool = getPool();
|
|
1359
|
+
const cols = [
|
|
1360
|
+
"source",
|
|
1361
|
+
"index_slug",
|
|
1362
|
+
"interval",
|
|
1363
|
+
"ts",
|
|
1364
|
+
"value",
|
|
1365
|
+
"constituents_count",
|
|
1366
|
+
"top_constituent_symbol",
|
|
1367
|
+
"top_constituent_weight_pct",
|
|
1368
|
+
"constituents"
|
|
1369
|
+
];
|
|
1370
|
+
const maxRows = getSafeBulkInsertRows(cols.length);
|
|
1371
|
+
if (rows.length > maxRows) {
|
|
1372
|
+
for (let i = 0; i < rows.length; i += maxRows) {
|
|
1373
|
+
await upsertMarketCmcIndexContextRows(rows.slice(i, i + maxRows));
|
|
1374
|
+
}
|
|
1375
|
+
return;
|
|
1376
|
+
}
|
|
1377
|
+
const valuesSql = rows.map(
|
|
1378
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1379
|
+
).join(",");
|
|
1380
|
+
const flat = rows.flatMap((row) => [
|
|
1381
|
+
row.source,
|
|
1382
|
+
row.indexSlug,
|
|
1383
|
+
row.interval,
|
|
1384
|
+
row.ts,
|
|
1385
|
+
row.value,
|
|
1386
|
+
row.constituentsCount ?? null,
|
|
1387
|
+
row.topConstituentSymbol ?? null,
|
|
1388
|
+
row.topConstituentWeightPct ?? null,
|
|
1389
|
+
row.constituents ? JSON.stringify(row.constituents) : null
|
|
1390
|
+
]);
|
|
1391
|
+
await pool.query(
|
|
1392
|
+
`
|
|
1393
|
+
INSERT INTO market_cmc_index_context (${cols.join(",")})
|
|
1394
|
+
VALUES ${valuesSql}
|
|
1395
|
+
ON CONFLICT (source, index_slug, interval, ts) DO UPDATE SET
|
|
1396
|
+
value = EXCLUDED.value,
|
|
1397
|
+
constituents_count = COALESCE(EXCLUDED.constituents_count, market_cmc_index_context.constituents_count),
|
|
1398
|
+
top_constituent_symbol = COALESCE(EXCLUDED.top_constituent_symbol, market_cmc_index_context.top_constituent_symbol),
|
|
1399
|
+
top_constituent_weight_pct = COALESCE(EXCLUDED.top_constituent_weight_pct, market_cmc_index_context.top_constituent_weight_pct),
|
|
1400
|
+
constituents = COALESCE(EXCLUDED.constituents, market_cmc_index_context.constituents),
|
|
1401
|
+
ingested_at = now()
|
|
1402
|
+
`,
|
|
1403
|
+
flat
|
|
1404
|
+
);
|
|
1405
|
+
}
|
|
1406
|
+
async function getMarketContextBackfillCoverage(params) {
|
|
1407
|
+
const source = String(params.source || "").trim().toLowerCase();
|
|
1408
|
+
const scopes = [
|
|
1409
|
+
...new Set(
|
|
1410
|
+
params.scopes.map(
|
|
1411
|
+
(scope) => String(scope || "").trim().toLowerCase()
|
|
1412
|
+
).filter(Boolean)
|
|
1413
|
+
)
|
|
1414
|
+
];
|
|
1415
|
+
const interval = String(params.interval || "").trim().toLowerCase();
|
|
1416
|
+
if (!source || !scopes.length || !interval) return [];
|
|
1417
|
+
await ensureBinanceMarketSchema();
|
|
1418
|
+
const pool = getPool();
|
|
1419
|
+
const res = await pool.query(
|
|
1420
|
+
`
|
|
1421
|
+
SELECT
|
|
1422
|
+
source,
|
|
1423
|
+
scope,
|
|
1424
|
+
interval,
|
|
1425
|
+
extract(epoch from from_ts)*1000 AS from_ms,
|
|
1426
|
+
extract(epoch from to_ts)*1000 AS to_ms,
|
|
1427
|
+
rows_count
|
|
1428
|
+
FROM market_context_backfill_coverage
|
|
1429
|
+
WHERE source = $1
|
|
1430
|
+
AND scope = ANY($2)
|
|
1431
|
+
AND interval = $3
|
|
1432
|
+
AND from_ts >= to_timestamp($4/1000.0)
|
|
1433
|
+
AND to_ts <= to_timestamp($5/1000.0)
|
|
1434
|
+
`,
|
|
1435
|
+
[source, scopes, interval, params.fromMs, params.toMs]
|
|
1436
|
+
);
|
|
1437
|
+
return res.rows.map((row) => ({
|
|
1438
|
+
source: String(row.source).toLowerCase(),
|
|
1439
|
+
scope: String(row.scope).toLowerCase(),
|
|
1440
|
+
interval: String(row.interval).toLowerCase(),
|
|
1441
|
+
fromMs: Number(row.from_ms),
|
|
1442
|
+
toMs: Number(row.to_ms),
|
|
1443
|
+
rowsCount: Number(row.rows_count ?? 0)
|
|
1444
|
+
}));
|
|
1445
|
+
}
|
|
1446
|
+
async function upsertMarketContextBackfillCoverage(rows) {
|
|
1447
|
+
const normalizedRows = rows.map((row) => ({
|
|
1448
|
+
source: String(row.source || "").trim().toLowerCase(),
|
|
1449
|
+
scope: String(row.scope || "").trim().toLowerCase(),
|
|
1450
|
+
interval: String(row.interval || "").trim().toLowerCase(),
|
|
1451
|
+
fromMs: Math.trunc(row.fromMs),
|
|
1452
|
+
toMs: Math.trunc(row.toMs),
|
|
1453
|
+
rowsCount: Math.max(0, Math.trunc(row.rowsCount))
|
|
1454
|
+
})).filter(
|
|
1455
|
+
(row) => row.source && row.scope && row.interval && Number.isFinite(row.fromMs) && Number.isFinite(row.toMs) && row.toMs >= row.fromMs
|
|
1456
|
+
);
|
|
1457
|
+
if (!normalizedRows.length) return;
|
|
1458
|
+
await ensureBinanceMarketSchema();
|
|
1459
|
+
const pool = getPool();
|
|
1460
|
+
const cols = [
|
|
1461
|
+
"source",
|
|
1462
|
+
"scope",
|
|
1463
|
+
"interval",
|
|
1464
|
+
"from_ts",
|
|
1465
|
+
"to_ts",
|
|
1466
|
+
"rows_count"
|
|
1467
|
+
];
|
|
1468
|
+
const valuesSql = normalizedRows.map(
|
|
1469
|
+
(_, i) => `(${cols.map((__, j) => `$${i * cols.length + j + 1}`).join(",")})`
|
|
1470
|
+
).join(",");
|
|
1471
|
+
const flat = normalizedRows.flatMap((row) => [
|
|
1472
|
+
row.source,
|
|
1473
|
+
row.scope,
|
|
1474
|
+
row.interval,
|
|
1475
|
+
new Date(row.fromMs),
|
|
1476
|
+
new Date(row.toMs),
|
|
1477
|
+
row.rowsCount
|
|
1478
|
+
]);
|
|
1479
|
+
await pool.query(
|
|
1480
|
+
`
|
|
1481
|
+
INSERT INTO market_context_backfill_coverage (${cols.join(",")})
|
|
1482
|
+
VALUES ${valuesSql}
|
|
1483
|
+
ON CONFLICT (source, scope, interval, from_ts, to_ts) DO UPDATE SET
|
|
1484
|
+
rows_count = EXCLUDED.rows_count,
|
|
1485
|
+
checked_at = now()
|
|
1486
|
+
`,
|
|
1487
|
+
flat
|
|
1488
|
+
);
|
|
1489
|
+
}
|
|
1490
|
+
var toMarketFeatureAge = (rowTs, atMs) => {
|
|
1491
|
+
const ageMs = atMs - rowTs.getTime();
|
|
1492
|
+
return Number.isFinite(ageMs) ? ageMs : null;
|
|
1493
|
+
};
|
|
1494
|
+
async function getLatestMarketTradeFlow(params) {
|
|
1495
|
+
await ensureBinanceMarketSchema();
|
|
1496
|
+
const pool = getPool();
|
|
1497
|
+
const res = await pool.query(
|
|
1498
|
+
`
|
|
1499
|
+
SELECT
|
|
1500
|
+
symbol,
|
|
1501
|
+
interval,
|
|
1502
|
+
ts,
|
|
1503
|
+
trades::int AS trades,
|
|
1504
|
+
buy_base_volume AS "buyBaseVolume",
|
|
1505
|
+
sell_base_volume AS "sellBaseVolume",
|
|
1506
|
+
buy_quote_volume AS "buyQuoteVolume",
|
|
1507
|
+
sell_quote_volume AS "sellQuoteVolume",
|
|
1508
|
+
net_base_delta AS "netBaseDelta",
|
|
1509
|
+
net_quote_delta AS "netQuoteDelta",
|
|
1510
|
+
buy_pressure_pct AS "buyPressurePct",
|
|
1511
|
+
source
|
|
1512
|
+
FROM market_trade_flow
|
|
1513
|
+
WHERE symbol = $1
|
|
1514
|
+
AND interval = $2
|
|
1515
|
+
AND ts <= to_timestamp($3/1000.0)
|
|
1516
|
+
ORDER BY ts DESC
|
|
1517
|
+
LIMIT 1
|
|
1518
|
+
`,
|
|
1519
|
+
[params.symbol.toUpperCase(), params.interval, params.atMs]
|
|
1520
|
+
);
|
|
1521
|
+
const row = res.rows[0];
|
|
1522
|
+
if (!row) return null;
|
|
1523
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1524
|
+
return {
|
|
1525
|
+
...row,
|
|
1526
|
+
ageMs,
|
|
1527
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs
|
|
1528
|
+
};
|
|
1529
|
+
}
|
|
1530
|
+
async function getLatestMarketBreadth(params) {
|
|
1531
|
+
await ensureBinanceMarketSchema();
|
|
1532
|
+
const pool = getPool();
|
|
1533
|
+
const res = await pool.query(
|
|
1534
|
+
`
|
|
1535
|
+
SELECT
|
|
1536
|
+
universe,
|
|
1537
|
+
interval,
|
|
1538
|
+
ts,
|
|
1539
|
+
symbols_count::int AS "symbolsCount",
|
|
1540
|
+
advancers::int AS advancers,
|
|
1541
|
+
decliners::int AS decliners,
|
|
1542
|
+
unchanged::int AS unchanged,
|
|
1543
|
+
advance_decline_ratio AS "advanceDeclineRatio",
|
|
1544
|
+
pct_above_ma20 AS "pctAboveMa20",
|
|
1545
|
+
pct_above_ma50 AS "pctAboveMa50",
|
|
1546
|
+
equal_weighted_return AS "equalWeightedReturn",
|
|
1547
|
+
volume_weighted_return AS "volumeWeightedReturn",
|
|
1548
|
+
dispersion,
|
|
1549
|
+
btc_return_1h AS "btcReturn1h",
|
|
1550
|
+
btc_return_4h AS "btcReturn4h",
|
|
1551
|
+
btc_return_24h AS "btcReturn24h",
|
|
1552
|
+
alt_basket_return_1h AS "altBasketReturn1h",
|
|
1553
|
+
alt_basket_return_4h AS "altBasketReturn4h",
|
|
1554
|
+
alt_basket_return_24h AS "altBasketReturn24h",
|
|
1555
|
+
btc_vs_alt_return_1h AS "btcVsAltReturn1h",
|
|
1556
|
+
btc_vs_alt_return_4h AS "btcVsAltReturn4h",
|
|
1557
|
+
btc_vs_alt_return_24h AS "btcVsAltReturn24h",
|
|
1558
|
+
btc_turnover_share_1h AS "btcTurnoverShare1h",
|
|
1559
|
+
btc_turnover_share_24h AS "btcTurnoverShare24h",
|
|
1560
|
+
btc_turnover_share_change_24h AS "btcTurnoverShareChange24h",
|
|
1561
|
+
alt_vol_to_btc_vol_24h AS "altVolToBtcVol24h",
|
|
1562
|
+
alt_dispersion_24h AS "altDispersion24h",
|
|
1563
|
+
btc_alt_regime AS "btcAltRegime",
|
|
1564
|
+
source
|
|
1565
|
+
FROM market_breadth
|
|
1566
|
+
WHERE universe = $1
|
|
1567
|
+
AND interval = $2
|
|
1568
|
+
AND ts <= to_timestamp($3/1000.0)
|
|
1569
|
+
ORDER BY ts DESC
|
|
1570
|
+
LIMIT 1
|
|
1571
|
+
`,
|
|
1572
|
+
[params.universe, params.interval, params.atMs]
|
|
1573
|
+
);
|
|
1574
|
+
const row = res.rows[0];
|
|
1575
|
+
if (!row) return null;
|
|
1576
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1577
|
+
return {
|
|
1578
|
+
...row,
|
|
1579
|
+
ageMs,
|
|
1580
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
async function getLatestMarketGlobalContext(params) {
|
|
1584
|
+
await ensureBinanceMarketSchema();
|
|
1585
|
+
const pool = getPool();
|
|
1586
|
+
const source = params.source ?? "coinmarketcap_global";
|
|
1587
|
+
const res = await pool.query(
|
|
1588
|
+
`
|
|
1589
|
+
SELECT
|
|
1590
|
+
source,
|
|
1591
|
+
ts,
|
|
1592
|
+
updated_at_ts AS "updatedAt",
|
|
1593
|
+
active_cryptocurrencies::int AS "activeCryptocurrencies",
|
|
1594
|
+
active_exchanges::int AS "activeExchanges",
|
|
1595
|
+
active_market_pairs::int AS "activeMarketPairs",
|
|
1596
|
+
markets::int AS markets,
|
|
1597
|
+
total_market_cap_usd AS "totalMarketCapUsd",
|
|
1598
|
+
total_volume_usd AS "totalVolumeUsd",
|
|
1599
|
+
total_volume_reported_usd AS "totalVolumeReportedUsd",
|
|
1600
|
+
btc_dominance_pct AS "btcDominancePct",
|
|
1601
|
+
eth_dominance_pct AS "ethDominancePct",
|
|
1602
|
+
alt_market_cap_usd AS "altMarketCapUsd",
|
|
1603
|
+
alt_volume_usd AS "altVolumeUsd",
|
|
1604
|
+
alt_volume_reported_usd AS "altVolumeReportedUsd",
|
|
1605
|
+
btc_to_alt_market_cap_ratio AS "btcToAltMarketCapRatio",
|
|
1606
|
+
market_cap_change_pct_24h_usd AS "marketCapChangePct24hUsd"
|
|
1607
|
+
FROM market_global_context
|
|
1608
|
+
WHERE source = $1
|
|
1609
|
+
AND ts <= to_timestamp($2/1000.0)
|
|
1610
|
+
ORDER BY ts DESC
|
|
1611
|
+
LIMIT 1
|
|
1612
|
+
`,
|
|
1613
|
+
[source, params.atMs]
|
|
1614
|
+
);
|
|
1615
|
+
const row = res.rows[0];
|
|
1616
|
+
if (!row) return null;
|
|
1617
|
+
const previousRes = await pool.query(
|
|
1618
|
+
`
|
|
1619
|
+
SELECT
|
|
1620
|
+
btc_dominance_pct AS "btcDominancePct",
|
|
1621
|
+
eth_dominance_pct AS "ethDominancePct",
|
|
1622
|
+
alt_market_cap_usd AS "altMarketCapUsd",
|
|
1623
|
+
alt_volume_usd AS "altVolumeUsd"
|
|
1624
|
+
FROM market_global_context
|
|
1625
|
+
WHERE source = $1
|
|
1626
|
+
AND ts <= $2::timestamptz - interval '24 hours'
|
|
1627
|
+
ORDER BY ts DESC
|
|
1628
|
+
LIMIT 1
|
|
1629
|
+
`,
|
|
1630
|
+
[source, row.ts]
|
|
1631
|
+
);
|
|
1632
|
+
const previousDominance = previousRes.rows[0]?.btcDominancePct == null ? null : Number(previousRes.rows[0].btcDominancePct);
|
|
1633
|
+
const previousEthDominance = previousRes.rows[0]?.ethDominancePct == null ? null : Number(previousRes.rows[0].ethDominancePct);
|
|
1634
|
+
const previousAltMarketCap = previousRes.rows[0]?.altMarketCapUsd == null ? null : Number(previousRes.rows[0].altMarketCapUsd);
|
|
1635
|
+
const previousAltVolume = previousRes.rows[0]?.altVolumeUsd == null ? null : Number(previousRes.rows[0].altVolumeUsd);
|
|
1636
|
+
const currentDominance = row.btcDominancePct == null ? null : Number(row.btcDominancePct);
|
|
1637
|
+
const currentEthDominance = row.ethDominancePct == null ? null : Number(row.ethDominancePct);
|
|
1638
|
+
const currentAltMarketCap = row.altMarketCapUsd == null ? null : Number(row.altMarketCapUsd);
|
|
1639
|
+
const currentAltVolume = row.altVolumeUsd == null ? null : Number(row.altVolumeUsd);
|
|
1640
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1641
|
+
return {
|
|
1642
|
+
...row,
|
|
1643
|
+
ageMs,
|
|
1644
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs,
|
|
1645
|
+
btcDominanceChange24hPct: currentDominance != null && previousDominance != null ? currentDominance - previousDominance : null,
|
|
1646
|
+
ethDominanceChange24hPct: currentEthDominance != null && previousEthDominance != null ? currentEthDominance - previousEthDominance : null,
|
|
1647
|
+
altMarketCapChange24hPct: currentAltMarketCap != null && previousAltMarketCap != null && previousAltMarketCap > 0 ? (currentAltMarketCap - previousAltMarketCap) / previousAltMarketCap : null,
|
|
1648
|
+
altVolumeChange24hPct: currentAltVolume != null && previousAltVolume != null && previousAltVolume > 0 ? (currentAltVolume - previousAltVolume) / previousAltVolume : null
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
async function getMarketGlobalContextCoverage(params) {
|
|
1652
|
+
await ensureBinanceMarketSchema();
|
|
1653
|
+
const pool = getPool();
|
|
1654
|
+
const res = await pool.query(
|
|
1655
|
+
`
|
|
1656
|
+
SELECT
|
|
1657
|
+
extract(epoch from MIN(ts))*1000 AS first_ms,
|
|
1658
|
+
extract(epoch from MAX(ts))*1000 AS last_ms,
|
|
1659
|
+
COUNT(*)::int AS rows
|
|
1660
|
+
FROM market_global_context
|
|
1661
|
+
WHERE source = $1
|
|
1662
|
+
AND ts >= to_timestamp($2/1000.0)
|
|
1663
|
+
AND ts <= to_timestamp($3/1000.0)
|
|
1664
|
+
`,
|
|
1665
|
+
[params.source, params.startMs, params.endMs]
|
|
1666
|
+
);
|
|
1667
|
+
const row = res.rows[0];
|
|
1668
|
+
const rows = Number(row?.rows ?? 0);
|
|
1669
|
+
const firstMs = Number(row?.first_ms);
|
|
1670
|
+
const lastMs = Number(row?.last_ms);
|
|
1671
|
+
if (!rows || !Number.isFinite(firstMs) || !Number.isFinite(lastMs)) {
|
|
1672
|
+
return null;
|
|
1673
|
+
}
|
|
1674
|
+
return { firstMs, lastMs, rows };
|
|
1675
|
+
}
|
|
1676
|
+
async function getMarketReferenceAssetContextCoverage(params) {
|
|
1677
|
+
const symbols = [
|
|
1678
|
+
...new Set(
|
|
1679
|
+
params.symbols.map((symbol) => symbol.trim().toUpperCase()).filter(Boolean)
|
|
1680
|
+
)
|
|
1681
|
+
];
|
|
1682
|
+
const coverage = /* @__PURE__ */ new Map();
|
|
1683
|
+
if (!symbols.length) return coverage;
|
|
1684
|
+
await ensureBinanceMarketSchema();
|
|
1685
|
+
const pool = getPool();
|
|
1686
|
+
const res = await pool.query(
|
|
1687
|
+
`
|
|
1688
|
+
SELECT
|
|
1689
|
+
symbol,
|
|
1690
|
+
extract(epoch from MIN(ts))*1000 AS first_ms,
|
|
1691
|
+
extract(epoch from MAX(ts))*1000 AS last_ms,
|
|
1692
|
+
COUNT(*)::int AS rows
|
|
1693
|
+
FROM market_reference_asset_context
|
|
1694
|
+
WHERE source = $1
|
|
1695
|
+
AND symbol = ANY($2)
|
|
1696
|
+
AND interval = $3
|
|
1697
|
+
AND ts >= to_timestamp($4/1000.0)
|
|
1698
|
+
AND ts <= to_timestamp($5/1000.0)
|
|
1699
|
+
GROUP BY symbol
|
|
1700
|
+
`,
|
|
1701
|
+
[params.source, symbols, params.interval, params.startMs, params.endMs]
|
|
1702
|
+
);
|
|
1703
|
+
for (const row of res.rows) {
|
|
1704
|
+
const firstMs = Number(row.first_ms);
|
|
1705
|
+
const lastMs = Number(row.last_ms);
|
|
1706
|
+
const rows = Number(row.rows);
|
|
1707
|
+
if (Number.isFinite(firstMs) && Number.isFinite(lastMs) && rows > 0) {
|
|
1708
|
+
coverage.set(row.symbol.toUpperCase(), { firstMs, lastMs, rows });
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
return coverage;
|
|
1712
|
+
}
|
|
1713
|
+
async function getLatestMarketReferenceAssetContexts(params) {
|
|
1714
|
+
const source = params.source ?? "coinmarketcap_reference_asset";
|
|
1715
|
+
const interval = params.interval ?? "1d";
|
|
1716
|
+
const symbols = [
|
|
1717
|
+
...new Set(
|
|
1718
|
+
params.symbols.map((symbol) => symbol.trim().toUpperCase()).filter(Boolean)
|
|
1719
|
+
)
|
|
1720
|
+
];
|
|
1721
|
+
const rows = /* @__PURE__ */ new Map();
|
|
1722
|
+
if (!symbols.length) return rows;
|
|
1723
|
+
await ensureBinanceMarketSchema();
|
|
1724
|
+
const pool = getPool();
|
|
1725
|
+
const res = await pool.query(
|
|
1726
|
+
`
|
|
1727
|
+
SELECT DISTINCT ON (symbol)
|
|
1728
|
+
source,
|
|
1729
|
+
symbol,
|
|
1730
|
+
cmc_id AS "cmcId",
|
|
1731
|
+
interval,
|
|
1732
|
+
ts,
|
|
1733
|
+
open_usd AS "openUsd",
|
|
1734
|
+
high_usd AS "highUsd",
|
|
1735
|
+
low_usd AS "lowUsd",
|
|
1736
|
+
close_usd AS "closeUsd",
|
|
1737
|
+
volume_usd AS "volumeUsd",
|
|
1738
|
+
market_cap_usd AS "marketCapUsd"
|
|
1739
|
+
FROM market_reference_asset_context
|
|
1740
|
+
WHERE source = $1
|
|
1741
|
+
AND symbol = ANY($2)
|
|
1742
|
+
AND interval = $3
|
|
1743
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
1744
|
+
ORDER BY symbol ASC, ts DESC
|
|
1745
|
+
`,
|
|
1746
|
+
[source, symbols, interval, params.atMs]
|
|
1747
|
+
);
|
|
1748
|
+
for (const row of res.rows) {
|
|
1749
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1750
|
+
rows.set(row.symbol.toUpperCase(), {
|
|
1751
|
+
...row,
|
|
1752
|
+
ageMs,
|
|
1753
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs
|
|
1754
|
+
});
|
|
1755
|
+
}
|
|
1756
|
+
return rows;
|
|
1757
|
+
}
|
|
1758
|
+
async function getLatestMarketCmcExchangeLiquidityContext(params) {
|
|
1759
|
+
await ensureBinanceMarketSchema();
|
|
1760
|
+
const pool = getPool();
|
|
1761
|
+
const source = params.source ?? "coinmarketcap_exchange_liquidity";
|
|
1762
|
+
const interval = params.interval ?? "1d";
|
|
1763
|
+
const res = await pool.query(
|
|
1764
|
+
`
|
|
1765
|
+
SELECT
|
|
1766
|
+
source,
|
|
1767
|
+
interval,
|
|
1768
|
+
ts,
|
|
1769
|
+
exchanges_count::int AS "exchangesCount",
|
|
1770
|
+
total_volume_usd AS "totalVolumeUsd",
|
|
1771
|
+
binance_volume_usd AS "binanceVolumeUsd",
|
|
1772
|
+
binance_volume_share AS "binanceVolumeShare",
|
|
1773
|
+
top_exchange_volume_share AS "topExchangeVolumeShare",
|
|
1774
|
+
liquidity_regime AS "liquidityRegime"
|
|
1775
|
+
FROM market_cmc_exchange_liquidity_context
|
|
1776
|
+
WHERE source = $1
|
|
1777
|
+
AND interval = $2
|
|
1778
|
+
AND ts <= to_timestamp($3/1000.0)
|
|
1779
|
+
ORDER BY ts DESC
|
|
1780
|
+
LIMIT 1
|
|
1781
|
+
`,
|
|
1782
|
+
[source, interval, params.atMs]
|
|
1783
|
+
);
|
|
1784
|
+
const row = res.rows[0];
|
|
1785
|
+
if (!row) return null;
|
|
1786
|
+
const previousRes = await pool.query(
|
|
1787
|
+
`
|
|
1788
|
+
SELECT total_volume_usd AS "totalVolumeUsd"
|
|
1789
|
+
FROM market_cmc_exchange_liquidity_context
|
|
1790
|
+
WHERE source = $1
|
|
1791
|
+
AND interval = $2
|
|
1792
|
+
AND ts <= $3::timestamptz - interval '24 hours'
|
|
1793
|
+
ORDER BY ts DESC
|
|
1794
|
+
LIMIT 1
|
|
1795
|
+
`,
|
|
1796
|
+
[source, interval, row.ts]
|
|
1797
|
+
);
|
|
1798
|
+
const currentTotal = row.totalVolumeUsd == null ? null : Number(row.totalVolumeUsd);
|
|
1799
|
+
const previousTotal = previousRes.rows[0]?.totalVolumeUsd == null ? null : Number(previousRes.rows[0].totalVolumeUsd);
|
|
1800
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1801
|
+
return {
|
|
1802
|
+
...row,
|
|
1803
|
+
ageMs,
|
|
1804
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs,
|
|
1805
|
+
totalVolumeChange24hPct: currentTotal != null && previousTotal != null && previousTotal > 0 ? (currentTotal - previousTotal) / previousTotal : null
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
async function getLatestMarketCmcIndexContexts(params) {
|
|
1809
|
+
const source = params.source ?? "coinmarketcap_index";
|
|
1810
|
+
const interval = params.interval ?? "1d";
|
|
1811
|
+
const indexSlugs = [
|
|
1812
|
+
...new Set(
|
|
1813
|
+
params.indexSlugs.map((slug) => slug.trim().toLowerCase()).filter(
|
|
1814
|
+
(slug) => ["cmc100", "cmc20"].includes(slug)
|
|
1815
|
+
)
|
|
1816
|
+
)
|
|
1817
|
+
];
|
|
1818
|
+
const rows = /* @__PURE__ */ new Map();
|
|
1819
|
+
if (!indexSlugs.length) return rows;
|
|
1820
|
+
await ensureBinanceMarketSchema();
|
|
1821
|
+
const pool = getPool();
|
|
1822
|
+
const res = await pool.query(
|
|
1823
|
+
`
|
|
1824
|
+
SELECT DISTINCT ON (index_slug)
|
|
1825
|
+
source,
|
|
1826
|
+
index_slug AS "indexSlug",
|
|
1827
|
+
interval,
|
|
1828
|
+
ts,
|
|
1829
|
+
value,
|
|
1830
|
+
constituents_count::int AS "constituentsCount",
|
|
1831
|
+
top_constituent_symbol AS "topConstituentSymbol",
|
|
1832
|
+
top_constituent_weight_pct AS "topConstituentWeightPct",
|
|
1833
|
+
constituents
|
|
1834
|
+
FROM market_cmc_index_context
|
|
1835
|
+
WHERE source = $1
|
|
1836
|
+
AND index_slug = ANY($2)
|
|
1837
|
+
AND interval = $3
|
|
1838
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
1839
|
+
ORDER BY index_slug ASC, ts DESC
|
|
1840
|
+
`,
|
|
1841
|
+
[source, indexSlugs, interval, params.atMs]
|
|
1842
|
+
);
|
|
1843
|
+
for (const row of res.rows) {
|
|
1844
|
+
const previousRes = await pool.query(
|
|
1845
|
+
`
|
|
1846
|
+
SELECT value
|
|
1847
|
+
FROM market_cmc_index_context
|
|
1848
|
+
WHERE source = $1
|
|
1849
|
+
AND index_slug = $2
|
|
1850
|
+
AND interval = $3
|
|
1851
|
+
AND ts <= $4::timestamptz - interval '24 hours'
|
|
1852
|
+
ORDER BY ts DESC
|
|
1853
|
+
LIMIT 1
|
|
1854
|
+
`,
|
|
1855
|
+
[source, row.indexSlug, interval, row.ts]
|
|
1856
|
+
);
|
|
1857
|
+
const currentValue = row.value == null ? null : Number(row.value);
|
|
1858
|
+
const previousValue = previousRes.rows[0]?.value == null ? null : Number(previousRes.rows[0].value);
|
|
1859
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1860
|
+
rows.set(row.indexSlug, {
|
|
1861
|
+
...row,
|
|
1862
|
+
ageMs,
|
|
1863
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs,
|
|
1864
|
+
valueChange24hPct: currentValue != null && previousValue != null && previousValue > 0 ? (currentValue - previousValue) / previousValue : null
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
return rows;
|
|
1868
|
+
}
|
|
1869
|
+
async function getLatestMarketCmcFearGreedContext(params) {
|
|
1870
|
+
await ensureBinanceMarketSchema();
|
|
1871
|
+
const pool = getPool();
|
|
1872
|
+
const source = params.source ?? "coinmarketcap_fear_greed";
|
|
1873
|
+
const interval = params.interval ?? "1d";
|
|
1874
|
+
const res = await pool.query(
|
|
1875
|
+
`
|
|
1876
|
+
SELECT
|
|
1877
|
+
source,
|
|
1878
|
+
interval,
|
|
1879
|
+
ts,
|
|
1880
|
+
value::int AS value,
|
|
1881
|
+
classification,
|
|
1882
|
+
sentiment_regime AS "sentimentRegime"
|
|
1883
|
+
FROM market_cmc_fear_greed_context
|
|
1884
|
+
WHERE source = $1
|
|
1885
|
+
AND interval = $2
|
|
1886
|
+
AND ts <= to_timestamp($3/1000.0)
|
|
1887
|
+
ORDER BY ts DESC
|
|
1888
|
+
LIMIT 1
|
|
1889
|
+
`,
|
|
1890
|
+
[source, interval, params.atMs]
|
|
1891
|
+
);
|
|
1892
|
+
const row = res.rows[0];
|
|
1893
|
+
if (!row) return null;
|
|
1894
|
+
const previousRes = await pool.query(
|
|
1895
|
+
`
|
|
1896
|
+
SELECT
|
|
1897
|
+
value::int AS value,
|
|
1898
|
+
'24h' AS bucket
|
|
1899
|
+
FROM market_cmc_fear_greed_context
|
|
1900
|
+
WHERE source = $1
|
|
1901
|
+
AND interval = $2
|
|
1902
|
+
AND ts <= $3::timestamptz - interval '24 hours'
|
|
1903
|
+
ORDER BY ts DESC
|
|
1904
|
+
LIMIT 1
|
|
1905
|
+
`,
|
|
1906
|
+
[source, interval, row.ts]
|
|
1907
|
+
);
|
|
1908
|
+
const previous7dRes = await pool.query(
|
|
1909
|
+
`
|
|
1910
|
+
SELECT value::int AS value
|
|
1911
|
+
FROM market_cmc_fear_greed_context
|
|
1912
|
+
WHERE source = $1
|
|
1913
|
+
AND interval = $2
|
|
1914
|
+
AND ts <= $3::timestamptz - interval '7 days'
|
|
1915
|
+
ORDER BY ts DESC
|
|
1916
|
+
LIMIT 1
|
|
1917
|
+
`,
|
|
1918
|
+
[source, interval, row.ts]
|
|
1919
|
+
);
|
|
1920
|
+
const previousValue = previousRes.rows[0]?.value == null ? null : Number(previousRes.rows[0].value);
|
|
1921
|
+
const previous7dValue = previous7dRes.rows[0]?.value == null ? null : Number(previous7dRes.rows[0].value);
|
|
1922
|
+
const ageMs = toMarketFeatureAge(row.ts, params.atMs);
|
|
1923
|
+
return {
|
|
1924
|
+
...row,
|
|
1925
|
+
ageMs,
|
|
1926
|
+
stale: ageMs == null || params.maxAgeMs != null && ageMs > params.maxAgeMs,
|
|
1927
|
+
valueChange24h: previousValue == null ? null : row.value - previousValue,
|
|
1928
|
+
valueChange7d: previous7dValue == null ? null : row.value - previous7dValue
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
async function getMarketCmcFearGreedContextCoverage(params) {
|
|
1932
|
+
await ensureBinanceMarketSchema();
|
|
1933
|
+
const pool = getPool();
|
|
1934
|
+
const res = await pool.query(
|
|
1935
|
+
`
|
|
1936
|
+
SELECT
|
|
1937
|
+
extract(epoch from MIN(ts))*1000 AS first_ms,
|
|
1938
|
+
extract(epoch from MAX(ts))*1000 AS last_ms,
|
|
1939
|
+
COUNT(*)::int AS rows
|
|
1940
|
+
FROM market_cmc_fear_greed_context
|
|
1941
|
+
WHERE source = $1
|
|
1942
|
+
AND interval = $2
|
|
1943
|
+
AND ts >= to_timestamp($3/1000.0)
|
|
1944
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
1945
|
+
`,
|
|
1946
|
+
[params.source, params.interval, params.startMs, params.endMs]
|
|
1947
|
+
);
|
|
1948
|
+
const rows = Number(res.rows[0]?.rows ?? 0);
|
|
1949
|
+
const firstMs = Number(res.rows[0]?.first_ms);
|
|
1950
|
+
const lastMs = Number(res.rows[0]?.last_ms);
|
|
1951
|
+
if (!rows || !Number.isFinite(firstMs) || !Number.isFinite(lastMs)) {
|
|
1952
|
+
return null;
|
|
1953
|
+
}
|
|
1954
|
+
return { firstMs, lastMs, rows };
|
|
1955
|
+
}
|
|
1956
|
+
async function getMarketCmcExchangeLiquidityContextCoverage(params) {
|
|
1957
|
+
await ensureBinanceMarketSchema();
|
|
1958
|
+
const pool = getPool();
|
|
1959
|
+
const res = await pool.query(
|
|
1960
|
+
`
|
|
1961
|
+
SELECT
|
|
1962
|
+
extract(epoch from MIN(ts))*1000 AS first_ms,
|
|
1963
|
+
extract(epoch from MAX(ts))*1000 AS last_ms,
|
|
1964
|
+
COUNT(*)::int AS rows
|
|
1965
|
+
FROM market_cmc_exchange_liquidity_context
|
|
1966
|
+
WHERE source = $1
|
|
1967
|
+
AND interval = $2
|
|
1968
|
+
AND ts >= to_timestamp($3/1000.0)
|
|
1969
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
1970
|
+
`,
|
|
1971
|
+
[params.source, params.interval, params.startMs, params.endMs]
|
|
1972
|
+
);
|
|
1973
|
+
const rows = Number(res.rows[0]?.rows ?? 0);
|
|
1974
|
+
const firstMs = Number(res.rows[0]?.first_ms);
|
|
1975
|
+
const lastMs = Number(res.rows[0]?.last_ms);
|
|
1976
|
+
if (!rows || !Number.isFinite(firstMs) || !Number.isFinite(lastMs)) {
|
|
1977
|
+
return null;
|
|
1978
|
+
}
|
|
1979
|
+
return { firstMs, lastMs, rows };
|
|
1980
|
+
}
|
|
1981
|
+
async function getMarketCmcIndexContextCoverage(params) {
|
|
1982
|
+
const indexSlugs = [
|
|
1983
|
+
...new Set(
|
|
1984
|
+
params.indexSlugs.map((slug) => slug.trim().toLowerCase()).filter(
|
|
1985
|
+
(slug) => ["cmc100", "cmc20"].includes(slug)
|
|
1986
|
+
)
|
|
1987
|
+
)
|
|
1988
|
+
];
|
|
1989
|
+
const coverage = /* @__PURE__ */ new Map();
|
|
1990
|
+
if (!indexSlugs.length) return coverage;
|
|
1991
|
+
await ensureBinanceMarketSchema();
|
|
1992
|
+
const pool = getPool();
|
|
1993
|
+
const res = await pool.query(
|
|
1994
|
+
`
|
|
1995
|
+
SELECT
|
|
1996
|
+
index_slug,
|
|
1997
|
+
extract(epoch from MIN(ts))*1000 AS first_ms,
|
|
1998
|
+
extract(epoch from MAX(ts))*1000 AS last_ms,
|
|
1999
|
+
COUNT(*)::int AS rows
|
|
2000
|
+
FROM market_cmc_index_context
|
|
2001
|
+
WHERE source = $1
|
|
2002
|
+
AND index_slug = ANY($2)
|
|
2003
|
+
AND interval = $3
|
|
2004
|
+
AND ts >= to_timestamp($4/1000.0)
|
|
2005
|
+
AND ts <= to_timestamp($5/1000.0)
|
|
2006
|
+
GROUP BY index_slug
|
|
2007
|
+
`,
|
|
2008
|
+
[params.source, indexSlugs, params.interval, params.startMs, params.endMs]
|
|
2009
|
+
);
|
|
2010
|
+
for (const row of res.rows) {
|
|
2011
|
+
const indexSlug = row.index_slug;
|
|
2012
|
+
const firstMs = Number(row.first_ms);
|
|
2013
|
+
const lastMs = Number(row.last_ms);
|
|
2014
|
+
const rows = Number(row.rows);
|
|
2015
|
+
if (Number.isFinite(firstMs) && Number.isFinite(lastMs) && rows > 0) {
|
|
2016
|
+
coverage.set(indexSlug, { firstMs, lastMs, rows });
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
return coverage;
|
|
2020
|
+
}
|
|
2021
|
+
async function getMarketTradeFlowCoverage(params) {
|
|
2022
|
+
const symbols = [
|
|
2023
|
+
...new Set(params.symbols.map((item) => item.toUpperCase()))
|
|
2024
|
+
];
|
|
2025
|
+
if (!symbols.length) return /* @__PURE__ */ new Map();
|
|
2026
|
+
await ensureBinanceMarketSchema();
|
|
2027
|
+
const pool = getPool();
|
|
2028
|
+
const res = await pool.query(
|
|
2029
|
+
`
|
|
2030
|
+
SELECT
|
|
2031
|
+
symbol,
|
|
2032
|
+
MIN(ts) AS first_ts,
|
|
2033
|
+
MAX(ts) AS last_ts,
|
|
2034
|
+
COUNT(*)::int AS rows
|
|
2035
|
+
FROM market_trade_flow
|
|
2036
|
+
WHERE symbol = ANY($1)
|
|
2037
|
+
AND interval = $2
|
|
2038
|
+
AND ts >= to_timestamp($3/1000.0)
|
|
2039
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
2040
|
+
GROUP BY symbol
|
|
2041
|
+
`,
|
|
2042
|
+
[symbols, params.interval, params.startMs, params.endMs]
|
|
2043
|
+
);
|
|
2044
|
+
return new Map(
|
|
2045
|
+
res.rows.map((row) => [
|
|
2046
|
+
String(row.symbol).toUpperCase(),
|
|
2047
|
+
{
|
|
2048
|
+
firstMs: new Date(row.first_ts).getTime(),
|
|
2049
|
+
lastMs: new Date(row.last_ts).getTime(),
|
|
2050
|
+
rows: Number(row.rows) || 0
|
|
2051
|
+
}
|
|
2052
|
+
])
|
|
2053
|
+
);
|
|
2054
|
+
}
|
|
2055
|
+
var getTableRowCountIfExists = async (tableName) => {
|
|
2056
|
+
const pool = getPool();
|
|
2057
|
+
const exists = await pool.query("SELECT to_regclass($1) AS name", [
|
|
2058
|
+
tableName
|
|
2059
|
+
]);
|
|
2060
|
+
if (!exists.rows[0]?.name) return null;
|
|
2061
|
+
const count = await pool.query(
|
|
2062
|
+
`SELECT COUNT(*)::int AS rows FROM ${tableName}`
|
|
2063
|
+
);
|
|
2064
|
+
return Number(count.rows[0]?.rows ?? 0);
|
|
2065
|
+
};
|
|
2066
|
+
async function cleanupDeprecatedMarketContext(params = {}) {
|
|
2067
|
+
const apply = Boolean(params.apply);
|
|
2068
|
+
const pool = getPool();
|
|
2069
|
+
const items = [];
|
|
2070
|
+
const cleanupRows = async ({
|
|
2071
|
+
tableName,
|
|
2072
|
+
whereSql,
|
|
2073
|
+
name
|
|
2074
|
+
}) => {
|
|
2075
|
+
const tableRows = await getTableRowCountIfExists(tableName);
|
|
2076
|
+
if (tableRows == null) return;
|
|
2077
|
+
const count = await pool.query(
|
|
2078
|
+
`
|
|
2079
|
+
SELECT COUNT(*)::int AS rows
|
|
2080
|
+
FROM ${tableName}
|
|
2081
|
+
WHERE ${whereSql}
|
|
2082
|
+
`
|
|
2083
|
+
);
|
|
2084
|
+
const rows = Number(count.rows[0]?.rows ?? 0);
|
|
2085
|
+
if (rows <= 0) return;
|
|
2086
|
+
if (apply) {
|
|
2087
|
+
await pool.query(
|
|
2088
|
+
`
|
|
2089
|
+
DELETE FROM ${tableName}
|
|
2090
|
+
WHERE ${whereSql}
|
|
2091
|
+
`
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
items.push({
|
|
2095
|
+
kind: "rows",
|
|
2096
|
+
name,
|
|
2097
|
+
rows,
|
|
2098
|
+
action: "delete_rows",
|
|
2099
|
+
applied: apply
|
|
2100
|
+
});
|
|
2101
|
+
};
|
|
2102
|
+
for (const tableName of ["market_order_book_depth", "onchain_flow_context"]) {
|
|
2103
|
+
const rows = await getTableRowCountIfExists(tableName);
|
|
2104
|
+
if (rows == null) continue;
|
|
2105
|
+
if (apply) {
|
|
2106
|
+
await pool.query(`DROP TABLE IF EXISTS ${tableName}`);
|
|
2107
|
+
}
|
|
2108
|
+
items.push({
|
|
2109
|
+
kind: "table",
|
|
2110
|
+
name: tableName,
|
|
2111
|
+
rows,
|
|
2112
|
+
action: "drop_table",
|
|
2113
|
+
applied: apply
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
await cleanupRows({
|
|
2117
|
+
tableName: "market_global_context",
|
|
2118
|
+
whereSql: "source = 'coingecko_global'",
|
|
2119
|
+
name: "market_global_context/source=coingecko_global"
|
|
2120
|
+
});
|
|
2121
|
+
await cleanupRows({
|
|
2122
|
+
tableName: "market_global_context",
|
|
2123
|
+
whereSql: "source = 'coinmarketcap_global_hourly'",
|
|
2124
|
+
name: "market_global_context/source=coinmarketcap_global_hourly"
|
|
2125
|
+
});
|
|
2126
|
+
await cleanupRows({
|
|
2127
|
+
tableName: "market_reference_asset_context",
|
|
2128
|
+
whereSql: "source = 'coinmarketcap_reference_asset' AND interval = '1h'",
|
|
2129
|
+
name: "market_reference_asset_context/source=coinmarketcap_reference_asset/interval=1h"
|
|
2130
|
+
});
|
|
2131
|
+
await cleanupRows({
|
|
2132
|
+
tableName: "market_cmc_breadth_context",
|
|
2133
|
+
whereSql: "source = 'coinmarketcap_market_breadth'",
|
|
2134
|
+
name: "market_cmc_breadth_context/source=coinmarketcap_market_breadth"
|
|
2135
|
+
});
|
|
2136
|
+
await cleanupRows({
|
|
2137
|
+
tableName: "market_context_backfill_coverage",
|
|
2138
|
+
whereSql: "(source IN ('coinmarketcap_global_hourly', 'coinmarketcap_market_breadth') OR (source = 'coinmarketcap_reference_asset' AND interval = '1h'))",
|
|
2139
|
+
name: "market_context_backfill_coverage/deprecated_cmc_sources"
|
|
2140
|
+
});
|
|
2141
|
+
return items;
|
|
2142
|
+
}
|
|
2143
|
+
async function getMarketBreadthCoverage(params) {
|
|
2144
|
+
await ensureBinanceMarketSchema();
|
|
2145
|
+
const pool = getPool();
|
|
2146
|
+
const res = await pool.query(
|
|
2147
|
+
`
|
|
2148
|
+
SELECT
|
|
2149
|
+
MIN(ts) AS first_ts,
|
|
2150
|
+
MAX(ts) AS last_ts,
|
|
2151
|
+
COUNT(*)::int AS rows,
|
|
2152
|
+
COUNT(*) FILTER (
|
|
2153
|
+
WHERE btc_alt_regime IS NOT NULL
|
|
2154
|
+
AND btc_return_24h IS NOT NULL
|
|
2155
|
+
AND alt_basket_return_24h IS NOT NULL
|
|
2156
|
+
)::int AS btc_alt_metrics_rows
|
|
2157
|
+
FROM market_breadth
|
|
2158
|
+
WHERE universe = $1
|
|
2159
|
+
AND interval = $2
|
|
2160
|
+
AND ts >= to_timestamp($3/1000.0)
|
|
2161
|
+
AND ts <= to_timestamp($4/1000.0)
|
|
2162
|
+
`,
|
|
2163
|
+
[params.universe, params.interval, params.startMs, params.endMs]
|
|
2164
|
+
);
|
|
2165
|
+
const row = res.rows[0];
|
|
2166
|
+
if (!row?.first_ts || !row?.last_ts) return null;
|
|
2167
|
+
return {
|
|
2168
|
+
firstMs: new Date(row.first_ts).getTime(),
|
|
2169
|
+
lastMs: new Date(row.last_ts).getTime(),
|
|
2170
|
+
rows: Number(row.rows) || 0,
|
|
2171
|
+
btcAltMetricsRows: Number(row.btc_alt_metrics_rows) || 0
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
397
2174
|
async function getSpreadRangeForSymbols(symbols, interval, startMs, endMs) {
|
|
398
2175
|
if (!symbols.length) {
|
|
399
2176
|
return [];
|
|
@@ -451,12 +2228,17 @@ async function getSpreadSummary(hours = 24, limit = 500) {
|
|
|
451
2228
|
};
|
|
452
2229
|
}
|
|
453
2230
|
async function getCandlesRange(provider, symbol, interval, startMs, endMs) {
|
|
2231
|
+
await ensureCandlesSchema();
|
|
454
2232
|
const pool = getPool();
|
|
455
2233
|
const normalizedProvider = normalizeCandleProvider(provider);
|
|
456
2234
|
const normalizedSymbol = normalizeCandleSymbol(symbol);
|
|
457
2235
|
const sql = `
|
|
458
2236
|
SELECT symbol, interval, ts,
|
|
459
|
-
open, high, low, close, volume, turnover
|
|
2237
|
+
open, high, low, close, volume, turnover,
|
|
2238
|
+
taker_buy_base_volume AS "takerBuyBaseVolume",
|
|
2239
|
+
taker_buy_quote_volume AS "takerBuyQuoteVolume",
|
|
2240
|
+
taker_sell_base_volume AS "takerSellBaseVolume",
|
|
2241
|
+
taker_sell_quote_volume AS "takerSellQuoteVolume"
|
|
460
2242
|
FROM candles
|
|
461
2243
|
WHERE provider = $1 AND symbol = $2 AND interval = $3
|
|
462
2244
|
AND ts >= to_timestamp($4/1000.0)
|
|
@@ -500,6 +2282,58 @@ async function getDataEdges(provider, symbol, interval) {
|
|
|
500
2282
|
const max = Number.isFinite(Number(maxRaw)) ? Number(maxRaw) : void 0;
|
|
501
2283
|
return { min, max };
|
|
502
2284
|
}
|
|
2285
|
+
async function getDataEdgesForSymbols(provider, symbols, interval) {
|
|
2286
|
+
const normalizedSymbols = [
|
|
2287
|
+
...new Set(symbols.map(normalizeCandleSymbol).filter(Boolean))
|
|
2288
|
+
];
|
|
2289
|
+
const result = /* @__PURE__ */ new Map();
|
|
2290
|
+
for (const symbol of normalizedSymbols) {
|
|
2291
|
+
result.set(symbol, {});
|
|
2292
|
+
}
|
|
2293
|
+
if (!normalizedSymbols.length) {
|
|
2294
|
+
return result;
|
|
2295
|
+
}
|
|
2296
|
+
const pool = getPool();
|
|
2297
|
+
const normalizedProvider = normalizeCandleProvider(provider);
|
|
2298
|
+
const sql = `
|
|
2299
|
+
WITH requested(symbol) AS (
|
|
2300
|
+
SELECT unnest($2::text[])
|
|
2301
|
+
)
|
|
2302
|
+
SELECT
|
|
2303
|
+
r.symbol,
|
|
2304
|
+
(
|
|
2305
|
+
SELECT extract(epoch from c.ts)*1000
|
|
2306
|
+
FROM candles c
|
|
2307
|
+
WHERE c.provider = $1 AND c.symbol = r.symbol AND c.interval = $3
|
|
2308
|
+
ORDER BY c.ts ASC
|
|
2309
|
+
LIMIT 1
|
|
2310
|
+
) AS min_ms,
|
|
2311
|
+
(
|
|
2312
|
+
SELECT extract(epoch from c.ts)*1000
|
|
2313
|
+
FROM candles c
|
|
2314
|
+
WHERE c.provider = $1 AND c.symbol = r.symbol AND c.interval = $3
|
|
2315
|
+
ORDER BY c.ts DESC
|
|
2316
|
+
LIMIT 1
|
|
2317
|
+
) AS max_ms
|
|
2318
|
+
FROM requested r
|
|
2319
|
+
`;
|
|
2320
|
+
const response = await pool.query(sql, [
|
|
2321
|
+
normalizedProvider,
|
|
2322
|
+
normalizedSymbols,
|
|
2323
|
+
interval
|
|
2324
|
+
]);
|
|
2325
|
+
for (const row of response.rows) {
|
|
2326
|
+
const symbol = normalizeCandleSymbol(String(row.symbol || ""));
|
|
2327
|
+
if (!symbol) continue;
|
|
2328
|
+
const min = row.min_ms == null ? NaN : Number(row.min_ms);
|
|
2329
|
+
const max = row.max_ms == null ? NaN : Number(row.max_ms);
|
|
2330
|
+
result.set(symbol, {
|
|
2331
|
+
...Number.isFinite(min) ? { min } : {},
|
|
2332
|
+
...Number.isFinite(max) ? { max } : {}
|
|
2333
|
+
});
|
|
2334
|
+
}
|
|
2335
|
+
return result;
|
|
2336
|
+
}
|
|
503
2337
|
async function waitForDbReady(attempts = 20, delayMs = 1e3) {
|
|
504
2338
|
const pool = getPool();
|
|
505
2339
|
let lastError;
|
|
@@ -562,19 +2396,47 @@ async function findContinuityGap(provider, symbol, interval) {
|
|
|
562
2396
|
};
|
|
563
2397
|
}
|
|
564
2398
|
export {
|
|
2399
|
+
cleanupDeprecatedMarketContext,
|
|
2400
|
+
closeTimescalePool,
|
|
565
2401
|
deleteCandles,
|
|
566
2402
|
findContinuityGap,
|
|
567
2403
|
getCandlesRange,
|
|
568
2404
|
getDataEdges,
|
|
2405
|
+
getDataEdgesForSymbols,
|
|
2406
|
+
getDerivativesBackfillCoverage,
|
|
569
2407
|
getDerivativesDataEdgesForSymbols,
|
|
570
2408
|
getDerivativesRangeForSymbols,
|
|
571
2409
|
getDerivativesSummary,
|
|
572
2410
|
getDerivativesWindow,
|
|
2411
|
+
getLatestMarketBreadth,
|
|
2412
|
+
getLatestMarketCmcExchangeLiquidityContext,
|
|
2413
|
+
getLatestMarketCmcFearGreedContext,
|
|
2414
|
+
getLatestMarketCmcIndexContexts,
|
|
2415
|
+
getLatestMarketGlobalContext,
|
|
2416
|
+
getLatestMarketReferenceAssetContexts,
|
|
2417
|
+
getLatestMarketTradeFlow,
|
|
2418
|
+
getMarketBreadthCoverage,
|
|
2419
|
+
getMarketCmcExchangeLiquidityContextCoverage,
|
|
2420
|
+
getMarketCmcFearGreedContextCoverage,
|
|
2421
|
+
getMarketCmcIndexContextCoverage,
|
|
2422
|
+
getMarketContextBackfillCoverage,
|
|
2423
|
+
getMarketGlobalContextCoverage,
|
|
2424
|
+
getMarketReferenceAssetContextCoverage,
|
|
2425
|
+
getMarketTradeFlowCoverage,
|
|
573
2426
|
getSpreadRangeForSymbols,
|
|
574
2427
|
getSpreadSummary,
|
|
575
2428
|
toRows,
|
|
576
2429
|
upsertCandles,
|
|
577
2430
|
upsertDerivatives,
|
|
2431
|
+
upsertDerivativesBackfillCoverage,
|
|
2432
|
+
upsertMarketBreadthRows,
|
|
2433
|
+
upsertMarketCmcExchangeLiquidityContextRows,
|
|
2434
|
+
upsertMarketCmcFearGreedContextRows,
|
|
2435
|
+
upsertMarketCmcIndexContextRows,
|
|
2436
|
+
upsertMarketContextBackfillCoverage,
|
|
2437
|
+
upsertMarketGlobalContextRows,
|
|
2438
|
+
upsertMarketReferenceAssetContextRows,
|
|
2439
|
+
upsertMarketTradeFlowRows,
|
|
578
2440
|
upsertSpreadRows,
|
|
579
2441
|
waitForDbReady
|
|
580
2442
|
};
|