diff --git a/README.md b/README.md index 9fdb3c1..7f0f54a 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ public repositories. - Getting started: https://docs.tradejs.dev/getting-started/quickstart - Installation: https://docs.tradejs.dev/getting-started/installation - First backtest: https://docs.tradejs.dev/getting-started/first-backtest +- Codex strategy skills: https://docs.tradejs.dev/guides/codex-strategy-skills - Examples: https://docs.tradejs.dev/examples - Repository ownership: https://docs.tradejs.dev/advanced/repository-ownership - Environment and secret ownership: https://docs.tradejs.dev/operations/env-reference diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 8f85aed..d0b3db6 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -21,7 +21,9 @@ npx create-tradejs This installs the packages, starts local infrastructure, creates the initial user and backtest config, and opens the Web UI. Continue with -[Run your first backtest](./first-backtest). +[Run your first backtest](./first-backtest). The generated project also includes +[focused Codex strategy skills](../guides/codex-strategy-skills) under +`.codex/skills`. ## Manual Installation diff --git a/docs/guides/codex-strategy-skills.md b/docs/guides/codex-strategy-skills.md new file mode 100644 index 0000000..8f36b10 --- /dev/null +++ b/docs/guides/codex-strategy-skills.md @@ -0,0 +1,167 @@ +--- +title: Codex strategy workflow skills +--- + +`npx create-tradejs` installs the complete checksum-managed TradeJS skill set in +the generated project's `.codex/skills` directory. Each invocation has one +workflow owner. This keeps one core experiment separate from end-to-end +improvement research, gate analysis, reporting, and production mutations. + +## Choose one workflow owner + +- Use `$strategy-improvement-research` to choose hypothesis families, manage + the bounded trial ledger, select the best candidate, and freeze the complete + core + gate handoff. +- Use `$strategy-backtest-research` to implement or execute one already + preregistered core experiment. It returns reconciled evidence and does not + choose the next candidate. +- Use `$ai-train-local-research` only after the core/export is frozen. It owns + deterministic-gate analysis and does not reopen core selection. + +The improvement workflow composes the two specialist stages. Invoking a +specialist directly does not implicitly start the full improvement lineage. + +## Supporting skills + +| Skill | Purpose | +| --- | --- | +| `$strategy-backtest-research` | Execute one scoped implementation or preregistered core-backtest experiment | +| `$ai-train-local-research` | Analyze and tune the deterministic gate for one frozen core/export | +| `$backtest-config-redis` | Read a named research grid from local Redis without promoting it | +| `$save-strategy-config-from-backtest` | Explicitly promote a research grid into the Project's Git-owned declaration | +| `$runtime-parity-mismatch-analysis` | Diagnose an existing runtime-parity mismatch artifact before considering a rerun | + +## Lifecycle skill map + +| Skill | Purpose | May change production? | +| --- | --- | --- | +| `$strategy-candidate-report` | Show the latest explicitly selected candidate, its exact config, freshness, chart, and metrics | No | +| `$strategy-candidate-compare` | Compare that candidate with the exact deployed composition on a common scope | No | +| `$strategy-improvement-plan` | Analyze source and evidence and rank causal improvement hypotheses | No | +| `$strategy-improvement-research` | Start a new bounded core + deterministic-gate research lineage and freeze the best reproducible candidate | No | +| `$strategy-period-revalidate` | Recheck production and strong prior candidates on an extended common period without retuning | No | +| `$strategy-forward-start` | Publish and start the latest eligible candidate—or an explicitly named reproducible historical candidate—at `MAX_LOSS_VALUE=1` | Yes | +| `$strategy-forward-status` | Inspect identity, parity, orders, execution, and normalized live evidence | No | +| `$strategy-risk-scale` | Change only `MAX_LOSS_VALUE` for the same deployed composition | Yes | + +`$strategy-release` is a deprecated compatibility router. It selects exactly +one focused lifecycle skill and must not recreate the former all-in-one +research, publication, deployment, and risk workflow. + +Example prompts stay short: + +```text +$strategy-candidate-report MarketFlushReversal +$strategy-improvement-research MarketFlushReversal +$strategy-forward-start MarketFlushReversal +``` + +## Installation and updates + +The canonical skill source lives in the TradeJS framework repository. Every +official TradeJS skill is included in one SHA-256 manifest; generated Projects +must not maintain independent copies. Update the complete official snapshot +only through an explicitly selected `create-tradejs` version: + +```bash +npx create-tradejs@ --update-skills . +``` + +The updater preserves unrelated custom skills and rejects changes to an +already managed file. When a release first brings an existing official skill +under bundle management, the explicit update adopts that same-named official +snapshot. + +## Research roots + +Advanced source-aware research keeps three responsibilities separate: + +- `PROJECT_CWD` owns `.env`, configuration, datasets, notes, and reports. +- `TRADEJS_SOURCE_REPOSITORY_ROOT` is the exact framework or standalone + strategy Git checkout whose build and lineage are under study. +- `TRADEJS_FRAMEWORK_REPOSITORY_ROOT` supplies the built framework research + runtime. It is required by the gate-ablation tool when the source root is a + standalone strategy; when the source is the framework, both roots may be the + same checkout. + +The ablation tool imports `strategyEntries` from the standalone strategy build, +so accepting a strategy path never silently falls back to the Project's +published package. + +## How candidates are ranked + +The research skill does not optimize only full-period profit, win rate, or a +profitable 7-day tail. It first requires causal and data validity, trace +reconciliation, and positive out-of-sample expectancy per unit of risk after +costs. It then considers probabilistic or deflated Sharpe, drawdown and tail +loss, recovery, loss streaks, losing-month streaks, walk-forward/regime +stability, concentration, cost robustness, and executable trade cadence. + +Full-period PnL and win rate remain important economic diagnostics, but neither +is sufficient alone. Short 7d/30d/180d windows describe the current regime. +Their weight depends on independent support: fewer than 20 events is +underpowered, 20–49 is diagnostic, and 50 or more is selection-grade. A sparse +tail does not impose a 7-, 30-, or 180-day waiting period before a risk-1 +prospective test. + +Every new improvement-research invocation starts a new lineage. Before testing +new hypotheses it revalidates the strongest old candidates on the new common +period. It continues past audits and failed first rounds until it freezes a +reproducible best candidate, exhausts its bounded fresh-candidate budget, or +records a hard causal blocker for every remaining family. + +## What forward start does + +`$strategy-forward-start ` is the explicit authorization boundary +for a bounded live forward test. By default, it consumes the latest +checksum-verified, forward-eligible candidate and sets `MAX_LOSS_VALUE=1`. + +- If the strategy is missing from the target deployment, the skill adds and + enables its full reviewed declaration. +- If it is running with a different package, core config, deterministic gate, + context, or direction policy, the skill performs one guarded replacement. +- If the exact risk-1 composition already runs, it makes no configuration + change and verifies the rollout idempotently. + +### Explicitly named historical candidate + +The operator may instead name one different historically promising candidate +for prospective-only learning. This does not rewrite the earlier selection or +turn contrary recent evidence into a positive historical verdict. The exact +expression, direction policy, effective config, source/data lineage, evidence +hashes, full-period metrics, and chart must remain reproducible; the maximum +covered period must have positive net PnL and profit factor above 1. + +Before rollout, Codex writes a new immutable operator-authorization artifact +that references the original selection and the contrary or underpowered +evidence. Missing hashes, non-positive maximum-period economics, or a candidate +that would require fresh tuning remain blockers. The mode changes only the +authority for a risk-1 prospective test—it does not manufacture historical +eligibility. + +When the selected candidate includes unpublished strategy source, the skill +uses the repository's configured release workflow to commit and push the +complete release range, publish the immutable package, install its exact +version and lockfile in the Project, commit and push the full Git-owned +`tradejs.config.ts`, deploy the exact Project tip, and verify +`strategyRevision` and `deploymentCompositionId`. + +The skill never invents a production target. You must already have an exact +runtime user, deployment, trading account, connector, and package/deployment +workflow. `create-tradejs` provides the skills and local project, but it does +not create registry credentials, exchange credentials, production hosting, or +an unmanaged background daemon. If authorization or a target binding is +missing, Codex stops at that boundary and gives the exact action you must +complete. + +## Scaling is a separate decision + +Use `$strategy-risk-scale ` only after reviewing prospective +evidence. It preserves the exact package, core, gate, context, universe, and +direction policy and changes only `MAX_LOSS_VALUE`, by at most one approved +step. Scaling is event-driven rather than calendar-driven: execution parity, +after-cost expectancy, normalized drawdown/tail loss, slippage, concentration, +and independent trade support matter more than “30 days have passed.” + +See [Run a Strategy in Production](../getting-started/run-strategy-in-production) +for account, immutable build, and runtime requirements. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/getting-started/installation.md b/i18n/ru/docusaurus-plugin-content-docs/current/getting-started/installation.md index 0123714..a87945d 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/getting-started/installation.md +++ b/i18n/ru/docusaurus-plugin-content-docs/current/getting-started/installation.md @@ -20,7 +20,9 @@ npx create-tradejs Команда устанавливает пакеты, запускает локальные сервисы, создаёт начального пользователя и конфигурацию бэктеста, затем открывает веб-приложение. -Продолжение: [Первый бэктест](./first-backtest). +Продолжение: [Первый бэктест](./first-backtest). Созданный проект также содержит +[узкие Codex skills для стратегий](../guides/codex-strategy-skills) в +`.codex/skills`. ## Ручная установка diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/codex-strategy-skills.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/codex-strategy-skills.md new file mode 100644 index 0000000..c01e084 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/codex-strategy-skills.md @@ -0,0 +1,169 @@ +--- +title: Codex skills для работы со стратегиями +--- + +`npx create-tradejs` устанавливает в `.codex/skills` созданного проекта полный +checksum-managed набор TradeJS skills. У каждого вызова есть один владелец +workflow. Поэтому отдельный core-эксперимент не смешивается с полным улучшением +стратегии, анализом gate, отчётностью и production-изменениями. + +## Выбор владельца workflow + +- `$strategy-improvement-research` выбирает семейства гипотез, управляет + ограниченным trial ledger, выбирает лучшего кандидата и фиксирует полный + handoff core + gate. +- `$strategy-backtest-research` реализует или запускает один заранее + зарегистрированный core-эксперимент. Он возвращает сверенное evidence и не + выбирает следующего кандидата. +- `$ai-train-local-research` используется после фиксации core/export. Он + отвечает за deterministic-gate analysis и не открывает заново core selection. + +Improvement workflow последовательно использует оба специализированных этапа. +Прямой вызов specialist skill не запускает полный improvement lineage. + +## Вспомогательные skills + +| Skill | Назначение | +| --- | --- | +| `$strategy-backtest-research` | Выполнить одну ограниченную реализацию или заранее зарегистрированный core-backtest эксперимент | +| `$ai-train-local-research` | Исследовать deterministic gate для одного зафиксированного core/export | +| `$backtest-config-redis` | Прочитать именованный исследовательский grid из локального Redis без продвижения | +| `$save-strategy-config-from-backtest` | Явно перенести исследовательский grid в Git-owned декларацию Project | +| `$runtime-parity-mismatch-analysis` | Разобрать готовый runtime-parity mismatch artifact до решения о новом replay | + +## Карта lifecycle skills + +| Skill | Назначение | Может изменить production? | +| --- | --- | --- | +| `$strategy-candidate-report` | Показать последнего явно выбранного кандидата, точный конфиг, свежесть, график и метрики | Нет | +| `$strategy-candidate-compare` | Сравнить кандидата с точной запущенной composition на общем периоде | Нет | +| `$strategy-improvement-plan` | Проанализировать source и evidence и ранжировать причинные гипотезы | Нет | +| `$strategy-improvement-research` | Начать новый ограниченный контур исследования core + deterministic gate и зафиксировать лучшего воспроизводимого кандидата | Нет | +| `$strategy-period-revalidate` | Перепроверить production и сильных старых кандидатов на расширенном общем периоде без подстройки | Нет | +| `$strategy-forward-start` | Опубликовать и запустить последнего допустимого кандидата — либо явно названного воспроизводимого исторического кандидата — с `MAX_LOSS_VALUE=1` | Да | +| `$strategy-forward-status` | Проверить identity, parity, ордера, исполнение и нормализованный live evidence | Нет | +| `$strategy-risk-scale` | Изменить только `MAX_LOSS_VALUE` у той же запущенной composition | Да | + +`$strategy-release` оставлен как deprecated compatibility router. Он выбирает +ровно один focused lifecycle skill и не должен воссоздавать прежний общий +workflow исследования, публикации, деплоя и изменения риска. + +Промпты остаются короткими: + +```text +$strategy-candidate-report MarketFlushReversal +$strategy-improvement-research MarketFlushReversal +$strategy-forward-start MarketFlushReversal +``` + +## Установка и обновление + +Canonical source skills находится в репозитории TradeJS framework. Все +официальные TradeJS skills входят в один SHA-256 manifest; созданные Projects +не поддерживают независимые копии. Полный официальный snapshot обновляется +только через явно выбранную версию `create-tradejs`: + +```bash +npx create-tradejs@ --update-skills . +``` + +Updater сохраняет несвязанные custom skills и отклоняет изменения уже +управляемого файла. Когда новая версия впервые включает существующий +официальный skill в bundle, явное обновление принимает canonical snapshot с +тем же именем. + +## Корни исследования + +Advanced source-aware research разделяет три ответственности: + +- `PROJECT_CWD` владеет `.env`, конфигурацией, datasets, notes и reports. +- `TRADEJS_SOURCE_REPOSITORY_ROOT` указывает точный Git checkout framework или + standalone strategy, чей build и lineage исследуются. +- `TRADEJS_FRAMEWORK_REPOSITORY_ROOT` предоставляет собранный framework runtime + для исследования. Он обязателен для gate-ablation tool, когда source root — + standalone strategy; если source — framework, оба root могут указывать на + один checkout. + +Ablation tool импортирует `strategyEntries` из build standalone strategy, +поэтому принятый strategy path не заменяется незаметно опубликованным пакетом +из Project. + +## Как выбирается кандидат + +Исследовательский skill не оптимизирует только прибыль за весь период, win +rate или прибыльный хвост 7 дней. Сначала он требует причинную и data-validity, +сверку trace и положительное out-of-sample ожидание на единицу риска после +издержек. Затем оценивает probabilistic/deflated Sharpe, drawdown и tail loss, +время восстановления, серии убытков, серии убыточных месяцев, +walk-forward/regime stability, концентрацию, cost robustness и исполнимую +частоту сделок. + +Прибыль за весь период и win rate остаются важными экономическими +диагностиками, но не являются достаточными сами по себе. Окна 7d/30d/180d +описывают текущий режим. Их вес зависит от числа независимых событий: меньше +20 — недостаточная мощность, 20–49 — диагностический уровень, 50 и больше — +уровень отбора. Разреженный хвост не требует ждать 7, 30 или 180 календарных +дней перед prospective-тестом с риском 1. + +Каждый вызов improvement-research создаёт новый lineage. До новых гипотез skill +перепроверяет сильнейших старых кандидатов на новом общем периоде. Он не +останавливается после аудита или первого неудачного раунда: работа завершается, +когда зафиксирован воспроизводимый лучший кандидат, исчерпан ограниченный +бюджет новых вариантов либо для всех оставшихся семейств записан жёсткий +причинный blocker. + +## Что делает forward start + +`$strategy-forward-start ` — явная граница полномочий для +ограниченного live forward-теста. По умолчанию skill берёт последнего +checksum-verified и forward-eligible кандидата и устанавливает +`MAX_LOSS_VALUE=1`. + +- Если стратегии нет в целевом deployment, skill добавляет и включает её + полную проверенную декларацию. +- Если запущен другой пакет, core config, deterministic gate, context или + direction policy, skill делает одну контролируемую замену. +- Если точная composition с риском 1 уже запущена, skill не меняет конфиг и + идемпотентно проверяет rollout. + +### Явно названный исторический кандидат + +Оператор может вместо этого явно назвать другого исторически перспективного +кандидата для prospective-only обучения. Это не переписывает прежний выбор и +не превращает противоречащие свежие данные в положительный исторический +вердикт. Точные expression, direction policy, effective config, lineage +исходников и данных, evidence hashes, метрики полного периода и график должны +оставаться воспроизводимыми; на максимально покрытом периоде требуются +положительный net PnL и profit factor выше 1. + +До rollout Codex создаёт новый immutable artifact с разрешением оператора, +который ссылается на исходный выбор и противоречащие либо статистически слабые +данные. Отсутствующие hashes, неположительная экономика максимального периода +или необходимость новой подстройки остаются блокерами. Этот режим меняет только +полномочие на prospective-тест с риском 1 и не создаёт историческую валидность +задним числом. + +Если кандидат содержит ещё не опубликованный source стратегии, skill через +настроенный release workflow коммитит и пушит полный release range, публикует +immutable package, устанавливает его точную версию и lockfile в Project, +коммитит и пушит полный Git-owned `tradejs.config.ts`, деплоит точный Project +tip и проверяет `strategyRevision` и `deploymentCompositionId`. + +Skill не выдумывает production target. Заранее должны существовать точные +runtime user, deployment, trading account, connector и workflow публикации и +деплоя. `create-tradejs` добавляет skills и локальный проект, но не создаёт +registry credentials, ключи биржи, production hosting или неуправляемый +background daemon. Если не хватает авторизации или binding, Codex +останавливается на этой границе и показывает точное действие для пользователя. + +## Увеличение риска — отдельное решение + +Используйте `$strategy-risk-scale ` только после анализа prospective +evidence. Skill сохраняет точные package, core, gate, context, universe и +direction policy и меняет только `MAX_LOSS_VALUE`, не более чем на один +разрешённый шаг. Решение зависит от событий, а не календаря: execution parity, +after-cost expectancy, нормализованные drawdown/tail loss, slippage, +концентрация и число независимых сделок важнее факта «прошло 30 дней». + +Требования к счёту, immutable build и runtime описаны в разделе +[Запуск стратегии в рабочем окружении](../getting-started/run-strategy-in-production). diff --git a/sidebars.ts b/sidebars.ts index eb6ac87..6ae57a7 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -134,6 +134,7 @@ const sidebars: SidebarsConfig = { 'runtime/backtesting/replay-evidence', 'runtime/backtesting/runtime-parity', 'runtime/backtesting/strategy-playbook', + 'guides/codex-strategy-skills', ], }, { diff --git a/static/llms-full.txt b/static/llms-full.txt index 75d096a..de3418d 100644 --- a/static/llms-full.txt +++ b/static/llms-full.txt @@ -68,6 +68,7 @@ The documentation covers: - Compare strategies: https://docs.tradejs.dev/guides/compare-strategies - Pine-backed strategy workflows: https://docs.tradejs.dev/guides/pine-workflows - AI/ML workflows: https://docs.tradejs.dev/guides/ai-ml-workflows +- Codex strategy workflow skills: https://docs.tradejs.dev/guides/codex-strategy-skills ### Strategy Authoring diff --git a/static/llms.txt b/static/llms.txt index 7e5c486..06b40da 100644 --- a/static/llms.txt +++ b/static/llms.txt @@ -19,6 +19,7 @@ Marketing site: https://tradejs.dev - Understanding output: https://docs.tradejs.dev/getting-started/understanding-output - Root user setup: https://docs.tradejs.dev/getting-started/root-user - Run a strategy in production: https://docs.tradejs.dev/getting-started/run-strategy-in-production +- Codex strategy workflow skills: https://docs.tradejs.dev/guides/codex-strategy-skills - Examples: https://docs.tradejs.dev/examples - Core API: https://docs.tradejs.dev/api/framework - Built-in strategy catalog: https://docs.tradejs.dev/strategies/reference @@ -29,6 +30,7 @@ Marketing site: https://tradejs.dev - TypeScript strategies: https://docs.tradejs.dev/strategies/authoring/write-strategies - Backtest a strategy: https://docs.tradejs.dev/guides/backtest-strategy +- Codex strategy workflow skills: https://docs.tradejs.dev/guides/codex-strategy-skills - Backtesting: https://docs.tradejs.dev/runtime/backtesting/overview - Validate live decisions with replay: https://docs.tradejs.dev/runtime/backtesting/replay-evidence - Live signals: https://docs.tradejs.dev/runtime/execution/signals