neuroalpha 0.5.17 → 0.5.20
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/package.json +61 -60
- package/public/admin.html +604 -571
- package/public/app.js +101 -22
- package/public/landing.html +1207 -1273
- package/public/legal.html +6 -5
- package/public/splat3d.html +671 -0
- package/public/styles.css +12 -3
- package/scripts/set-admin-password.mjs +30 -0
- package/server/api/routes.js +55 -16
- package/server/auth/index.js +58 -13
- package/server/billing/yookassa.js +142 -133
- package/server/brokers/index.js +84 -52
- package/server/data/moex.js +6 -5
- package/server/db.js +1 -1
- package/server/index.js +3 -3
- package/server/instance/central.js +514 -505
- package/server/model/dataset.js +8 -9
- package/server/model/edge.js +74 -19
- package/server/model/forecast.js +117 -20
- package/server/model/live.js +16 -18
- package/server/model/research.js +48 -17
- package/server/security.js +4 -1
- package/server/strategist/index.js +758 -757
- package/server/strategist/tools.js +707 -675
package/server/model/dataset.js
CHANGED
|
@@ -19,10 +19,10 @@ export const BAR_MS = BAR_INTERVAL * 60000;
|
|
|
19
19
|
// горизонт в часах → число свечей (минимум одна свеча)
|
|
20
20
|
export const barsFromHours = (h) => Math.max(1, Math.round(Number(h) * (60 / BAR_INTERVAL)));
|
|
21
21
|
|
|
22
|
-
function cacheKey(interval, fromTs, tillTs, useMacro, useDividends) {
|
|
22
|
+
function cacheKey(interval, fromTs, tillTs, useMacro, useDividends, localOnly = false) {
|
|
23
23
|
const day = Math.floor(fromTs / DAY);
|
|
24
|
-
const
|
|
25
|
-
return JSON.stringify([interval, day,
|
|
24
|
+
const slot = Math.floor(tillTs / BAR_MS);
|
|
25
|
+
return JSON.stringify([interval, day, slot, useMacro ? 1 : 0, useDividends ? (process.env.DIVIDENDS_MODE || 1) : 0, localOnly ? 1 : 0]);
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
async function pool(items, limit, fn) {
|
|
@@ -219,14 +219,13 @@ export async function loadAlignedOpen(ds, symbol, { fromTs, tillTs, signal } = {
|
|
|
219
219
|
// цены с переносом последнего значения, обороты, доходности, рынок (IMOEX).
|
|
220
220
|
// Цены акций скорректированы на дивиденды (полная доходность; useDividends=false — без этого), макро — только при useMacro.
|
|
221
221
|
export async function loadDataset({ interval = BAR_INTERVAL, fromTs, tillTs, useMacro = false, useDividends = true, localOnly = false, onProgress = () => {}, signal }) {
|
|
222
|
-
const key = cacheKey(interval, fromTs, tillTs, useMacro, useDividends);
|
|
222
|
+
const key = cacheKey(interval, fromTs, tillTs, useMacro, useDividends, localOnly);
|
|
223
223
|
const hit = datasetCache.get(key);
|
|
224
|
-
if (hit && Date.now() - hit.at <
|
|
225
|
-
// Если в памяти уже есть более широкий датасет (
|
|
226
|
-
// который полностью покрывает запрошенный диапазон [fromTs … tillTs], возвращаем его мгновенно без пересборки!
|
|
224
|
+
if (hit && Date.now() - hit.at < 4 * 60000) return hit.ds;
|
|
225
|
+
// Если в памяти уже есть более широкий датасет (не localOnly), который полностью покрывает запрошенный диапазон [fromTs … tillTs], возвращаем его
|
|
227
226
|
const modeKey = JSON.stringify([interval, useMacro ? 1 : 0, useDividends ? (process.env.DIVIDENDS_MODE || 1) : 0]);
|
|
228
227
|
for (const v of datasetCache.values()) {
|
|
229
|
-
if (v.modeKey === modeKey && Date.now() - v.at <
|
|
228
|
+
if (v.modeKey === modeKey && (!v.localOnly || localOnly) && Date.now() - v.at < 4 * 60000 && v.fromTs <= fromTs + DAY && Math.abs(v.tillTs - tillTs) < 10 * 60000) {
|
|
230
229
|
return v.ds;
|
|
231
230
|
}
|
|
232
231
|
}
|
|
@@ -412,7 +411,7 @@ export async function loadDataset({ interval = BAR_INTERVAL, fromTs, tillTs, use
|
|
|
412
411
|
}
|
|
413
412
|
}
|
|
414
413
|
const ds = { tokens, symbols: tokens.map((t) => t.symbol), timeline, hourMsk, dowMsk, T, index, mret, mclose: mk.close, mopen: mk.open, macro, barsPerDay: days ? Math.round(T / days) : 54 };
|
|
415
|
-
datasetCache.set(key, { ds, at: Date.now(), modeKey, fromTs, tillTs });
|
|
414
|
+
datasetCache.set(key, { ds, at: Date.now(), modeKey, fromTs, tillTs, localOnly: Boolean(localOnly) });
|
|
416
415
|
if (datasetCache.size > 4) datasetCache.delete(datasetCache.keys().next().value);
|
|
417
416
|
return ds;
|
|
418
417
|
}
|
package/server/model/edge.js
CHANGED
|
@@ -1,19 +1,74 @@
|
|
|
1
|
-
// Copyright (c) 2026 Roman A. Perepelkin. All rights reserved. Proprietary software.
|
|
2
|
-
// Множители порога входа и выхода стратегии и классификация 1-го эшелона ликвидности Мосбиржи.
|
|
3
|
-
// Базовый порог = 2,5 × (комиссия + проскальзывание) × 2 стороны; множители поднимают его так,
|
|
4
|
-
// чтобы ожидаемое движение покрывало РЕАЛЬНЫЕ издержки с запасом.
|
|
5
|
-
// По фактическим сделкам счёта Т-Банка (111 сделок) и стресс-тесту:
|
|
6
|
-
// • бумаги 1-го эшелона (SBER, T, GAZP, LKOH, YDEX и др.): реальное проскальзывание ~0,01–0,03% + комиссия 0,04% → порог ×2 (от 0,50%);
|
|
7
|
-
// • бумаги 2–3 эшелона (MRKC, NKHP, AQUA и др.): широкий спред в стакане, проскальзывание до 0,10–0,25% → порог ещё в 1,35× выше (от 0,675%).
|
|
8
|
-
export const ENTRY_EDGE_MULT = 1.65;
|
|
9
|
-
export const TIER2_EDGE_MULT = 1.20;
|
|
10
|
-
|
|
11
|
-
// Голубые фишки и наиболее ликвидные акции 1-го эшелона Мосбиржи (глубокий стакан, минимальный спред):
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
'
|
|
15
|
-
'
|
|
16
|
-
'
|
|
17
|
-
]);
|
|
18
|
-
|
|
19
|
-
export
|
|
1
|
+
// Copyright (c) 2026 Roman A. Perepelkin. All rights reserved. Proprietary software.
|
|
2
|
+
// Множители порога входа и выхода стратегии и классификация 1-го эшелона ликвидности Мосбиржи.
|
|
3
|
+
// Базовый порог = 2,5 × (комиссия + проскальзывание) × 2 стороны; множители поднимают его так,
|
|
4
|
+
// чтобы ожидаемое движение покрывало РЕАЛЬНЫЕ издержки с запасом.
|
|
5
|
+
// По фактическим сделкам счёта Т-Банка (111 сделок) и стресс-тесту:
|
|
6
|
+
// • бумаги 1-го эшелона (SBER, T, GAZP, LKOH, YDEX и др.): реальное проскальзывание ~0,01–0,03% + комиссия 0,04% → порог ×2 (от 0,50%);
|
|
7
|
+
// • бумаги 2–3 эшелона (MRKC, NKHP, AQUA и др.): широкий спред в стакане, проскальзывание до 0,10–0,25% → порог ещё в 1,35× выше (от 0,675%).
|
|
8
|
+
export const ENTRY_EDGE_MULT = 1.65;
|
|
9
|
+
export const TIER2_EDGE_MULT = 1.20;
|
|
10
|
+
|
|
11
|
+
// Голубые фишки и наиболее ликвидные акции 1-го эшелона Мосбиржи (глубокий стакан, минимальный спред):
|
|
12
|
+
// высоковолатильные бумаги со спредом 2-го эшелона (SMLT, PIKK, POSI, AFKS, VKCO, CBOM, BSPB, SVCB) идут по порогу TIER2_EDGE_MULT.
|
|
13
|
+
export const TIER1_LIQUID_SYMBOLS = new Set([
|
|
14
|
+
'SBER', 'SBERP', 'LKOH', 'GAZP', 'T', 'YDEX', 'ROSN', 'NVTK', 'GMKN', 'PLZL',
|
|
15
|
+
'VTBR', 'TATN', 'TATNP', 'SNGS', 'SNGSP', 'ALRS', 'CHMF', 'NLMK', 'MAGN', 'MOEX',
|
|
16
|
+
'OZON', 'HEAD', 'PHOR', 'AFLT', 'MTSS', 'IRAO', 'TRNFP', 'RUAL', 'FLOT', 'X5',
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
export function symbolEdgeMult(symbol, { sigma = 0, avgSigma = 0, avgBarValRub = 0 } = {}) {
|
|
20
|
+
const isT1 = TIER1_LIQUID_SYMBOLS.has(symbol);
|
|
21
|
+
const base = isT1 ? 1.0 : TIER2_EDGE_MULT;
|
|
22
|
+
if (!(sigma > 0 || avgBarValRub > 0)) return base;
|
|
23
|
+
const refVal = isT1 ? 15e6 : 1.5e6;
|
|
24
|
+
const liqAdj = avgBarValRub > 0
|
|
25
|
+
? Math.max(-0.07, Math.min(0.10, -0.05 * Math.log10(Math.max(5e4, avgBarValRub) / refVal)))
|
|
26
|
+
: 0;
|
|
27
|
+
const sigRatio = (sigma > 0 && avgSigma > 0) ? (sigma / avgSigma) : 1;
|
|
28
|
+
const volAdj = Math.max(-0.05, Math.min(0.10, 0.12 * (sigRatio - 1)));
|
|
29
|
+
return Math.max(0.88, Math.min(1.45, base * (1 + liqAdj + volAdj)));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function computeTokenEdgeMults(tokens, sigma, fromIdx = 0, tillIdx = 0) {
|
|
33
|
+
const N = tokens.length;
|
|
34
|
+
let sigSum = 0, sigCnt = 0;
|
|
35
|
+
if (sigma) {
|
|
36
|
+
for (let i = 0; i < N; i++) if (sigma[i] > 0) { sigSum += sigma[i]; sigCnt++; }
|
|
37
|
+
}
|
|
38
|
+
const avgSigma = sigCnt > 0 ? sigSum / sigCnt : 0;
|
|
39
|
+
const out = new Float64Array(N);
|
|
40
|
+
for (let i = 0; i < N; i++) {
|
|
41
|
+
const tk = tokens[i];
|
|
42
|
+
const lo = Math.max(0, fromIdx);
|
|
43
|
+
const hi = tillIdx > lo ? Math.min(tk.value.length, tillIdx) : tk.value.length;
|
|
44
|
+
let vSum = 0, vCnt = 0;
|
|
45
|
+
for (let t = lo; t < hi; t++) {
|
|
46
|
+
if (tk.value[t] > 0) { vSum += tk.value[t]; vCnt++; }
|
|
47
|
+
}
|
|
48
|
+
const avgBarValRub = vCnt > 0 ? vSum / vCnt : 0;
|
|
49
|
+
out[i] = symbolEdgeMult(tk.symbol, { sigma: sigma ? sigma[i] : 0, avgSigma, avgBarValRub });
|
|
50
|
+
}
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Затухание штрафных счётчиков карантина на 30-минутном шаге (период полураспада ~15 торговых дней: 0,9985^(15×33) ≈ 0,48)
|
|
55
|
+
export const QUARANTINE_DECAY = 0.9985;
|
|
56
|
+
export const isStockQuarantined = (cnt, pnl) => (cnt >= 2 && pnl < -0.012) || pnl < -0.025;
|
|
57
|
+
|
|
58
|
+
// Граница вечерней сессии Мосбиржи (последняя 10-минутная свеча 23:40–23:50 МСК):
|
|
59
|
+
// не открываем новые внутридневные позиции, когда до конца торгов остаётся меньше горизонта H, и закрываем позиции перед ночью
|
|
60
|
+
const MSK = 3 * 3600000;
|
|
61
|
+
const DAY = 86400000;
|
|
62
|
+
export const SESSION_END_MINS_MSK = 23 * 60 + 40;
|
|
63
|
+
|
|
64
|
+
export const canEnterIntraday = (ts, horizonBars, barInterval = 10) => {
|
|
65
|
+
const minsMsk = Math.floor(((ts + MSK) % DAY) / 60000);
|
|
66
|
+
return minsMsk <= SESSION_END_MINS_MSK - horizonBars * barInterval;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export const shouldExitBeforeNight = (ts, entryTs = 0, stepBars = 3, barInterval = 10) => {
|
|
70
|
+
const minsMsk = Math.floor(((ts + MSK) % DAY) / 60000);
|
|
71
|
+
if (minsMsk >= SESSION_END_MINS_MSK - stepBars * barInterval) return true;
|
|
72
|
+
if (entryTs > 0 && Math.floor((ts + MSK) / DAY) > Math.floor((entryTs + MSK) / DAY)) return true;
|
|
73
|
+
return false;
|
|
74
|
+
};
|
package/server/model/forecast.js
CHANGED
|
@@ -5,9 +5,10 @@ import { loadDataset, barsFromHours, BAR_MS } from './dataset.js';
|
|
|
5
5
|
import { buildFold, MODELS, HEADS, KINDS, SCALES, BETAS, LIQ_MIN, FEATURE_WARMUP, explainAttention, mapSnapshot } from './models.js';
|
|
6
6
|
import { loadProfiles } from './profiles.js';
|
|
7
7
|
import { isMarketDown } from './research.js';
|
|
8
|
-
import { ENTRY_EDGE_MULT, TIER1_LIQUID_SYMBOLS, symbolEdgeMult } from './edge.js';
|
|
9
|
-
export { TIER1_LIQUID_SYMBOLS };
|
|
10
|
-
import { newsForSymbols } from '../news/index.js';
|
|
8
|
+
import { ENTRY_EDGE_MULT, TIER2_EDGE_MULT, TIER1_LIQUID_SYMBOLS, symbolEdgeMult, computeTokenEdgeMults } from './edge.js';
|
|
9
|
+
export { TIER1_LIQUID_SYMBOLS, symbolEdgeMult, computeTokenEdgeMults };
|
|
10
|
+
import { newsForSymbols, blockingNews } from '../news/index.js';
|
|
11
|
+
import { liveDividendGuard } from './dividends.js';
|
|
11
12
|
import { fetchTbankRealtimePrices } from '../brokers/index.js';
|
|
12
13
|
import { kvGet, kvSet } from '../db.js';
|
|
13
14
|
import { hub } from '../hub.js';
|
|
@@ -27,6 +28,9 @@ function buildInferenceFoldAt(ds, idx, fTrain, fitted, liveSnap = null) {
|
|
|
27
28
|
|
|
28
29
|
const z = new Float64Array(W * N);
|
|
29
30
|
const vr = new Float64Array(W * N);
|
|
31
|
+
const barTs = ds.timeline[idx] || 0;
|
|
32
|
+
const elapsedBars = liveSnap?.ts && barTs > 0 ? Math.max(1, (liveSnap.ts - barTs) / BAR_MS) : 1;
|
|
33
|
+
const liveScale = 1 / Math.sqrt(elapsedBars);
|
|
30
34
|
for (let uk = 0; uk < W; uk++) {
|
|
31
35
|
const t = lo + uk;
|
|
32
36
|
const isLast = uk === u && liveSnap?.prices?.size > 0;
|
|
@@ -40,7 +44,7 @@ function buildInferenceFoldAt(ds, idx, fTrain, fitted, liveSnap = null) {
|
|
|
40
44
|
const livePx = liveSnap.prices.get(tk.symbol);
|
|
41
45
|
if (livePx > 0 && prevPx > 0) rt = Math.log(livePx / prevPx);
|
|
42
46
|
}
|
|
43
|
-
const e = rt - beta[i] * mt;
|
|
47
|
+
const e = (rt - beta[i] * mt) * (isLast ? liveScale : 1);
|
|
44
48
|
z[uk * N + i] = Math.max(-8, Math.min(8, e / sigma[i]));
|
|
45
49
|
vr[uk * N + i] = Math.min(4, tk.valRatio[t]);
|
|
46
50
|
}
|
|
@@ -178,15 +182,18 @@ function applyLivePricesToFold(ds, f, u, fitted, liveSnap) {
|
|
|
178
182
|
const N = f.N;
|
|
179
183
|
const mPrev = ds.mclose?.[idx - 1] || 0;
|
|
180
184
|
const mLive = liveSnap.imoexPrice > 0 && mPrev > 0 ? Math.log(liveSnap.imoexPrice / mPrev) : ds.mret[idx];
|
|
185
|
+
const barTs = ds.timeline[idx] || 0;
|
|
186
|
+
const elapsedBars = liveSnap.ts && barTs > 0 ? Math.max(1, (liveSnap.ts - barTs) / BAR_MS) : 1;
|
|
187
|
+
const liveScale = 1 / Math.sqrt(elapsedBars);
|
|
181
188
|
|
|
182
|
-
// 1) пересчитываем z[u*N + i] по живой цене акции
|
|
189
|
+
// 1) пересчитываем z[u*N + i] по живой цене акции с нормировкой к масштабу одной 10-минутной свечи
|
|
183
190
|
for (let i = 0; i < N; i++) {
|
|
184
191
|
const tk = ds.tokens[i];
|
|
185
192
|
const prevPx = tk.close[idx - 1];
|
|
186
193
|
const livePx = liveSnap.prices.get(tk.symbol);
|
|
187
194
|
if (livePx > 0 && prevPx > 0) {
|
|
188
195
|
const ret = Math.log(livePx / prevPx);
|
|
189
|
-
const e = ret - f.beta[i] * mLive;
|
|
196
|
+
const e = (ret - f.beta[i] * mLive) * liveScale;
|
|
190
197
|
f.z[u * N + i] = Math.max(-8, Math.min(8, e / f.sigma[i]));
|
|
191
198
|
}
|
|
192
199
|
}
|
|
@@ -306,39 +313,51 @@ function buildPredictionRows(ds, p, idx, f, u, fitted, chosen, H, effMinEdge, au
|
|
|
306
313
|
let sInv = 0, nInv = 0;
|
|
307
314
|
for (let i = 0; i < ds.tokens.length; i++) if (f.sigma[i] > 0 && ds.tokens[i].liq[idx] >= LIQ_MIN) { sInv += 1 / f.sigma[i]; nInv++; }
|
|
308
315
|
const avgInv = nInv ? sInv / nInv : 0;
|
|
316
|
+
const trainSpan = Math.round(90 * (ds.barsPerDay || 54));
|
|
317
|
+
const edgeMults = computeTokenEdgeMults(ds.tokens, f.sigma, Math.max(0, idx - trainSpan), idx);
|
|
309
318
|
const rows = ds.tokens.map((tk, i) => {
|
|
310
319
|
const exp = preds[chosen][i] * f.sigma[i] * Math.sqrt(H);
|
|
311
320
|
const weight = avgInv > 0 && f.sigma[i] > 0 ? Math.max(0.4, Math.min(1.8, (1 / f.sigma[i]) / avgInv)) : 1;
|
|
312
321
|
const livePx = liveSnap?.prices?.get(tk.symbol) || tk.close[idx] || 0;
|
|
313
322
|
const lastMovePct = round(f.z[u * f.N + i] * f.sigma[i] * 100, 3);
|
|
314
|
-
//
|
|
315
|
-
|
|
316
|
-
const tierMult = symbolEdgeMult(tk.symbol);
|
|
323
|
+
// Индивидуальный множитель порога каждой акции по её фактическому обороту в рублях и волатильности свечи:
|
|
324
|
+
const tierMult = edgeMults[i] || symbolEdgeMult(tk.symbol);
|
|
317
325
|
const symNeedL = Math.max(needL * tierMult, 0.0030);
|
|
318
326
|
const symNeedS = Math.max(needS * tierMult, 0.0031);
|
|
319
|
-
//
|
|
320
|
-
//
|
|
321
|
-
|
|
322
|
-
const liveBuyOk = !(liveSnap
|
|
323
|
-
const liveShortOk = !(liveSnap
|
|
327
|
+
// Аварийный предохранитель экстремальных свечей (±4,5% за одну 10-минутную свечу — планка / остановка торгов / обвал):
|
|
328
|
+
// обычные рабочие импульсы 1,5–3,5% НЕ блокируются, так как именно на возврате к среднему после локального выброса модель формирует сигнал!
|
|
329
|
+
const EXTREME_BAR_MOVE_PCT = 4.5;
|
|
330
|
+
const liveBuyOk = !(liveSnap && lastMovePct < -EXTREME_BAR_MOVE_PCT);
|
|
331
|
+
const liveShortOk = !(liveSnap && lastMovePct > EXTREME_BAR_MOVE_PCT);
|
|
324
332
|
// сигналы — только по бумагам из текущего состава индекса (исторические бумаги остаются в матрице рынка как контекст)
|
|
325
333
|
const inIdx = !tk.inIndex || tk.inIndex[idx] === 1;
|
|
334
|
+
const shortAllowed = shortableMap && tk.symbol in shortableMap ? Boolean(shortableMap[tk.symbol]) : null;
|
|
326
335
|
const rawShortHit = inIdx && dir !== 'long' && tk.liq[idx] >= LIQ_MIN && exp < -symNeedS && liveShortOk;
|
|
327
|
-
const shortBlockedByBroker = Boolean(
|
|
336
|
+
const shortBlockedByBroker = Boolean(exp < 0 && shortAllowed === false);
|
|
337
|
+
const shortBlockedBySqueeze = Boolean(liveSnap && exp < 0 && lastMovePct > EXTREME_BAR_MOVE_PCT);
|
|
338
|
+
const buyBlockedByDip = Boolean(liveSnap && exp > 0 && lastMovePct < -EXTREME_BAR_MOVE_PCT);
|
|
328
339
|
const row = {
|
|
329
340
|
i, symbol: tk.symbol, name: tk.name,
|
|
341
|
+
tier: TIER1_LIQUID_SYMBOLS.has(tk.symbol) ? 1 : 2,
|
|
342
|
+
edgeMult: round(tierMult, 3),
|
|
343
|
+
sigmaPct: round(f.sigma[i] * 100, 3),
|
|
330
344
|
price: round(livePx, 4),
|
|
331
345
|
liquid: tk.liq[idx] >= LIQ_MIN,
|
|
332
346
|
expected: exp,
|
|
333
347
|
expectedPct: round(exp * 100, 3),
|
|
348
|
+
buyThresholdPct: round(symNeedL * 100, 3),
|
|
349
|
+
shortThresholdPct: round(symNeedS * 100, 3),
|
|
334
350
|
lastMovePct,
|
|
335
351
|
weight: round(weight, 3),
|
|
336
352
|
signal: inIdx && tk.liq[idx] >= LIQ_MIN && exp > symNeedL && liveBuyOk,
|
|
353
|
+
...(shortAllowed !== null ? { shortAllowed } : {}),
|
|
354
|
+
...(buyBlockedByDip ? { buyBlockedByDip: true } : {}),
|
|
337
355
|
...(inIdx ? {} : { inIndex: false }),
|
|
338
356
|
};
|
|
339
357
|
if (dir !== 'long') {
|
|
340
358
|
row.shortSignal = rawShortHit && !shortBlockedByBroker;
|
|
341
359
|
if (shortBlockedByBroker) row.shortBlockedByBroker = true;
|
|
360
|
+
if (shortBlockedBySqueeze) row.shortBlockedBySqueeze = true;
|
|
342
361
|
}
|
|
343
362
|
if (explain) {
|
|
344
363
|
const ex = explainAttention(fitted.attention, f, u, i);
|
|
@@ -350,13 +369,74 @@ function buildPredictionRows(ds, p, idx, f, u, fitted, chosen, H, effMinEdge, au
|
|
|
350
369
|
return { f, u, fitted, chosen, threshold, needL, needS, marketDown: bear, rows };
|
|
351
370
|
}
|
|
352
371
|
|
|
353
|
-
// Новости —
|
|
372
|
+
// Новости и защитные блокировки (сквиз, запрет шорта у брокера, дивидендная отсечка, новостной фильтр) — в прогнозе «сейчас»
|
|
354
373
|
function withNews(result, p) {
|
|
355
374
|
const nm = p.newsEnabled ? newsForSymbols(24) : null;
|
|
375
|
+
const nb = p.newsFilter ? blockingNews(6) : null;
|
|
376
|
+
const shortableMap = kvGet('tbankShortableMap')?.map || null;
|
|
377
|
+
const nowTs = Date.now();
|
|
378
|
+
const baseBuyThr = result.buyThresholdPct ?? result.thresholdPct ?? 0.413;
|
|
379
|
+
const baseShortThr = result.shortThresholdPct ?? result.thresholdPct ?? 0.516;
|
|
380
|
+
if (result.buyThresholdTier2Pct === undefined) result.buyThresholdTier2Pct = round(Math.max(baseBuyThr * TIER2_EDGE_MULT, 0.30), 3);
|
|
381
|
+
if (result.shortThresholdTier2Pct === undefined) result.shortThresholdTier2Pct = round(Math.max(baseShortThr * TIER2_EDGE_MULT, 0.31), 3);
|
|
356
382
|
for (const r of result.rows) {
|
|
383
|
+
const mult = symbolEdgeMult(r.symbol);
|
|
384
|
+
if (r.tier === undefined) r.tier = mult === 1 ? 1 : 2;
|
|
385
|
+
if (r.buyThresholdPct === undefined) r.buyThresholdPct = round(Math.max(baseBuyThr * mult, 0.30), 3);
|
|
386
|
+
if (r.shortThresholdPct === undefined) r.shortThresholdPct = round(Math.max(baseShortThr * mult, 0.31), 3);
|
|
357
387
|
const n = nm?.get(r.symbol);
|
|
358
388
|
if (n) r.news = n;
|
|
359
389
|
else delete r.news;
|
|
390
|
+
|
|
391
|
+
if (shortableMap && r.symbol in shortableMap) {
|
|
392
|
+
r.shortAllowed = Boolean(shortableMap[r.symbol]);
|
|
393
|
+
}
|
|
394
|
+
if (r.expectedPct < 0 && r.shortAllowed === false) {
|
|
395
|
+
r.shortBlockedByBroker = true;
|
|
396
|
+
r.shortSignal = false;
|
|
397
|
+
} else if (r.expectedPct >= 0) {
|
|
398
|
+
delete r.shortBlockedByBroker;
|
|
399
|
+
}
|
|
400
|
+
if (r.expectedPct < 0 && (r.lastMovePct ?? 0) > 4.5) {
|
|
401
|
+
r.shortBlockedBySqueeze = true;
|
|
402
|
+
r.shortSignal = false;
|
|
403
|
+
} else {
|
|
404
|
+
delete r.shortBlockedBySqueeze;
|
|
405
|
+
}
|
|
406
|
+
if (r.expectedPct > 0 && (r.lastMovePct ?? 0) < -4.5) {
|
|
407
|
+
r.buyBlockedByDip = true;
|
|
408
|
+
r.signal = false;
|
|
409
|
+
} else {
|
|
410
|
+
delete r.buyBlockedByDip;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const dg = p.modelUseDividends !== false ? liveDividendGuard(r.symbol, r.price, nowTs) : null;
|
|
414
|
+
if (r.expectedPct > 0 && dg?.blockLong) {
|
|
415
|
+
r.buyBlockedByDiv = `Отсечка ${dg.exDate} (дивиденд ${dg.yieldPct}%)`;
|
|
416
|
+
r.signal = false;
|
|
417
|
+
} else {
|
|
418
|
+
delete r.buyBlockedByDiv;
|
|
419
|
+
}
|
|
420
|
+
if (r.expectedPct < 0 && dg?.blockShort) {
|
|
421
|
+
r.shortBlockedByDiv = `Отсечка ${dg.exDate} (дивиденд ${dg.yieldPct}%)`;
|
|
422
|
+
r.shortSignal = false;
|
|
423
|
+
} else {
|
|
424
|
+
delete r.shortBlockedByDiv;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const bNews = nb?.get(r.symbol);
|
|
428
|
+
if (r.expectedPct > 0 && bNews?.bad) {
|
|
429
|
+
r.buyBlockedByNews = bNews.bad.gist;
|
|
430
|
+
r.signal = false;
|
|
431
|
+
} else {
|
|
432
|
+
delete r.buyBlockedByNews;
|
|
433
|
+
}
|
|
434
|
+
if (r.expectedPct < 0 && bNews?.good) {
|
|
435
|
+
r.shortBlockedByNews = bNews.good.gist;
|
|
436
|
+
r.shortSignal = false;
|
|
437
|
+
} else {
|
|
438
|
+
delete r.shortBlockedByNews;
|
|
439
|
+
}
|
|
360
440
|
}
|
|
361
441
|
return result;
|
|
362
442
|
}
|
|
@@ -417,6 +497,8 @@ async function tickLiveForecastState(p, now = Date.now()) {
|
|
|
417
497
|
bar: fmtLiveBarLabel(barTs, liveSnap ? liveTs : null),
|
|
418
498
|
buyThresholdPct: round(Math.max((r.needL ?? r.threshold) * 100, 0.30), 3),
|
|
419
499
|
shortThresholdPct: round(Math.max((r.needS ?? r.threshold) * 100, 0.31), 3),
|
|
500
|
+
buyThresholdTier2Pct: round(Math.max((r.needL ?? r.threshold) * TIER2_EDGE_MULT * 100, 0.30), 3),
|
|
501
|
+
shortThresholdTier2Pct: round(Math.max((r.needS ?? r.threshold) * TIER2_EDGE_MULT * 100, 0.31), 3),
|
|
420
502
|
marketDown: r.marketDown,
|
|
421
503
|
rows: sortedRows,
|
|
422
504
|
};
|
|
@@ -444,7 +526,7 @@ export async function forecastNow(input, { force = false, onProgress } = {}) {
|
|
|
444
526
|
// ВСЕГДА выполняем быстрый живой пересчёт по секундным котировкам Т-Банка/Мосбиржи (~80 мс, никогда не блокируя UI),
|
|
445
527
|
// а если с момента последнего обновления 10-минутных свечей прошло больше 10 минут — запускаем догрузку свечей параллельно в фоне!
|
|
446
528
|
if (!force && baseState && baseState.key === key) {
|
|
447
|
-
if (now - baseState.dsLoadedAt >=
|
|
529
|
+
if (now - baseState.dsLoadedAt >= 4 * 60000 && !inflight.has(key)) {
|
|
448
530
|
setImmediate(() => {
|
|
449
531
|
refreshDatasetStateInBackground(p, key).catch(() => {});
|
|
450
532
|
});
|
|
@@ -469,15 +551,26 @@ export async function forecastNow(input, { force = false, onProgress } = {}) {
|
|
|
469
551
|
}
|
|
470
552
|
const liveSnap = await fetchLiveMoexSnapshot().catch(() => null);
|
|
471
553
|
const liveTs = liveSnap?.ts || now;
|
|
554
|
+
const baseBuyThr = saved.result.buyThresholdPct ?? saved.result.thresholdPct ?? 0.413;
|
|
555
|
+
const baseShortThr = saved.result.shortThresholdPct ?? saved.result.thresholdPct ?? 0.516;
|
|
472
556
|
const rows = (saved.result.rows || []).map((r) => {
|
|
473
557
|
const px = liveSnap?.prices?.get(r.symbol);
|
|
474
|
-
|
|
558
|
+
const mult = symbolEdgeMult(r.symbol);
|
|
559
|
+
return {
|
|
560
|
+
...r,
|
|
561
|
+
...(px > 0 ? { price: round(px, 4) } : {}),
|
|
562
|
+
tier: r.tier ?? (mult === 1 ? 1 : 2),
|
|
563
|
+
buyThresholdPct: r.buyThresholdPct ?? round(Math.max(baseBuyThr * mult, 0.30), 3),
|
|
564
|
+
shortThresholdPct: r.shortThresholdPct ?? round(Math.max(baseShortThr * mult, 0.31), 3),
|
|
565
|
+
};
|
|
475
566
|
});
|
|
476
567
|
const updated = {
|
|
477
568
|
...saved.result,
|
|
478
569
|
at: now,
|
|
479
570
|
liveTs,
|
|
480
571
|
bar: fmtLiveBarLabel(saved.result.barTs || saved.result.at, liveSnap ? liveTs : null),
|
|
572
|
+
buyThresholdTier2Pct: saved.result.buyThresholdTier2Pct ?? round(Math.max(baseBuyThr * TIER2_EDGE_MULT, 0.30), 3),
|
|
573
|
+
shortThresholdTier2Pct: saved.result.shortThresholdTier2Pct ?? round(Math.max(baseShortThr * TIER2_EDGE_MULT, 0.31), 3),
|
|
481
574
|
rows,
|
|
482
575
|
};
|
|
483
576
|
return withNews(updated, p);
|
|
@@ -496,8 +589,10 @@ function refreshDatasetStateInBackground(p, key, { force = false, onProgress } =
|
|
|
496
589
|
const now = Date.now();
|
|
497
590
|
const task = (async () => {
|
|
498
591
|
hub.emit({ type: 'trading:pulse', kind: 'train', ts: now, text: 'Обновление котировок и расчёт прогноза…' });
|
|
499
|
-
|
|
500
|
-
|
|
592
|
+
// Всегда держим полный горизонт окна обучения (например, 160 дн. при modelTrainDays=90):
|
|
593
|
+
// чтение из локальной SQLite занимает ~0,3 с, гарантируя неизменность списка бумаг N (попадание в trainedModelCache за 1 мс без переобучения),
|
|
594
|
+
// прогретый суточный профиль объёма valRatio и корректный 10-дневный фильтр тренда isMarketDown!
|
|
595
|
+
const windowDays = Math.ceil(p.modelTrainDays * 1.5 + 25);
|
|
501
596
|
// При первом холодном прогреве после перезапуска сервера (!baseState && !force) сначала читаем 100% локально из SQLite (за ~1-2 сек без похода в сеть по 100 акциям),
|
|
502
597
|
// а сетевую догрузку свежих свечей запускаем уже после того, как baseState готов в RAM!
|
|
503
598
|
const coldLocalFirst = !baseState && !force;
|
|
@@ -523,6 +618,8 @@ function refreshDatasetStateInBackground(p, key, { force = false, onProgress } =
|
|
|
523
618
|
horizon: effHorizon, direction: p.modelDirection, model: r.chosen, thresholdPct: round(r.threshold * 100, 3),
|
|
524
619
|
buyThresholdPct: round(Math.max((r.needL ?? r.threshold) * 100, 0.30), 3),
|
|
525
620
|
shortThresholdPct: round(Math.max((r.needS ?? r.threshold) * 100, 0.31), 3),
|
|
621
|
+
buyThresholdTier2Pct: round(Math.max((r.needL ?? r.threshold) * TIER2_EDGE_MULT * 100, 0.30), 3),
|
|
622
|
+
shortThresholdTier2Pct: round(Math.max((r.needS ?? r.threshold) * TIER2_EDGE_MULT * 100, 0.31), 3),
|
|
526
623
|
marketDown: r.marketDown,
|
|
527
624
|
rows: sortedRows,
|
|
528
625
|
map: { symbols: ds.tokens.map((t) => t.symbol), names: ds.tokens.map((t) => t.name), pts: snap.pts.map(([x, y]) => [round(x, 3), round(y, 3)]), cl: snap.clusters },
|
package/server/model/live.js
CHANGED
|
@@ -5,7 +5,8 @@ import { round, DAY, MSK, fmtBarMsk } from '../util.js';
|
|
|
5
5
|
import { hub } from '../hub.js';
|
|
6
6
|
import { latestBarTs } from '../data/moex.js';
|
|
7
7
|
import { loadDataset, barsFromHours, BAR_MS, BAR_INTERVAL } from './dataset.js';
|
|
8
|
-
import { predictAt, lastClosedIndex
|
|
8
|
+
import { predictAt, lastClosedIndex } from './forecast.js';
|
|
9
|
+
import { symbolEdgeMult, QUARANTINE_DECAY, isStockQuarantined, canEnterIntraday, shouldExitBeforeNight } from './edge.js';
|
|
9
10
|
import { computeReport, downsample } from './metrics.js';
|
|
10
11
|
import { MODELS } from './models.js';
|
|
11
12
|
import { blockingNews } from '../news/index.js';
|
|
@@ -261,8 +262,7 @@ class LiveEngine {
|
|
|
261
262
|
try {
|
|
262
263
|
const p = s.params;
|
|
263
264
|
const now = Date.now();
|
|
264
|
-
const
|
|
265
|
-
const windowDays = trainedToday ? 7 : Math.ceil(p.modelTrainDays * 1.5 + 25);
|
|
265
|
+
const windowDays = Math.ceil(p.modelTrainDays * 1.5 + 25);
|
|
266
266
|
const ds = await loadDataset({ fromTs: now - windowDays * DAY, tillTs: now, useMacro: p.modelUseMacro, useDividends: p.modelUseDividends !== false });
|
|
267
267
|
s.lastSeenTs = latest;
|
|
268
268
|
changed = true;
|
|
@@ -416,25 +416,30 @@ class LiveEngine {
|
|
|
416
416
|
const exitRatio = autoAdapt ? 0.95 : Number(p.modelExitRatio ?? 0.5);
|
|
417
417
|
const mktDown = p.modelMarketFilter === 'ma' && r.marketDown;
|
|
418
418
|
const quarantined = new Set();
|
|
419
|
-
if (autoAdapt && s.trades.length >=
|
|
419
|
+
if (autoAdapt && s.trades.length >= 1) {
|
|
420
420
|
const stMap = new Map();
|
|
421
421
|
for (const t of s.trades) {
|
|
422
422
|
// затухание прошлых штрафов с возрастом сделки (~15 торговых дней полураспада)
|
|
423
423
|
const ageSteps = Math.max(0, (ts - (t.exitTs || ts)) / (stepBars * BAR_MS));
|
|
424
|
-
const wDecay = Math.pow(
|
|
424
|
+
const wDecay = Math.pow(QUARANTINE_DECAY, ageSteps);
|
|
425
425
|
const cur = stMap.get(t.symbol) || { pnl: 0, cnt: 0 };
|
|
426
426
|
cur.pnl = cur.pnl * 0.90 + (Number(t.pnlPct || 0) / 100) * wDecay;
|
|
427
427
|
cur.cnt += wDecay;
|
|
428
428
|
stMap.set(t.symbol, cur);
|
|
429
429
|
}
|
|
430
|
-
for (const [sym, st] of stMap) if (st.cnt
|
|
430
|
+
for (const [sym, st] of stMap) if (isStockQuarantined(st.cnt, st.pnl)) quarantined.add(sym);
|
|
431
431
|
}
|
|
432
432
|
for (const [sym, h] of s.held) {
|
|
433
|
+
if (autoAdapt && shouldExitBeforeNight(ts, h.entryTs, stepBars, BAR_INTERVAL)) {
|
|
434
|
+
closePos(sym, 'Закрытие перед ночным клирингом');
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
433
437
|
const x = row.get(sym);
|
|
434
438
|
const heldBars = Math.round((ts - h.entryTs) / BAR_MS);
|
|
435
|
-
const req = r.threshold * (autoAdapt && heldBars <= 2 * stepBars ? 0.35 : exitRatio);
|
|
439
|
+
const req = r.threshold * (autoAdapt && heldBars <= 2 * stepBars ? 0.35 : exitRatio) * symbolEdgeMult(sym);
|
|
436
440
|
if (!(x && x.liquid && (h.side === 'short' ? x.expected < -req : x.expected > req))) closePos(sym);
|
|
437
441
|
}
|
|
442
|
+
const timeOk = !autoAdapt || canEnterIntraday(ts, H, BAR_INTERVAL);
|
|
438
443
|
const sideHeld = (side) => [...s.held].filter(([sym, h]) => h.side === side && !closing.has(sym));
|
|
439
444
|
const nb = p.newsFilter ? blockingNews(6) : null;
|
|
440
445
|
const take = (list, side, n) => {
|
|
@@ -445,13 +450,6 @@ class LiveEngine {
|
|
|
445
450
|
if (quarantined.has(x.symbol)) { step.decisions.push({ action: 'skip', symbol: x.symbol, text: 'Пропущена: в карантине после серии убыточных сделок' }); continue; }
|
|
446
451
|
const b = nb?.get(x.symbol)?.[side === 'buy' ? 'bad' : 'good'];
|
|
447
452
|
if (b) { step.decisions.push({ action: 'skip', symbol: x.symbol, text: `Пропущена: ${side === 'buy' ? 'плохая' : 'хорошая'} новость — ${b.gist}` }); continue; }
|
|
448
|
-
if (autoK && out.length >= 1) {
|
|
449
|
-
const bestE = Math.abs(out[0].expected);
|
|
450
|
-
const curE = Math.abs(x.expected);
|
|
451
|
-
const relMin = out.length === 1 ? 0.62 : 0.78;
|
|
452
|
-
const absMin = out.length === 1 ? r.threshold * 1.15 : r.threshold * 1.45;
|
|
453
|
-
if (!(curE >= bestE * relMin && curE >= absMin)) break;
|
|
454
|
-
}
|
|
455
453
|
out.push(x);
|
|
456
454
|
}
|
|
457
455
|
return out;
|
|
@@ -459,13 +457,13 @@ class LiveEngine {
|
|
|
459
457
|
let entries;
|
|
460
458
|
if (dir === 'long') {
|
|
461
459
|
const free = K - s.held.size + s.pending.filter((o) => o.action === 'sell').length;
|
|
462
|
-
const candL = mktDown ? [] : r.rows.filter((x) => x.signal && !s.held.has(x.symbol)).sort((a, b) => b.expected - a.expected);
|
|
460
|
+
const candL = (mktDown || !timeOk) ? [] : r.rows.filter((x) => x.signal && !s.held.has(x.symbol) && !closing.has(x.symbol)).sort((a, b) => b.expected - a.expected);
|
|
463
461
|
if (mktDown && free > 0) step.decisions.push({ action: 'skip', symbol: 'IMOEX', text: 'Новые покупки пропущены: индекс Мосбиржи падает' });
|
|
464
462
|
entries = take(candL, 'buy', free).map((x) => [x, 'buy']);
|
|
465
463
|
} else {
|
|
466
|
-
const open = (x) => !s.held.has(x.symbol)
|
|
467
|
-
const candL = mktDown ? [] : r.rows.filter((x) => x.signal && open(x)).sort((a, b) => b.expected - a.expected);
|
|
468
|
-
const candS = r.rows.filter((x) => x.shortSignal && open(x)).sort((a, b) => a.expected - b.expected);
|
|
464
|
+
const open = (x) => !s.held.has(x.symbol) && !closing.has(x.symbol);
|
|
465
|
+
const candL = (mktDown || !timeOk) ? [] : r.rows.filter((x) => x.signal && open(x)).sort((a, b) => b.expected - a.expected);
|
|
466
|
+
const candS = !timeOk ? [] : r.rows.filter((x) => x.shortSignal && open(x)).sort((a, b) => a.expected - b.expected);
|
|
469
467
|
if (mktDown) step.decisions.push({ action: 'skip', symbol: 'IMOEX', text: 'Новые покупки пропущены: индекс Мосбиржи падает' });
|
|
470
468
|
const nL = K - sideHeld('long').length;
|
|
471
469
|
const nS = K - sideHeld('short').length;
|