А можно по русски?

#1
by tripolskypetr - opened

Оценка аналитиков TradingView через перебор сетки риск-менеджмента

Датасет отвечает на один вопрос: отличается ли рекомендация аналитика от
рыночного спреда — и если да, какой ценой.
Ценой здесь является риск-менеджмент
инвестора: насколько глубокий стоп он готов терпеть, на сколько дней замораживает
деньги и на каком проценте фиксирует прибыль.

Основа — посты TradingView Ideas по крипте с направлением LONG / SHORT.
Каждый пост прогоняется по 21 280 точкам сетки риск-менеджмента, и для каждой
точки считается, что случилось бы с деньгами. Один и тот же набор прогнозов даёт
от −445 % до +201 % итогового PnL в зависимости только от параметров выхода —
качество аналитика неотделимо от режима управления риском, в котором его читают.

Место в пайплайне. Это стадия отбора авторов, а не готовая стратегия. Её
результат — ранжирование: каких авторов стоит читать и в каком коридоре риска, —
которое передаётся в полноценный бэктест в
backtest-kit, чья сущность
Simulator и произвела эти артефакты. Здесь каждый автор градуируется изолированно
(один слот на автора, без общего капитала) — именно это делает числа сравнимыми
между авторами; превращение whitelist в портфель — общая экспозиция, валидация
риска по всем позициям, реальное исполнение ордеров — задача движка, а не датасета.
Референсная реализация второй стадии поставляется примером стратегии в
backtest-kit.

Что означает «хороший» и «плохой» прогноз

Единственная метрика градации — profit-before-stop, по хронологии реальной
сделки внутри окна удержания:

Исход Условие
hit (хороший прогноз) profit_lock или взвод trailing_take сработал раньше hard_stop
miss (плохой прогноз) hard_stop выбил первым, ИЛИ окно истекло без фиксации, ИЛИ свечи кончились до фиксации

Таймаут и обрыв данных — это убыток, а не исключение из статистики. Свеча,
задевшая одновременно стоп и уровень фиксации, отдаётся стопу: падающая цена для
лонга проходит нижний уровень первой.

Сетка

{
  hardStopPercent:      [1, 1.5, … 10],                  // 19 значений
  trailingTakePercent:  [0.5, 1, … 5],                   // 10 значений
  holdMinutes:          [114 суток],                  // 14 значений
  profitLockPercent:    [1, 1.5, 2, 2.5, 3, 3.5, 4, 5],  // 8 значений
}
// 19 × 10 × 14 × 8 = 21 280 точек

Сетка — это и есть инструмент измерения. Она отвечает на вопросы, которые нельзя
задать одним бэктестом:

  • Какой стоп нужен, чтобы прогнозы автора выжили. Если положительный PnL
    начинается только с hardStopPercent ≥ 7, автор входит слишком рано и рынок
    регулярно прошивает его «точку входа» на 7 %.
  • На сколько замораживаются деньги. avgHoldMinutes, p95, p99 в каждой
    точке. Если PnL появляется только при 11–14 сутках удержания, доходность
    оплачена омертвлённым капиталом.
  • Отличается ли сигнал от спреда. PnL считается за вычетом издержек
    (комиссия ×2 + слиппаж на обе ноги). Точки, где результат тонет в издержках, —
    это прогнозы на уровне шума.

Структура

content/<month>/
  assets/tv-ideas.normalize.jsonl   # вход: посты TradingView
  index.<symbol>.mjs                # прогон одного символа
  data/<SYMBOL>/
    result.json                     # сводка по символу
    result_reports.jsonl            # 21 280 точек × метрики + сделки
    result_best.jsonl               # победители по 4 критериям
    result_tracks.jsonl             # (правило × автор): hitRate

67 месяцев (jan_2021jul_2026), 11 символов, 2 503 файла, 63 GB.

Символ Месяцев Символ Месяцев
BTCUSDT 67 ZECUSDT 30
ETHUSDT 66 POLUSDT 16
DOGEUSDT 66 PENGUUSDT 16
SOLUSDT 59 HYPEUSDT 12
TRXUSDT 42 PUMPUSDT 3
NEARUSDT 37

result_reports.jsonl — ядро датасета

Одна строка на точку сетки (~2 ГБ на символ-месяц).

{
  "point": {"hardStopPercent": 7.5, "trailingTakePercent": 1.5,
            "holdMinutes": 15840, "profitLockPercent": 2},
  "skippedBusy": 71,
  "totalPnlPercent": 146.16, "avgPnlPercent": 0.40, "winRate": 0.70,
  "profitFactor": 1.58, "maxSeriesDrawdownPercent": 87.62,
  "calmarRatio": 24.35, "recoveryFactor": 1.67,
  "avgHoldMinutes": 4620.18, "p95HoldMinutes": 15840, "p99HoldMinutes": 15840,
  "sharpe": 1.86, "sortino": 3.46,
  "exitReasons": {"hard_stop": 14, "trailing_take": 69, "profit_lock": 228,
                  "time_expired": 37, "data_truncated": 16},
  "tradesList": [ /* ideaId, author, direction, exitReason, pnlPercent, … */ ]
}

tradesList даёт атрибуцию до конкретного поста: кто написал, когда вошли,
почему вышли, сколько потеряли или заработали.

result_tracks.jsonl — рейтинг авторов

Одна строка на (правило × автор), где правило — те же четыре уровня точки.
Ровно 21 280 × число_авторов строк (на jul_2026/BTCUSDT — 5 000 800).

{"holdMinutes": 1440, "profitLockPercent": 1, "hardStopPercent": 1,
 "trailingTakePercent": 0.5, "author": "BitCoinGuide",
 "ideas": 8, "hits": 6, "hitRate": 0.75}

Это сырьё без порогов и без бан-листа: движок торгует всех авторов и только
сообщает трек. Кого считать шумом — решает потребитель.

result_best.jsonl

Победители по четырём критериям: sharpe, sortino, pnl, recovery. Разные
критерии дают разные точки — оптимум по Sharpe и по PnL это не одно и то же.

Что показывают данные

На jul_2026/BTCUSDT (739 постов → 435 направленных после дедупликации):

точек сетки:            21 280
убыточных точек:        13 398 (63 %)
sharpe:                 −6.19 … +1.86
totalPnl:               −445 % … +201 %
winRate:                0.12 … 0.89

Причины выхода по всей сетке:

Причина Доля
profit_lock 37.2 %
trailing_take 22.0 %
time_expired 20.7 %
hard_stop 18.1 %
data_truncated 1.9 %

63 % конфигураций убыточны на одном и том же наборе прогнозов. Худшая точка
(стоп 1 %, трейлинг 0.5 %, лок 1 %, 2 суток) даёт −166 % и Sharpe −6.19; лучшая
(стоп 7.5 %, трейлинг 1.5 %, лок 2 %, 11 суток) — +146 % и Sharpe +1.86. Это и
есть измерение: аналитик сам по себе не «прибыльный» и не «убыточный» — он
прибылен в конкретном коридоре риска, и датасет показывает, в каком.

Зависимость от окна удержания на том же символе:

Удержание skippedBusy (avg) hitRate
1 сутки 16.1 0.343
7 суток 59.8 0.470
14 суток 70.2 0.464

hitRate выходит на плато к 7 суткам. Дальнейшее удержание прогноз не улучшает —
только замораживает деньги.

Методика прогона

  1. Фильтр и дедупликация. Идеи отбираются по символу, NEUTRAL
    отбрасываются, затем анти-флуд: один пост на автор + направление за 8 часов.
    Повтор мнения — не новое свидетельство, он выбрасывается целиком и не
    раздувает трек автора.
    Пример: 1 077 идей в файле → 739 по BTCUSDT → 449 направленных → 435.
  2. Профиль идеи. Один асинхронный проход по минутным свечам вперёд от минуты
    после публикации, на горизонт максимальной ступени сетки (14 суток).
    Считаются MFE / MAE, глубина «встряски китом», медианный ход. Свечи не
    перечитываются
    на каждую точку — исходы всех 21 280 точек выводятся из
    профиля арифметически.
  3. Слот на автора. У каждого автора свой единственный слот: пока его позиция
    открыта, его новые посты поглощаются (skippedBusy, absorbedIdeas). Авторы
    между собой не сталкиваются — чужая позиция слот не занимает. Слот держится
    до фактического выхода сделки, а не весь holdMinutes: эта ось — только
    верхняя граница, а hard_stop, profit_lock или trailing_take освобождают
    слот раньше. Поэтому skippedBusy зависит от всех четырёх уровней точки
    одновременно, а не от holdMinutes сам по себе — на jul_2026/BTCUSDT ступень
    20160 минут (стоп 4 %) поглощает 43 идеи при максимальном фактическом
    удержании 13 298 минут, а ступень 15840 минут (стоп 7.5 %) — 71.
  4. Контракты честности. Вход по open следующей минуты; выходы по теням
    свечей (high / low), никогда по close; при неоднозначной свече побеждает
    стоп; трейлинг и лок взводятся только от пиков предыдущих свечей;
    комиссия и слиппаж — на обе ноги.
  5. Инварианты. Каждая точка проверяется: PnL не ниже пола хардстопа,
    trailing_take не может зафиксировать убыток, profit_lock не может
    исполниться ниже своего уровня, выход не раньше входа. Нарушение — исключение,
    а не тихая порча данных.

Sharpe и Sortino — time-based: считаются по суточным приращениям equity на
окне, общем для всех точек сетки, и дни простоя входят в расчёт. Поэтому один и
тот же PnL, собранный редкими крупными выходами, даёт худший коэффициент, чем тот
же PnL частыми короткими сделками — замороженный капитал наказывается.

Ограничения

Это существенно — читайте до использования.

  • Трек автора — сводка за весь месяц, а не point-in-time сигнал. Каждая
    отдельная сделка считается строго вперёд: профиль строится от минуты после
    публикации, hit определяется по хронологии от входа. Ничто в
    result_reports.jsonl не заглядывает в своё будущее. Но result_tracks.jsonl
    агрегирует hitRate автора по всем его идеям месяца сразу, включая
    опубликованные позже. Если применить этот hitRate как фильтр входа к сделкам
    того же месяца, вы внесёте lookahead, которого в данных нет. Движок намеренно
    отдаёт сырой трек и не применяет бан-лист — торгуются все авторы (364 сделки +
    71 skippedBusy = все 435 направленных идей, 235 из 235 авторов). Дисциплина
    скользящего окна — задача потребителя.
  • Последние ступени сетки смещены. Профиль требует 14 суток свечей вперёд; у
    края истории данных не хватает. На jul_2026/BTCUSDT truncatedCount = 199 из
    435 (46 %), а сумма наблюдений падает на ступенях 12–14 суток (80 040 →
    76 560). Падение hitRate на 14 сутках — это край данных, а не ухудшение
    прогнозов. Не сравнивайте ступень 14 суток с короткими напрямую.
  • Месяц ограничивает идеи, а не свечи — поэтому соседние месяцы пересекаются.
    Каждая идея получает полный горизонт вперёд независимо от границ окна: пост от
    30-го числа считается на свечах уже следующего месяца и всё равно записывается в
    тот месяц, где открылся. На jun_2026/BTCUSDT в победившей точке 106 из 253
    сделок (42 %) выходят в июле, последняя — 7 июля при входе 30 июня 18:40.
    Обрезков на границе месяца нет — но прогоны при этом не являются
    непересекающимися периодами. Не суммируйте месячный PnL как независимые
    интервалы: первые ~14 дней каждого месяца покрыты дважды — открытыми позициями
    предыдущего месяца и его собственными идеями. Окно суточных корзин для
    Sharpe/Sortino тоже выходит за конец месяца (тянется до последнего
    outcomeKnownAt).
  • Infinitynull в JSON. sortino, profitFactor, calmarRatio и
    recoveryFactor бесконечны на сериях без убытков, а JSON.stringify пишет
    null. Читайте это как «нет знаменателя», а не как пропуск.
  • hitRate требует фильтра по объёму выборки. Значения 0.00 и 1.00 в
    tracks — как правило авторы с одной-двумя идеями. Без порога по ideas
    рейтинг бессмыслен.
  • Слот на автора — инструмент градации, а не модель портфеля. Каждый автор
    симулируется изолированно с единственным слотом, поэтому читаете вы «торговлю по
    сигналам одного гуру», а не реальную книгу позиций. Живой инвестор держит позиции
    сразу от нескольких авторов, и датасет намеренно этого не моделирует: авторы не
    взаимодействуют, общего капитала нет, глобального лимита экспозиции нет,
    неттинга между авторами нет. Изоляция — это то, что делает авторские числа
    сравнимыми: как только авторы разделили бы общий пул, hitRate автора начал бы
    зависеть от того, кто ещё случайно постил на той же неделе. Построение портфеля —
    следующая стадия, не эта (см. выше).
  • Покрытие символов неравномерно (от 67 месяцев у BTCUSDT до 3 у PUMPUSDT).
    Агрегация по всем символам без веса даст перекос в BTC.
  • Симулятор выбирает кандидатов, а не заменяет движок. Найденные по сетке
    параметры обязаны проверяться реальным бэктестом.

Использование

from datasets import load_dataset

# сетка риск-менеджмента (по умолчанию)
reports = load_dataset("tripolskypetr/trading-entries", "reports", split="train")

# рейтинг авторов
tracks = load_dataset("tripolskypetr/trading-entries", "tracks", split="train")

# исходные посты
ideas = load_dataset("tripolskypetr/trading-entries", "ideas", split="train")

result_reports.jsonl — около 2 ГБ на символ-месяц из-за tradesList. Для
анализа самой сетки поле лучше отбросить потоком:

jq -c 'del(.tradesList)' result_reports.jsonl > grid.jsonl

Воспроизведение прогона — backtest-kit + ccxt, точка входа
content/<month>/index.<symbol>.mjs.

Walk-forward: зафиксировать победителя месяца и прогнать на следующем

В ограничениях сказано, что hitRate автора нельзя применять внутри того же
месяца, на котором он измерен. Вот как этого избежать: берём точку сетки и автора
из месяца N, замораживаем сетку в эту единственную точку и подаём идеи месяца
N+1. Поскольку gridAxes мерджится по осям, а список из одного значения
фиксирует ось
, override из четырёх одиночных значений сворачивает перебор
21 280 точек в одну оценку вне выборки.

import { addExchangeSchema, addSimulatorSchema, Simulator } from "backtest-kit";
import { readFileSync } from "fs";
import { singleshot } from "functools-kit";
import ccxt from "ccxt";

const SYMBOL = "BTCUSDT";

// ── ТРЕНИРОВКА (jun_2026): победитель по sharpe + автор для теста ──────────
// взято из content/jun_2026/data/BTCUSDT/result_best.jsonl
const TRAINED_POINT = {
  hardStopPercent: 8.5,
  trailingTakePercent: 2,
  holdMinutes: 20160,     // 14 суток
  profitLockPercent: 5,
};
// из content/jun_2026/data/BTCUSDT/result_tracks.jsonl в той же точке
const AUTHOR = "TradingShot";   // тренировка: ideas 15, hits 14, hitRate 0.93

const getExchange = singleshot(async () => {
  const exchange = new ccxt.binance({
    options: { defaultType: "spot", adjustForTimeDifference: true },
    enableRateLimit: true,
    timeout: 15000,
  });
  await exchange.loadMarkets();
  return exchange;
});

addExchangeSchema({
  exchangeName: "ccxt_cached",
  getCandles: async (symbol, interval, since, limit) => {
    const exchange = await getExchange();
    const candles = await exchange.fetchOHLCV(symbol, interval, since.getTime(), limit);
    return candles.map(([timestamp, open, high, low, close, volume]) => ({
      timestamp, open, high, low, close, volume,
    }));
  },
});

// Заморозка каждой оси в одно значение превращает перебор в одну точку:
// правило торговли зафиксировано ТРЕНИРОВОЧНЫМ месяцем и переподогнать его нельзя.
addSimulatorSchema({
  simulatorName: "walk_forward",
  exchangeName: "ccxt_cached",
  gridAxes: {
    hardStopPercent:     [TRAINED_POINT.hardStopPercent],
    trailingTakePercent: [TRAINED_POINT.trailingTakePercent],
    holdMinutes:         [TRAINED_POINT.holdMinutes],
    profitLockPercent:   [TRAINED_POINT.profitLockPercent],
  },
});

// ── ТЕСТ (jul_2026): идеи СЛЕДУЮЩЕГО месяца, тренировке неизвестные ───────
const ideas = readFileSync("./content/jul_2026/assets/tv-ideas.normalize.jsonl", "utf-8")
  .split("\n")
  .filter(Boolean)
  .map((line) => JSON.parse(line))
  // подмена выборки: оставляем только автора, отобранного на тренировке
  .filter((idea) => idea.author === AUTHOR);

const result = await Simulator.run({
  symbol: SYMBOL,
  simulatorName: "walk_forward",
  ideas,
});

// в сетке ровно одна точка -> ровно один отчёт
const [report] = result.reports.reports;
const [track] = result.reports.tracks;

console.log("вне выборки:", {
  author: AUTHOR,
  point: report.point,
  hitRate: track.hitRate,          // сравнить с тренировочным hitRate
  ideas: track.ideas,
  totalPnlPercent: report.totalPnlPercent,
  winRate: report.winRate,
  exitReasons: report.exitReasons,
});

Чтобы получить те же числа ничего не запуская — сравнение уже лежит в датасете,
достаточно прочитать одну и ту же точку из result_tracks.jsonl обоих месяцев:

POINT='.hardStopPercent==8.5 and .trailingTakePercent==2
       and .holdMinutes==20160 and .profitLockPercent==5'
for M in jun_2026 jul_2026; do
  echo -n "$M: "
  jq -c "select($POINT) | select(.author==\"TradingShot\")" \
    content/$M/data/BTCUSDT/result_tracks.jsonl
done

Что эта точка показывает для победителя jun_2026 — и почему ограничение важно:

Автор Тренировка jun_2026 Тест jul_2026
TradingShot 14/15 = 0.93 2/8 = 0.25 развалился вне выборки
BitCoinGuide 8/11 = 0.73 8/8 = 1.00 держится
MasterAnanda 10/17 = 0.59 7/7 = 1.00 держится
ExpertTraderASK 10/13 = 0.77 3/7 = 0.43 деградирует

Лучший автор внутри выборки развалился сильнее всех. Отбор авторов по hitRate,
измеренному на том же месяце, выбрал бы TradingShot — это ровно тот lookahead,
который датасет намеренно не встраивает.

Исходник симулятора для постановки задачи ИИ агенту

import { getErrorMessage } from "functools-kit";
import { Exchange } from "../classes/Exchange";
import { ICandleData } from "../interfaces/Exchange.interface";
import {
  ISimulatorTrack,
  ISimulatorBest,
  ISimulatorIdea,
  ISimulatorIdeaProfile,
  ISimulatorMetricReport,
  ISimulator,
  ISimulatorGridAxes,
  ISimulatorGridPoint,
  ISimulatorParams,
  ISimulatorPointReport,
  ISimulatorResult,
  ISimulatorTrade,
  ISimulatorGradingRule,
  SimulatorExitReason,
  SimulatorRankingCriterion,
} from "../interfaces/Simulator.interface";

import { intervalStart } from "../utils/intervalStart";

import { GLOBAL_CONFIG } from "../config/params";

const MINUTE_MS = 60 * 1_000;
const DAY_MS = 24 * 60 * MINUTE_MS;

/**
 * Forward horizon of an idea profile, minutes — the LONGEST hold of
 * the schema's grid (max of the holdMinutes axis). Not an engine
 * constant: the schema defines both what is traded and over what
 * window authors are graded — no trade can outlive the longest hold,
 * and grading the ideas further than the machinery can trade would
 * judge authors on an event nobody harvests. Every idea gets its own
 * forward horizon regardless of frame boundaries — no cutoff
 * artifacts.
 *
 * @param axes - Grid axes carrying the holdMinutes list
 * @returns Profile horizon in minutes
 */
const HORIZON_MINUTES_FN = (axes: ISimulatorGridAxes): number => {
  const horizonMinutes = Math.max(...axes.holdMinutes);
  if (!Number.isFinite(horizonMinutes) || horizonMinutes <= 0) {
    throw new Error(
      `ClientSimulator: holdMinutes axis must contain at least one ` +
        `positive value — it defines the idea profile horizon`,
    );
  }
  return horizonMinutes;
};

/**
 * Anti-flood window: an author may contribute at most one idea per
 * direction within this many minutes. A repeated post is a bump of
 * the same opinion, not new evidence — it must not inflate the
 * author track record or retrigger entries.
 */
const AUTHOR_DEDUPE_MINUTES = 8 * 60;

/**
 * Sortino of a profitable series with zero losing days is
 * mathematically infinite. Infinity is used deliberately — a finite
 * sentinel (e.g. 999) misleads because real Sortino values can
 * exceed it. Consistent with profitFactor: Infinity when no losses.
 * NB: JSON.stringify turns Infinity into null in saved artifacts.
 */
const SORTINO_NO_LOSSES = Number.POSITIVE_INFINITY;

async function* ITERATE_CANDLES_FN(
  self: ClientSimulator,
  symbol: string,
  fromTs: number,
  count: number,
): AsyncGenerator<ICandleData> {
    let emitted = 0;
    let cursor = intervalStart(fromTs, "1m");
    while (emitted < count) {
      let chunk: ICandleData[];
      try {
        chunk = await Exchange.getRawCandles(
          symbol,
          "1m",
          { exchangeName: self.params.exchangeName },
          GLOBAL_CONFIG.CC_MAX_CANDLES_PER_REQUEST,
          cursor,
          cursor + GLOBAL_CONFIG.CC_MAX_CANDLES_PER_REQUEST * MINUTE_MS,
        );
      } catch (error) {
        // контракт Exchange строг: пропуски заблокированы, адаптер
        // обязан вернуть ровно limit свечей — поэтому конец доступной
        // истории приходит сюда ИСКЛЮЧЕНИЕМ (пустой или неполный
        // чанк). Для симулятора это штатный случай: идея у края
        // данных получает обрезанный профиль (truncated), а не валит
        // весь прогон. Обрезка идёт по границе последнего полного
        // чанка; следствие — у идей, чей ПЕРВЫЙ чанк задевает край,
        // свечей не будет вовсе (null-профиль): у края истории есть
        // теневая зона глубиной в один чанк. Реальные транзиентные
        // сбои сети гасятся ретраями Exchange до этой точки.
        self.params.logger.debug("ClientSimulator candle feed exhausted", {
          symbol,
          cursor,
          error: `${getErrorMessage(error)}`,
        });
        return;
      }
      if (!chunk.length) {
        return;
      }
      for (const candle of chunk) {
        if (candle.timestamp < fromTs) {
          continue;
        }
        yield candle;
        emitted += 1;
        if (emitted >= count) {
          return;
        }
      }
      // частичный чанк = конец доступной истории: следующий запрос
      // был бы полностью за краем данных, а пустой ответ адаптера —
      // ошибка контракта Exchange (пропуски заблокированы на его
      // уровне). Останавливаемся — профиль будет помечен truncated.
      if (chunk.length < GLOBAL_CONFIG.CC_MAX_CANDLES_PER_REQUEST) {
        return;
      }
      cursor += GLOBAL_CONFIG.CC_MAX_CANDLES_PER_REQUEST * MINUTE_MS;
    }
}

/**
 * Drops flood duplicates: for every author + direction pair only the
 * first idea of each AUTHOR_DEDUPE_MINUTES window survives. A kept
 * idea opens the window; posts inside it are discarded entirely —
 * they get no profile (no track record inflation) and no entry
 * trigger.
 *
 * @param ideas - Ideas sorted by publication time ascending
 * @returns Deduplicated ideas (order preserved)
 */
const DEDUPE_IDEAS_FN = (ideas: ISimulatorIdea[]): ISimulatorIdea[] => {
  const lastKept = new Map<string, number>();
  const result: ISimulatorIdea[] = [];
  for (const idea of ideas) {
    const key = `${idea.author}:${idea.direction}`;
    const last = lastKept.get(key);
    if (
      last !== undefined &&
      idea.ts - last < AUTHOR_DEDUPE_MINUTES * MINUTE_MS
    ) {
      continue;
    }
    lastKept.set(key, idea.ts);
    result.push(idea);
  }
  return result;
};

/**
 * Builds the per-candle trajectory profile of a single idea in ONE
 * asynchronous candle pass: entry basis, MFE/MAE extremes and whale
 * shakeout depth (worst MAE before the max-MFE candle). Outcomes of
 * ANY grid point are later derived from the profile arithmetically —
 * candles are never re-iterated per grid point.
 *
 * The ban-list dependent flag (authorBanned) is filled by
 * TRAIN_AUTHOR_FILTER_FN afterwards.
 *
 * NO candles for an idea is a FATAL error, not a skip: it means the
 * exchange feed is broken (getCandles failing or empty), and a run
 * built on missing candles is garbage — it must throw loudly, never
 * silently produce a zero profile. A PARTIAL profile at the very edge
 * of history (fewer candles than the horizon, but > 0) stays legal —
 * it is marked truncated, not dropped.
 *
 * @param self - ClientSimulator instance reference
 * @param symbol - Trading pair symbol
 * @param idea - Idea to profile
 * @param horizonMinutes - Forward horizon (the grid's longest hold)
 * @returns Idea profile (never null — throws when candles are absent)
 */
const BUILD_PROFILE_FN = async (
  self: ClientSimulator,
  symbol: string,
  idea: ISimulatorIdea,
  horizonMinutes: number,
): Promise<ISimulatorIdeaProfile> => {
  const entryTimestamp = intervalStart(idea.ts, "1m") + MINUTE_MS;
  const candles: ICandleData[] = [];
  for await (const candle of ITERATE_CANDLES_FN(
    self,
    symbol,
    entryTimestamp,
    horizonMinutes,
  )) {
    candles.push(candle);
  }
  if (!candles.length) {
    throw new Error(
      `ClientSimulator ${self.params.simulatorName}: no candles for ` +
        `${symbol} idea ${idea.id} @ ${new Date(entryTimestamp).toISOString()} ` +
        `— the exchange feed returned nothing (broken getCandles or empty ` +
        `history); a run built on missing candles is garbage, aborting`,
    );
  }
  const direction = idea.direction === "LONG" ? 1 : -1;
  const entryPrice = candles[0].open;

  let maxMfePercent = 0;
  let maxMaePercent = 0;
  let minutesToMfe = 0;
  let minutesToMae = 0;
  let shakeoutMaePercent = 0;
  for (let i = 0; i < candles.length; i++) {
    const favorable = direction > 0 ? candles[i].high : candles[i].low;
    const adverse = direction > 0 ? candles[i].low : candles[i].high;
    const mfe = (direction * (favorable - entryPrice) * 100) / entryPrice;
    const mae = (direction * (adverse - entryPrice) * 100) / entryPrice;
    if (mfe > maxMfePercent) {
      maxMfePercent = mfe;
      minutesToMfe = i;
      shakeoutMaePercent = maxMaePercent;
    }
    if (mae < maxMaePercent) {
      maxMaePercent = mae;
      minutesToMae = i;
    }
  }

  // медиана подписанных ходов close-ов от входа — сырьё метрики
  // "retain": median > 0 означает "цена простояла ВЫШЕ входа не
  // меньше половины горизонта" — без окон и без уровней
  const moves = candles
    .map(({ close }) => (direction * (close - entryPrice) * 100) / entryPrice)
    .sort((a, b) => a - b);
  const half = Math.floor(moves.length / 2);
  const medianMovePercent =
    moves.length % 2 === 1 ? moves[half] : (moves[half - 1] + moves[half]) / 2;

  const lastClose = candles[candles.length - 1].close;
  return {
    idea,
    entryTimestamp,
    entryPrice,
    candles,
    hit: direction * (lastClose - entryPrice) > 0,
    outcomeKnownAt: entryTimestamp + candles.length * MINUTE_MS,
    truncated: candles.length < horizonMinutes,
    maxMfePercent,
    maxMaePercent,
    minutesToMfe,
    minutesToMae,
    shakeoutMaePercent,
    medianMovePercent,
  };
};

/**
 * Grading-rule dependent context: the trained per-author TRACKS of
 * one grading rule (hold x lock x metric). Built once per unique
 * rule of the grid. No ban set / no per-profile flags — the engine
 * trades EVERY author and only reports the raw track; who to trust
 * is userspace.
 */
interface IAuthorFilterContext {
  tracks: ISimulatorTrack[];
}

/**
 * Derives the single GRADING rule from a grid point. The rule is the
 * point's own four trading levels — hold window, lock, hard stop,
 * trailing — because an author is graded on exactly the trade the
 * point would take. No metric discrimination and no thresholds live
 * here (grading is one binary outcome; who to trust is userspace).
 *
 * @param point - Grid point carrying the rule fields
 * @returns Grading rule
 */
const AUTHOR_RULE_FN = (point: ISimulatorGridPoint): ISimulatorGradingRule => ({
  holdMinutes: point.holdMinutes,
  profitLockPercent: point.profitLockPercent,
  hardStopPercent: point.hardStopPercent,
  trailingTakePercent: point.trailingTakePercent,
});

/**
 * Author "hit" under the single PROFIT-BEFORE-STOP rule, graded by
 * the REAL-TRADE chronology inside the rule's hold window (the first
 * holdMinutes candles of the idea's trajectory). Walk the window
 * candle by candle:
 *   - a HIT is a fixation (the lock, when lock > 0, OR the trailing
 *     arm level) firing BEFORE the hard stop;
 *   - a MISS is the hard stop knocking the position out first, OR
 *     nothing fixing by the window end (a timeout is a bad outcome),
 *     OR the candle data running out before any fixation (window is
 *     capped at candles.length, so a short profile that never fixes
 *     falls through to the miss return — running out of candles is a
 *     loss, same as a timeout).
 * A candle touching both the stop and a fixation goes to the stop
 * (the falling price crosses the lower level first for a long),
 * exactly as SIMULATE_TRADE_FN resolves it — the grade matches what
 * the trade would actually do.
 *
 * lock = 0 is valid: the lock level then equals entry and is never
 * counted as a fixation on its own — the hit is the trailing arm
 * alone racing the hard stop.
 *
 * @param profile - Idea profile
 * @param rule - Grading rule (see AUTHOR_RULE_FN)
 * @returns Whether the idea counts as the author's hit
 */
const AUTHOR_HIT_FN = (
  profile: ISimulatorIdeaProfile,
  rule: ISimulatorGradingRule,
): boolean => {
  const { candles, entryPrice } = profile;
  const direction = profile.idea.direction === "LONG" ? 1 : -1;
  const window = Math.min(rule.holdMinutes, candles.length);
  // lock = 0 => замок отключён (уровень равен entry, не считаем его
  // фиксацией); фиксация тогда — только взвод трейлинга vs стоп
  const lockEnabled = rule.profitLockPercent > 0;
  const lockLevel =
    entryPrice * (1 + (direction * rule.profitLockPercent) / 100);
  const stopLevel =
    entryPrice * (1 - (direction * rule.hardStopPercent) / 100);
  const trailRatio = rule.trailingTakePercent / 100;
  const armLevel = entryPrice / (1 - direction * trailRatio);
  for (let i = 0; i < window; i++) {
    const favorable = direction > 0 ? candles[i].high : candles[i].low;
    const adverse = direction > 0 ? candles[i].low : candles[i].high;
    const stopHit = direction > 0 ? adverse <= stopLevel : adverse >= stopLevel;
    if (stopHit) {
      return false; // хардстоп выбил раньше фиксации
    }
    const lockHit =
      lockEnabled &&
      (direction > 0 ? favorable >= lockLevel : favorable <= lockLevel);
    const trailHit = direction > 0 ? favorable >= armLevel : favorable <= armLevel;
    if (lockHit || trailHit) {
      return true; // фиксация раньше стопа
    }
  }
  return false; // до конца окна ни фиксации, ни стопа (таймаут = miss)
};

/**
 * Trains the raw per-author TRACK on the whole simulated range for
 * ONE grading rule (lookahead inside train is deliberate — honesty
 * is a userspace walk-forward concern, not the engine's). No ban:
 * every author gets a track, the engine grades and reports, userspace
 * decides who to trust. EVERY idea counts: a HIT is a fixation firing
 * before the hard stop inside the observed window; a MISS is the hard
 * stop firing first, the hold window expiring, OR the candle data
 * running out before any fixation — running out of candles and the
 * hold timing out are both losses, not exclusions (a fixation already
 * seen in the observed portion still counts as a hit).
 *
 * @param profiles - Profiles of all directional ideas
 * @param rule - Grading rule (hold window + lock + stop + trailing)
 * @returns Filter context with the rule's tracks (sorted by ideas)
 */
const TRAIN_AUTHOR_FILTER_FN = (
  profiles: ISimulatorIdeaProfile[],
  rule: ISimulatorGradingRule,
): IAuthorFilterContext => {
  const byAuthor = new Map<string, { ideas: number; hits: number }>();
  for (const profile of profiles) {
    const stat = byAuthor.get(profile.idea.author) ?? { ideas: 0, hits: 0 };
    stat.ideas += 1;
    if (AUTHOR_HIT_FN(profile, rule)) {
      stat.hits += 1;
    }
    byAuthor.set(profile.idea.author, stat);
  }
  // lock и stop теперь всегда часть идентичности правила (единственная
  // метрика profit-before-stop зависит от обоих) — кладём как есть
  const tracks: ISimulatorTrack[] = [...byAuthor].map(([author, stat]) => ({
    holdMinutes: rule.holdMinutes,
    profitLockPercent: rule.profitLockPercent,
    hardStopPercent: rule.hardStopPercent,
    trailingTakePercent: rule.trailingTakePercent,
    author,
    ideas: stat.ideas,
    hits: stat.hits,
    hitRate: stat.ideas ? stat.hits / stat.ideas : 0,
  }));
  return { tracks: tracks.sort((a, b) => b.ideas - a.ideas) };
};

/**
 * Simulates one trade: an idea profile against a grid point.
 *
 * Honesty contracts (violating any produces garbage):
 * - entry at the open of the minute AFTER publication, slippage in
 *   the fill price against the position;
 * - exits are checked against candle wicks (high/low), never close;
 * - trailing take arms from the peak of PREVIOUS candles only (the
 *   current candle peak updates after the checks) and only when the
 *   locked level is not worse than the entry;
 * - profit lock arms from previous-candle peaks the same way: once
 *   price has touched +lock% from entry, a FIXED floor sits at that
 *   level and a pullback to it exits; a runner is untouched — when
 *   the peak clears the lock, the trailing floor rises above it and
 *   the pullback hits the trailing level first;
 * - stop and any profit floor reachable inside one candle -> stop
 *   wins; both floors reachable -> the HIGHER one fills (falling
 *   price crosses it first);
 * - fees are charged separately: 2 x CC_PERCENT_FEE.
 *
 * @param profile - Idea profile (candle trajectory)
 * @param point - Grid point to evaluate
 * @returns Simulated trade with net PnL
 */
const SIMULATE_TRADE_FN = (
  profile: ISimulatorIdeaProfile,
  point: ISimulatorGridPoint,
): ISimulatorTrade => {
  const direction = profile.idea.direction === "LONG" ? 1 : -1;
  const slip = GLOBAL_CONFIG.CC_PERCENT_SLIPPAGE / 100;
  const entryFill = profile.entryPrice * (1 + direction * slip);
  const stopLevel =
    entryFill * (1 - (direction * point.hardStopPercent) / 100);
  const trailRatio = point.trailingTakePercent / 100;
  /**
   * Peak at which the trailing take lock is not worse than entry:
   * long: peak*(1-r) >= entry  =>  peak >= entry/(1-r)
   * short: peak*(1+r) <= entry =>  peak <= entry/(1+r)
   */
  const armLevel = entryFill / (1 - direction * trailRatio);
  const lockLevel =
    point.profitLockPercent > 0
      ? entryFill * (1 + (direction * point.profitLockPercent) / 100)
      : null;

  let peak = entryFill;
  let exitLevel: number | null = null;
  let exitReason: SimulatorExitReason = "time_expired";
  let exitIndex = Math.min(point.holdMinutes, profile.candles.length) - 1;

  for (let i = 0; i <= exitIndex; i++) {
    const candle = profile.candles[i];
    const adverse = direction > 0 ? candle.low : candle.high;
    const stopHit =
      direction > 0 ? adverse <= stopLevel : adverse >= stopLevel;
    const trailLevel = peak * (1 - direction * trailRatio);
    const trailArmed =
      direction > 0 ? peak >= armLevel : peak <= armLevel;
    const trailHit =
      trailArmed &&
      (direction > 0 ? adverse <= trailLevel : adverse >= trailLevel);
    const lockArmed =
      lockLevel !== null &&
      (direction > 0 ? peak >= lockLevel : peak <= lockLevel);
    const lockHit =
      lockArmed &&
      (direction > 0 ? adverse <= lockLevel! : adverse >= lockLevel!);
    if (stopHit) {
      exitLevel = stopLevel;
      exitReason = "hard_stop";
      exitIndex = i;
      break;
    }
    // оба пола пробиты одной свечой: падающая цена сперва проходит
    // ВЕРХНИЙ из взведённых уровней — он и исполняется
    if (trailHit && lockHit) {
      const trailBetter =
        direction > 0 ? trailLevel >= lockLevel! : trailLevel <= lockLevel!;
      exitLevel = trailBetter ? trailLevel : lockLevel!;
      exitReason = trailBetter ? "trailing_take" : "profit_lock";
      exitIndex = i;
      break;
    }
    if (trailHit) {
      exitLevel = trailLevel;
      exitReason = "trailing_take";
      exitIndex = i;
      break;
    }
    if (lockHit) {
      exitLevel = lockLevel!;
      exitReason = "profit_lock";
      exitIndex = i;
      break;
    }
    const favorable = direction > 0 ? candle.high : candle.low;
    peak =
      direction > 0 ? Math.max(peak, favorable) : Math.min(peak, favorable);
  }

  if (exitLevel === null) {
    exitLevel = profile.candles[exitIndex].close;
    exitReason =
      profile.truncated && exitIndex === profile.candles.length - 1
        ? "data_truncated"
        : "time_expired";
  }

  const exitFill = exitLevel * (1 - direction * slip);
  const pnlPercent =
    direction * ((exitFill - entryFill) / entryFill) * 100 -
    2 * GLOBAL_CONFIG.CC_PERCENT_FEE;

  return {
    ideaId: profile.idea.id,
    symbol: profile.idea.symbol,
    author: profile.idea.author,
    direction: profile.idea.direction,
    entryTimestamp: profile.entryTimestamp,
    exitTimestamp: profile.entryTimestamp + exitIndex * MINUTE_MS,
    exitReason,
    holdMinutesActual: exitIndex + 1,
    pnlPercent,
    absorbedIdeas: [],
  };
};

/**
 * Holding time distribution: mean and tail percentiles (nearest
 * rank). Eternal holds are visible in the tail, not in the mean —
 * a couple of dead trades barely move the average but instantly
 * push p95/p99 to the hold cap.
 *
 * @param holdMinutes - Holding times of trades, minutes (any order)
 * @returns Mean, p95 and p99 of the distribution (zeros when empty)
 */
const COMPUTE_HOLD_STATS_FN = (
  holdMinutes: number[],
): {
  avgHoldMinutes: number;
  p95HoldMinutes: number;
  p99HoldMinutes: number;
} => {
  const holds = [...holdMinutes].sort((a, b) => a - b);
  const percentile = (percent: number): number =>
    holds.length
      ? holds[
          Math.min(holds.length - 1, Math.floor((percent / 100) * holds.length))
        ]
      : 0;
  return {
    avgHoldMinutes: holds.length
      ? holds.reduce((acc, value) => acc + value, 0) / holds.length
      : 0,
    p95HoldMinutes: percentile(95),
    p99HoldMinutes: percentile(99),
  };
};

/**
 * Evaluates one grid point with PER-AUTHOR slot semantics: each
 * author has his own single slot — one open position per author,
 * an idea arriving while THAT author's slot is busy is absorbed,
 * any unbanned author's idea triggers an entry in his own slot.
 * Authors never collide (the doctrine forbids interaction); within
 * one author his own frequent posts absorb each other. The trained
 * author filter is preprocessing and is always applied.
 *
 * Sharpe/Sortino are TIME-BASED: computed over daily equity
 * increments across the whole simulated range (idle days included,
 * realized PnL booked on the exit day). The bucket window is
 * identical for every grid point, so the ratios are comparable and
 * dead holding time is penalized: the same total PnL concentrated in
 * rare chunky exits yields a higher daily variance — and a lower
 * ratio — than PnL spread over frequent short trades. Capital frozen
 * in a stale position is no longer free.
 *
 * @param profiles - Profiles sorted by entry timestamp
 * @param point - Grid point to evaluate
 * @param rangeStartTs - Start of the shared daily bucket window
 * @param rangeDays - Number of daily buckets in the shared window
 * @returns Aggregated report and the trade list
 */
const EVALUATE_POINT_FN = (
  profiles: ISimulatorIdeaProfile[],
  point: ISimulatorGridPoint,
  rangeStartTs: number,
  rangeDays: number,
): { report: ISimulatorPointReport; trades: ISimulatorTrade[] } => {
  const trades: ISimulatorTrade[] = [];
  const exitReasons: Record<SimulatorExitReason, number> = {
    hard_stop: 0,
    trailing_take: 0,
    profit_lock: 0,
    time_expired: 0,
    data_truncated: 0,
  };
  let skippedBusy = 0;
  // СЛОТ НА АВТОРА: каждый автор торгует изолированно — его идею
  // может поглотить только его же открытая позиция, не чужая. Так
  // между авторами перекрытий нет (доктрина «букашки не
  // взаимодействуют»), внутри автора его частые посты поглощают друг
  // друга — это его собственное свойство. busyUntil/holdingTrade —
  // по автору
  const busyUntilByAuthor = new Map<string, number>();
  const holdingTradeByAuthor = new Map<string, ISimulatorTrade>();

  for (const profile of profiles) {
    // все авторы торгуются — банов нет; кого отсеять решает userspace
    // по сырому треку (tracks[])
    const author = profile.idea.author;
    const busyUntil = busyUntilByAuthor.get(author) ?? -Infinity;
    if (profile.entryTimestamp < busyUntil) {
      skippedBusy += 1;
      const holdingTrade = holdingTradeByAuthor.get(author);
      if (holdingTrade) {
        holdingTrade.absorbedIdeas.push({
          ideaId: profile.idea.id,
          author: profile.idea.author,
        });
      }
      continue;
    }
    const trade = SIMULATE_TRADE_FN(profile, point);
    trades.push(trade);
    exitReasons[trade.exitReason] += 1;
    busyUntilByAuthor.set(author, trade.exitTimestamp + MINUTE_MS);
    holdingTradeByAuthor.set(author, trade);
  }

  let totalPnlPercent = 0;
  let wins = 0;
  let grossProfit = 0;
  let grossLoss = 0;
  let equity = 0;
  let equityPeak = 0;
  let maxSeriesDrawdownPercent = 0;
  for (const trade of trades) {
    totalPnlPercent += trade.pnlPercent;
    if (trade.pnlPercent > 0) {
      wins += 1;
      grossProfit += trade.pnlPercent;
    } else {
      grossLoss += -trade.pnlPercent;
    }
    equity += trade.pnlPercent;
    equityPeak = Math.max(equityPeak, equity);
    maxSeriesDrawdownPercent = Math.max(
      maxSeriesDrawdownPercent,
      equityPeak - equity,
    );
  }
  // суточная сетка приращений equity, общая для всех точек:
  // pnl сделки бронируется в день выхода, дни ожидания = 0
  const daily = new Array<number>(Math.max(rangeDays, 0)).fill(0);
  for (const trade of trades) {
    const bucket = Math.min(
      daily.length - 1,
      Math.max(0, Math.floor((trade.exitTimestamp - rangeStartTs) / DAY_MS)),
    );
    if (bucket >= 0 && bucket < daily.length) {
      daily[bucket] += trade.pnlPercent;
    }
  }
  const dayCount = daily.length;
  const meanDaily = dayCount ? totalPnlPercent / dayCount : 0;
  const varianceDaily = dayCount
    ? daily.reduce((acc, value) => acc + (value - meanDaily) ** 2, 0) /
      dayCount
    : 0;
  const stdDaily = Math.sqrt(varianceDaily);
  const sharpe =
    stdDaily > 0 ? (meanDaily / stdDaily) * Math.sqrt(dayCount) : 0;
  const downsideVarianceDaily = dayCount
    ? daily.reduce((acc, value) => acc + Math.min(value, 0) ** 2, 0) /
      dayCount
    : 0;
  const downsideDevDaily = Math.sqrt(downsideVarianceDaily);
  const sortino =
    downsideDevDaily > 0
      ? (meanDaily / downsideDevDaily) * Math.sqrt(dayCount)
      : meanDaily > 0
        ? SORTINO_NO_LOSSES
        : 0;

  const holdStats = COMPUTE_HOLD_STATS_FN(
    trades.map(({ holdMinutesActual }) => holdMinutesActual),
  );

  // Calmar — годовая доходность к просадке кривой (окно корзин общее
  // для всех точек), recovery — сырой PnL к той же просадке; без
  // просадки при положительном PnL оба бесконечны (как profitFactor)
  const annualizedPnlPercent = rangeDays > 0
    ? totalPnlPercent * (365 / rangeDays)
    : 0;
  const calmarRatio =
    maxSeriesDrawdownPercent > 0
      ? annualizedPnlPercent / maxSeriesDrawdownPercent
      : totalPnlPercent > 0
        ? Number.POSITIVE_INFINITY
        : 0;
  const recoveryFactor =
    maxSeriesDrawdownPercent > 0
      ? totalPnlPercent / maxSeriesDrawdownPercent
      : totalPnlPercent > 0
        ? Number.POSITIVE_INFINITY
        : 0;

  return {
    report: {
      point,
      skippedBusy,
      totalPnlPercent,
      avgPnlPercent: trades.length ? totalPnlPercent / trades.length : 0,
      winRate: trades.length ? wins / trades.length : 0,
      profitFactor: grossLoss > 0 ? grossProfit / grossLoss : Infinity,
      maxSeriesDrawdownPercent,
      calmarRatio,
      recoveryFactor,
      avgHoldMinutes: holdStats.avgHoldMinutes,
      p95HoldMinutes: holdStats.p95HoldMinutes,
      p99HoldMinutes: holdStats.p99HoldMinutes,
      sharpe,
      sortino,
      exitReasons,
      tradesList: trades,
    },
    trades,
  };
};

/**
 * Builds the cartesian product of grid axes. The single
 * profit-before-stop metric grades every point, so no combination is
 * inert: lock = 0 is valid (fixation is then the trailing arm alone),
 * every point carries a hard stop and a trailing take. An empty grid
 * (an empty axis list) is a configuration error and throws loudly in
 * RUN_FN.
 *
 * @param axes - Value lists per axis
 * @returns All grid points
 */
const BUILD_GRID_FN = (axes: ISimulatorGridAxes): ISimulatorGridPoint[] =>
  axes.hardStopPercent.flatMap((hardStopPercent) =>
    axes.trailingTakePercent.flatMap((trailingTakePercent) =>
      axes.holdMinutes.flatMap((holdMinutes) =>
        axes.profitLockPercent.map((profitLockPercent) => ({
          hardStopPercent,
          trailingTakePercent,
          holdMinutes,
          profitLockPercent,
        })),
      ),
    ),
  );

/**
 * Trade invariants — catch arithmetic bugs before any grid analysis.
 * Throws on violation.
 *
 * @param trades - Trades of one grid point
 * @param point - The grid point (for error context)
 */
const ASSERT_TRADE_INVARIANTS_FN = (
  trades: ISimulatorTrade[],
  point: ISimulatorGridPoint,
): void => {
  const costFloor =
    2 * GLOBAL_CONFIG.CC_PERCENT_FEE +
    4 * GLOBAL_CONFIG.CC_PERCENT_SLIPPAGE +
    0.01;
  const worstAllowed = -point.hardStopPercent - costFloor;
  for (const trade of trades) {
    if (trade.pnlPercent < worstAllowed) {
      throw new Error(
        `ClientSimulator invariant: pnl ${trade.pnlPercent.toFixed(3)} below floor ` +
          `${worstAllowed.toFixed(3)} (idea ${trade.ideaId}, ${JSON.stringify(point)})`,
      );
    }
    if (
      trade.exitReason === "trailing_take" &&
      trade.pnlPercent < -costFloor
    ) {
      throw new Error(
        `ClientSimulator invariant: trailing take locked a loss ${trade.pnlPercent.toFixed(3)} ` +
          `(idea ${trade.ideaId}, ${JSON.stringify(point)})`,
      );
    }
    if (
      trade.exitReason === "profit_lock" &&
      trade.pnlPercent < point.profitLockPercent - costFloor
    ) {
      throw new Error(
        `ClientSimulator invariant: profit lock filled below its level ${trade.pnlPercent.toFixed(3)} ` +
          `(idea ${trade.ideaId}, ${JSON.stringify(point)})`,
      );
    }
    if (trade.exitTimestamp < trade.entryTimestamp) {
      throw new Error(
        `ClientSimulator invariant: exit before entry (idea ${trade.ideaId})`,
      );
    }
  }
};

/**
 * Full simulation run for a symbol: ideas -> profiles -> author
 * filter training -> grid evaluation -> four rankings.
 *
 * Every progress point the reference Sweep script printed to console
 * is emitted through ISimulatorCallbacks instead.
 *
 * @param self - ClientSimulator instance reference
 * @param symbol - Trading pair symbol
 * @param allIdeas - Ideas to simulate (other symbols are filtered out)
 * @returns Final result with reports and rankings; the author artifact lives per-winner in best[]
 */
const RUN_FN = async (
  self: ClientSimulator,
  symbol: string,
  allIdeas: ISimulatorIdea[],
): Promise<ISimulatorResult> => {
  const ideas = allIdeas
    .filter((idea) => idea.symbol === symbol)
    .sort((a, b) => a.ts - b.ts);
  const directional = DEDUPE_IDEAS_FN(
    ideas.filter(({ direction }) => direction !== "NEUTRAL"),
  );
  if (self.params.callbacks?.onIdeas) {
    self.params.callbacks?.onIdeas(symbol, ideas.length, directional.length);
  }

  const horizonMinutes = HORIZON_MINUTES_FN(self.params.gridAxes);
  const profiles: ISimulatorIdeaProfile[] = [];
  for (let index = 0; index < directional.length; index++) {
    // нет свечей у идеи -> BUILD_PROFILE_FN бросает: прогон на
    // отсутствующих свечах — мусор, падаем громко, а не молча нулями
    profiles.push(
      await BUILD_PROFILE_FN(self, symbol, directional[index], horizonMinutes),
    );
    if (self.params.callbacks?.onProgress) {
      self.params.callbacks?.onProgress(
        symbol,
        "profiles",
        index + 1,
        directional.length,
      );
    }
  }
  const truncatedCount = profiles.filter(({ truncated }) => truncated).length;
  if (self.params.callbacks?.onProfiles) {
    self.params.callbacks?.onProfiles(symbol, profiles, truncatedCount);
  }

  // трек авторов считается по разу на каждое уникальное ГРАДИРУЮЩЕЕ
  // правило: единственная метрика profit-before-stop зависит от всех
  // четырёх уровней точки, поэтому ключ — hold:lock:stop:trailing.
  // Порогов НЕТ (их вырезали — ступенька 0/1). Ключ — деталь
  // мемоизации; наружу выходит плоский tracks[]
  const filterByRule = new Map<
    string,
    { rule: ISimulatorGradingRule; filter: IAuthorFilterContext }
  >();
  const ruleKeyOf = (rule: ISimulatorGradingRule): string =>
    `${rule.holdMinutes}:${rule.profitLockPercent}:${rule.hardStopPercent}:${rule.trailingTakePercent}`;
  const trainRule = (point: ISimulatorGridPoint): void => {
    const rule = AUTHOR_RULE_FN(point);
    const key = ruleKeyOf(rule);
    if (filterByRule.has(key)) {
      return;
    }
    const entry = { rule, filter: TRAIN_AUTHOR_FILTER_FN(profiles, rule) };
    filterByRule.set(key, entry);
    if (self.params.callbacks?.onAuthorsTrained) {
      self.params.callbacks?.onAuthorsTrained(symbol, entry.filter.tracks);
    }
  };

  // общее окно суточных корзин для time-based Sharpe/Sortino:
  // от первого входа до последнего известного исхода, одинаково
  // для всех точек сетки — метрики сравнимы между точками
  const rangeStartTs = profiles.length
    ? Math.min(...profiles.map(({ entryTimestamp }) => entryTimestamp))
    : 0;
  const rangeEndTs = profiles.length
    ? Math.max(...profiles.map(({ outcomeKnownAt }) => outcomeKnownAt))
    : 0;
  const rangeDays = Math.max(1, Math.ceil((rangeEndTs - rangeStartTs) / DAY_MS));

  const points = BUILD_GRID_FN(self.params.gridAxes);
  // сетка обязана быть непустой: пустая сетка — ошибка конфигурации
  // (пустой axis), о которой нужно кричать, а не молча вернуть нули
  if (!points.length) {
    throw new Error(
      `ClientSimulator ${self.params.simulatorName}: the grid is empty — ` +
        `every gridAxes list must carry at least one value`,
    );
  }
  const reports: ISimulatorPointReport[] = [];
  const allHoldMinutes: number[] = [];
  for (let index = 0; index < points.length; index++) {
    const point = points[index];
    // трек правила этой точки — мемоизируется, эмитит onAuthorsTrained
    trainRule(point);
    const { report, trades } = EVALUATE_POINT_FN(
      profiles,
      point,
      rangeStartTs,
      rangeDays,
    );
    ASSERT_TRADE_INVARIANTS_FN(trades, point);
    reports.push(report);
    for (const trade of trades) {
      allHoldMinutes.push(trade.holdMinutesActual);
    }
    if (self.params.callbacks?.onGridPoint) {
      self.params.callbacks?.onGridPoint(symbol, report, trades);
    }
    if (self.params.callbacks?.onProgress) {
      self.params.callbacks?.onProgress(
        symbol,
        "grid",
        index + 1,
        points.length,
      );
    }
  }
  const holdStats = COMPUTE_HOLD_STATS_FN(allHoldMinutes);

  const rankings: {
    criterion: SimulatorRankingCriterion;
    value: (report: ISimulatorPointReport) => number;
  }[] = [
    { criterion: "sharpe", value: ({ sharpe }) => sharpe },
    { criterion: "sortino", value: ({ sortino }) => sortino },
    { criterion: "pnl", value: ({ totalPnlPercent }) => totalPnlPercent },
    { criterion: "recovery", value: ({ recoveryFactor }) => recoveryFactor },
  ];
  // равенство проверяется до вычитания: Infinity - Infinity = NaN
  // ломает контракт компаратора (sortino/profitFactor бесконечны
  // на сериях без убытков)
  const byRankingDesc =
    (value: (report: ISimulatorPointReport) => number) =>
    (a: ISimulatorPointReport, b: ISimulatorPointReport) => {
      const va = value(a);
      const vb = value(b);
      if (va === vb) {
        return 0;
      }
      return vb - va;
    };
  const orderValue =
    rankings.find(({ criterion }) => criterion === self.params.reportOrder)
      ?.value ?? rankings[0].value;

  // единственная корзина: все точки сетки градируются одной метрикой
  // profit-before-stop, поэтому reports/best/tracks — плоские, без
  // словаря по метрике
  const bucket: ISimulatorMetricReport = {
    reports: [...reports],
    best: [],
    tracks: [],
  };

  // рейтинги внутри корзины: победитель по каждому критерию
  for (const ranking of rankings) {
    const sorted = [...bucket.reports].sort(byRankingDesc(ranking.value));
    const winner = sorted[0] ?? null;
    // сделки победителя не дублируются — лежат на winner.tradesList;
    // трек — в bucket.tracks
    const bestEntry: ISimulatorBest = {
      criterion: ranking.criterion,
      report: winner,
    };
    bucket.best.push(bestEntry);
    if (self.params.callbacks?.onRanking) {
      self.params.callbacks?.onRanking(
        symbol,
        ranking.criterion,
        sorted,
        bestEntry,
      );
    }
  }
  // порядок точек — контракт потребителя run(): критерий задаёт схема
  // (reportOrder), компаратор — защищённый
  bucket.reports.sort(byRankingDesc(orderValue));

  // author tracks — сырьё, ОДНА строка на (правило x автор): раскладка
  // per grading rule (hold x lock x stop x trailing), дедуплицированная
  // против reports[]. Каждый трек уже самодостаточен (несёт
  // hold/lock/stop/author) — grep/jq без джойна
  for (const { filter } of filterByRule.values()) {
    bucket.tracks.push(...filter.tracks);
  }

  const result: ISimulatorResult = {
    symbol,
    ideasTotal: ideas.length,
    ideasDirectional: directional.length,
    profileCount: profiles.length,
    truncatedCount,
    avgHoldMinutes: holdStats.avgHoldMinutes,
    p95HoldMinutes: holdStats.p95HoldMinutes,
    p99HoldMinutes: holdStats.p99HoldMinutes,
    reports: bucket,
  };
  if (self.params.callbacks?.onDone) {
    self.params.callbacks?.onDone(symbol, result);
  }
  return result;
};

/**
 * Parameter sweep engine over crowd trading ideas (the "Simulator").
 *
 * Finds production strategy parameters (hard stop, trailing take,
 * hold duration, author ban rule) by simulating every idea against
 * every point of the grid — WITHOUT re-running a backtest per point.
 * Authors are graded STRICTLY in isolation — no interaction metrics
 * (consensus counting, vote weighting) exist here by design; swarm
 * ranking over long histories is userspace. The root iteration is
 * over IDEAS, not candles and not grid points:
 *
 * 1. Each idea gets ONE asynchronous forward candle pass from the
 *    minute after its publication, capped by the grid's longest
 *    hold (max of the holdMinutes axis — the schema defines the
 *    horizon, not an engine constant). The pass produces a
 *    per-candle trajectory
 *    profile (MFE/MAE extremes, whale shakeout depth). Overlapping
 *    and sparse ideas are both supported: candle chunks are fetched
 *    lazily through the Exchange (persist cache first), gaps between
 *    ideas are never requested.
 * 2. The author ban list is TRAINED on the whole range (lookahead
 *    inside train is deliberate): authors with enough ideas and a hit
 *    rate worse than a coin are excluded from entries. The list is
 *    part of the result — apply it in production as-is.
 * 3. The outcome of every grid point is derived arithmetically from
 *    the profiles with production slot semantics (one position per
 *    author, busy-slot ideas skipped). Honesty contracts: entry at
 *    next-minute open, exits by candle wicks (never close-to-close),
 *    stop wins inside an ambiguous candle, trailing arms only from
 *    previous-candle peaks, fees and slippage from GLOBAL_CONFIG on
 *    both legs.
 * 4. Grid winners are picked by four rankings (Sharpe, Sortino, PnL,
 *    total PnL) with an anti-fluke minimum-trades guard.
 *
 * Every stage emits an ISimulatorCallbacks hook; the client itself
 * is stateless between runs — each run() call is independent.
 *
 * Validation of the chosen parameters MUST be done by a real engine
 * backtest (Backtest.run): the simulator picks candidates, it does
 * not replace the engine.
 */
export class ClientSimulator implements ISimulator {
  constructor (readonly params: ISimulatorParams) { }

  /**
   * Runs the full simulation pipeline for a symbol.
   *
   * Steps and emitted callbacks:
   * 1. Filters the input array by symbol, sorts by publication time,
   *    drops NEUTRAL ideas and flood duplicates (at most one idea
   *    per author per direction per AUTHOR_DEDUPE_MINUTES)
   *    -> onIdeas(symbol, total, directional).
   * 2. Builds one trajectory profile per idea (lazy candle fetch
   *    through the Exchange schema; ideas with no candle data are
   *    dropped) -> onProfiles(symbol, profiles, truncatedCount).
   * 3. Trains the author ban list on the whole range
   *    -> onAuthorsTrained(symbol, stats, bannedIdeas).
   * 4. Evaluates the cartesian grid of params.gridAxes over the
   *    profiles, checking trade invariants on every point
   *    -> onGridPoint(symbol, report, trades) per point.
   * 5. Ranks all points by Sharpe, Sortino and total PnL
   *    -> onRanking(symbol, criterion, sorted, best) per criterion.
   * 6. Assembles the final result -> onDone(symbol, result).
   *
   * The ideas array may contain multiple symbols — foreign ones are
   * filtered out before any computation, so one shared feed can be
   * passed for every symbol.
   *
   * @param symbol - Trading pair symbol to simulate (e.g., "BTCUSDT")
   * @param ideas - Ideas feed (other symbols are filtered out)
   * @returns Final result: grid reports keyed by author metric (each
   * bucket sorted by reportOrder),
   * winners of the four rankings with their trade lists, and the
   * trained author filter artifact (stats + ban list)
   * @throws Error when a grid point produces a trade violating the
   * arithmetic invariants (PnL below the hard stop floor, trailing
   * take locking a loss, exit before entry)
   */
  public run = async (
    symbol: string,
    ideas: ISimulatorIdea[],
  ): Promise<ISimulatorResult> => {
    this.params.logger.debug("ClientSimulator run", {
      symbol,
      ideasLen: ideas.length,
    });
    return await RUN_FN(this, symbol, ideas);
  }
}

Sign up or log in to comment