[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EDJS6769TVDTGVQ945TFAX":3,"skill-same:01M7EDJS6769TVDTGVQ945TFAX":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7EDJS6769TVDTGVQ945TFAX","quant-trading-experiment",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fquant-trading-experiment\u002Fquant-trading-experiment\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# quant-trading-experiment\n\n# Quant Trading Experiment\n\nOperate a 12-room, 20-agent quantitative research organization with live demo trading on BingX VST.\n\n## Architecture (stable)\n\n- **CT106 `cortexquant`** = `192.168.1.19`. FastAPI :8080.\n- **12 Rooms**: QUANT_RESEARCH, WEIRD_EDGE, MATH_SIGNAL, STRATEGY_ENG, REGIME_DETECTION, BACKTEST, OPTIMIZATION, SELECTION, RED_TEAM, TRADING_JOURNAL, AI_COACH, RISK_COMMITTEE.\n- **Signal Flow**: Telegram → Telethon MTProto → Parse → 12-Step Validation → Rooms + Demo → BingX VST.\n- **LIVE_TRADING=false** hard default. Demo uses `DEMO_TRADING=true`.\n\n## Critical startup pattern\n\n`await server.serve()` blocks forever. Demo initialization MUST be a background task:\n\n```python\n# CORRECT\nasyncio.create_task(start_demo_experiment())\nawait server.serve()\n\n# WRONG — never reached\nawait start_demo_experiment()\nawait server.serve()\n```\n\n## BingX API quirks\n\n- **Demo balance key is `VST`, not `USDT`**: `balance.get(\"VST\", {}).get(\"total\", 100000)`\n- **Perpetual swap symbols**: `AVAX\u002FUSDT:USDT` not `AVAX\u002FUSDT`. Use `_get_swap_symbol()`.\n- **Position side required**: `params={'positionSide': 'LONG', 'leverage': 3}`\n- **Sandbox**: `exchange.set_sandbox_mode(True)` — VST only, no real funds.\n\n## Schema dependencies\n\n`tg_parsed_signals.raw_message_id` FK → `tg_raw_messages.id`. Insert raw first, commit, then parsed.\n\n## Signal pipeline liveness — ingestion ≠ parsing\n\nA green systemd unit and a growing `tg_raw_messages` table prove the Telethon\nclient works. They do NOT prove any signal is being extracted. Before opening any\n\"why is no trade happening\" investigation, check the parse outcome distribution\nrather than the process state:\n\n```sql\nSELECT ingestion_status, count(*) FROM tg_raw_messages GROUP BY 1;\nSELECT date_trunc('day', created_at) AS d, count(*) FROM tg_parsed_signals GROUP BY 1 ORDER BY 1 DESC;\n```\n\nA healthy ingester can sit at thousands of rows while the entire signal path\ndownstream is dead — this system ran for days with raw messages arriving every\n~10 minutes and zero parsed signals.\n\n**The upstream channel changes its message format and the parser silently stops\nmatching.** When `PARSE_ERROR` dominates, do NOT assume the parser is broken and\nstart rewriting regexes. First classify the raw corpus by shape and by day\n(recipe: `references\u002Fsignal-parser-maintenance.md`) and answer the prior\nquestion: *does the feed currently contain anything parseable at all?* The feed\nhad degraded to re-posted disclaimer boilerplate every ~10 min plus a\nfunding-outlier digest — neither is a tradable signal — and the last real scout\nlist was 8 days old. The correct output there is \"no valid signal exists, clock\nNOT started\", not a rewritten parser and not a stale-signal trade.\n\nState the consequence plainly when the feed is empty:\n- Signal max age is 300 s; anything older is `stale_signal` by design.\n- Standing rule: never trade historical signals as if live.\n- Therefore the 7-day clock cannot start until a fresh parseable signal arrives.\n\n## Risk limits\n\n| Limit | Value |\n|---|---|\n| Max position | 2% portfolio |\n| Max exposure | 15% |\n| Max concurrent | 3 |\n| Leverage | 3x |\n| Stop loss | 2% |\n| Take profit | 4% |\n| Signal age | 5 min |\n\n## Safety Constraints\n\n- **LIVE_TRADING=false** is a HARD DEFAULT. Never enable without explicit written approval.\n- **Never claim profitability from a 7-day sample.** Demo results are not statistically significant.\n- **Never promise or imply guaranteed wins \u002F guaranteed returns, on this system or any trading system.** If asked to \"guarantee constant wins\" or similar, say plainly that no system guarantees returns on real markets (if one did, arbitrage would erase the edge) and redirect to the real target: positive expected value with survivable risk of ruin, validated only after enough trades exist to measure win rate \u002F EV per trade \u002F max drawdown. This is a correctness rule, not a hedge — do not soften it into a caveat and then answer the guarantee question anyway.\n- **Never auto-scale position sizes.** Fixed conservative limits only.\n- **Never trade historical signals as if live.** Only process signals received after experiment start.\n- **Demo credentials stay in server `.env` only.** Never commit or log secrets.\n- **Training completion is not model approval, AND training must persist.**\nA model is usable only when explicit validation gates pass; otherwise record it\n`observation_only` and let the strategy engine fall back to `ckp_baseline`.\nGates that must ALL hold on the validation split: directional accuracy > 0.52,\nSpearman IC > 0.02, R² ≥ 0, and MAE no worse than the no-model (`train`-mean)\nbaseline. Persist the approved\u002Fobservation-only decision AND the failing gate\nvalues into `models\u002Fml_metadata.json` — \"trained\" alone is not a record.\n\n**Critical: the `train()` method must call `save()` before returning.** A\n`train()` that fits the model in memory but never writes `ml_predictor.pkl` +\n`ml_metadata.json` to `MODEL_DIR` loses the trained artefact on every cycle —\nthe next `load()` finds nothing. After patching `train()`, verify with:\n`ls -la \u002Fopt\u002Fcortexquant\u002Fmodels\u002Fml_predictor.pkl` after a training run. A\ntrained-but-never-saved model is indistinguishable from an untrained one at\nload time; this is the bug that made the pipeline's ML always\nobservation-only even after the worker trained successfully.\n- **Chronological splits only, pooled by timestamp — never per-symbol, never\nshuffled.** Splitting each symbol independently lets one symbol's later bars land\nin another symbol's training window. The label is the forward return\n(`close.pct_change().shift(-1)`), so the final bar per symbol must be dropped\nafter shifting.\n- **Train on the exchange you actually execute on.** The legacy trainer pulled\nOHLCV from Binance while demo execution runs on BingX; symbol sets and available\nhistory differ, so the metrics described instruments that were never traded.\nBingX sandbox `fetch_ohlcv(..., since=\u003C45d ago>)` returns about 1000 bars\nregardless of how far back you ask, so record the ACTUAL period covered rather\nthan the requested lookback.\n\n## Pitfalls\n\n- main.py blocking: demo must be create_task, not await.\n- BingX VST balance, not USDT.\n- Swap symbols need `:USDT` suffix.\n- FK constraints: raw before parsed.\n- Separate-process tests see callback=None — test via server API.\n- **`re.match()` anchors at position 0 — real channel lines are indented, so a\n  pattern without a leading `\\s*` matches none of them.** Test every parser regex\n  against the ACTUAL corpus (`SELECT raw_text FROM tg_raw_messages`), never\n  against an idealized example typed from memory; the scout lines arrive as\n  `\" 1. ALCH-USDT | ...\"` with a leading space.\n- **When a parser has two alternate line patterns, do not assume identical group\n  numbering.** `match.group(3)` on a 2-group fallback pattern raises\n  `IndexError: no such group`. Normalize both patterns into the same\n  `(symbol, data)` tuple in one place instead of indexing groups inline.\n- **A crash guarded by a condition that never currently holds is still a live\n  bug.** `tg_service._process_message` iterates `for p in parsed:` while the\n  variable is `parsed_results` — a `NameError` that never fires only because\n  `parse()` currently returns `None` for every message. The moment a real signal\n  arrives it raises, rolls back the transaction, and loses BOTH the raw and the\n  parsed row. When auditing an ingestion path, trace the branch that runs when\n  the happy path finally succeeds, not just the branch executing today.\n- **Noise markers beat clever regexes for messages that must never trade.** A\n  disclaimer\u002Fdisclaimer-repost or a funding-outlier digest mentions LONG\u002FSHORT\n  and carries `SYMBOL-USDT | RSI15=...` lines, so a naive symbol matcher happily\n  emits fake signals from it. Reject on substring markers (`\"About these scanner\n  lists\"`, `\"Funding Outliers\"`, `\"not guaranteed trade calls\"`) before line\n  parsing, and assert those rejections in the parser's self-check.\n- **Scope discipline**: When asked to fix startup, locate the real running server's main.py first. Do not keep building new modules — inspect the deployed code, find the entrypoint, fix the actual blocking call.\n- **No systemd unit means the server is exactly one dropped SSH session from\n  being dead with no error.** Launching `main.py` by hand (even with\n  `setsid`\u002F`nohup`) survives only as long as something keeps the process\n  supervised. When an audit or a \"why isn't it running\" check finds the log\n  stopped mid-line with no crash\u002FOOM entry, that absence of a unit IS the root\n  cause — write `\u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexquant.service` with\n  `ExecStart=\u002Fopt\u002Fcortexquant\u002Fstart.sh` and `Restart=on-failure`, don't just\n  relaunch by hand again.\n**Two config classes can both define risk limits — grep the import in the\nfile that places orders, not the first `Settings`-looking file.**\n  `src\u002Futils\u002Fconfig.py` carries a generic `Settings` class and\n  `src\u002Fexchange\u002Fdemo_trading_service.py` carries its own `BingXDemoConfig`.\n  If both are live in the same process (not dead code), confirm which one each\n  consumer actually imports via `grep 'from.*import.*config\\|demo_trader.config'`\n  in every file that touches risk\u002Fexposure\u002Fconcurrency logic — including the\n  risk engine, the pipeline, and any worker that calls risk methods.\n  **When two live config classes disagree, fix by making the risk engine accept\n  an optional `config` parameter** (defaulting to the generic one, overridable by\n  the demo config) rather than deleting one class. That keeps both consumers\n  wired through a single authoritative check while preserving each consumer's\n  own limits. See `references\u002Frisk-config-consolidation.md` for the exact pattern.\n  Dead-code config classes (imported nowhere) should be removed, not patched.\n- **A defined settings key is not the same as an enforced control — grep every\n  reference before crediting a security setting as active.** `API_SECRET_KEY`\n  in `Settings` had zero consumers until an `@app.middleware(\"http\")` bearer-auth\n  check was added in `api.py` gating every POST\u002FPUT\u002FPATCH\u002FDELETE (GETs stay open\n  for dashboards). Return `JSONResponse(status_code=401, ...)` from that\n  middleware, never `raise HTTPException` — middleware exceptions bypass\n  FastAPI's handlers and become a 500 instead (see `python-fastapi-hardening`).\n  Verify all three cases with curl: no token → 401, wrong token → 401, real\n  token from `.env` → 200. `CORSMiddleware(allow_origins=[\"*\"])` still means\n  any LAN host can send the request; the bearer check is what actually gates it.\n- **The demo kill switch (`demo_trader.kill_switch`, flipped via\n  `POST \u002Fapi\u002Fdemo\u002Fkill-switch`) has no deactivate endpoint** — unlike the\n  separate generic `\u002Fapi\u002Fkill-switch\u002F{activate,deactivate}` pair in\n  `risk.py`\u002F`api.py`. Once tripped it only resets by restarting the service\n  (`systemctl restart cortexquant`), which re-runs `start_demo_experiment()`\n  and starts a *new* experiment run. Never POST that endpoint during testing\n  without immediately restarting the service afterward, or the demo trader\n  stays halted with no code-level way to resume it.\n- **A room method existing with the right name is not the same as it computing\n  anything real — grep for its actual callers and body before crediting a\n  feature as implemented.** `BacktestRoom.run_backtest()` in `rooms.py` returns\n  a hardcoded all-zero dict (sharpe\u002Fwin_rate\u002Fetc all 0) and never calls the real\n  `src\u002Fbacktest\u002Fbacktester.py::Backtester` class that already does point-in-time\n  simulation with fees\u002Fslippage\u002FSharpe\u002Fdrawdown. Before proposing to \"add\n  backtesting\" or \"wire up X\", check whether the real engine already exists and\n  is just unwired — that's a smaller diff than writing a new one, and the\n  correct fix is calling the existing class, not building another.\n- **Red Team and Risk Committee are already hard promotion gates** —\n  `ChiefQuantDirector.promote_research()` calls `_check_veto()` before allowing\n  a transition to `PRODUCTION_CANDIDATE`\u002F`LIVE_ELIGIBLE`, and either room's\n  `VETO` message flips the experiment to `REJECTED` and blocks promotion. If\n  asked to \"make Red Team\u002FRisk Committee a hard gate\", verify this isn't\n  already true before writing new veto-enforcement code.\n- **`ResearchTask` rows get created by every room (`create_task`,\n  `delegate_to_room`) but nothing ever consumes the PENDING queue.** There is\n  no worker loop that picks up pending tasks, runs them, and marks them\n  RUNNING\u002FCOMPLETED\u002FFAILED outside of tests — `ChiefQuantDirector.prioritize_queue()`\n  only reads the queue, nothing drains it. Any \"make the rooms actually run\n  autonomously\" ask needs a task-consumer loop as the actual missing piece,\n  not more room\u002Fagent scaffolding (which already exists for all 12 rooms\u002F24 agents).\n- **Supervision house style is `asyncio.create_task` loops inside the FastAPI\n  process, not Celery** — `celery==5.4.0` sits in `requirements.txt` unused.\n  Adding Celery for background workers means a broker + beat + separate worker\n  process to supervise themselves — more moving parts than one more\n  `asyncio.create_task` loop next to the existing `demo_lifecycle.py` \u002F\n  `_monitor_experiment()` pattern. Stay with asyncio tasks + a persisted\n  heartbeat\u002Fstatus table unless throughput genuinely outgrows a single process.\n- **For a large multi-phase build request (new worker architecture, incentive\n  system, dashboard overhaul, etc.), audit the real filesystem for what already\n  exists before scoping phases.** Pull the actual source tree first (rooms,\n  schema, events, dashboard, backtester) via SSH\u002Ftar rather than assuming from\n  memory notes, then present the phased plan against what's real vs. stubbed —\n  this cuts scope by however much already exists and avoids rebuilding working code.\n\n## Demo activation flow\n\nThe demo experiment starts via the API with the Bearer token from `.env`:\n```bash\nTOKEN=$(grep '^API_SECRET_KEY=' \u002Fopt\u002Fcortexquant\u002F.env | cut -d= -f2)\ncurl -s -X POST -H \"Authorization: Bearer $TOKEN\" http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fdemo\u002Fstart\n```\nThis calls `demo_trader.initialize(api_key, secret)` → loads BingX VST markets → creates an `ExperimentRun` row → sets `demo_trader.is_active = True` and `demo_trader.experiment_end` to 7 days out. **The start call must happen AFTER the server is running** (main.py calls `start_demo_experiment()` as a background task, but if `DEMO_TRADING` was off at boot, a manual restart via the API is needed).\n\nAfter start, verify markets loaded and balance:\n```bash\ncurl -s http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fdemo\u002Fstatus | python3 -m json.tool\n# Expect: \"is_active\": true, \"experiment_end\" set, \"days_remaining\": 6-7\n```\n\n### Reconciliation Overflow Pitfall\n\nThe startup reconciliation script (`reconcile_demo.py`) creates `DemoTrade` DB\nrows for every open exchange position. If reconciliation runs when more than\n`MAX_CONCURRENT_TRADES` positions are open on the exchange (e.g., 5 positions\nvs 3 limit), the demo trader immediately hits `Max concurrent trades reached`\nand rejects **every** fresh signal — even though some pre-existing positions are\ndesirable (BTC, AVAX) and others are noise (BAS, ARC, EGLD).\n\n**Fix:** reconciliation must count existing positions against\n`MAX_CONCURRENT_TRADES` and only mark the oldest N as open; close (or skip) the\nrest via the BingX API before starting the experiment clock. Reconciliation\nmust also update `demo_trader.daily_pnl` from exchange positions so the\ndaily-loss guard has real data — a `daily_pnl` that stays 0 means the guard\nnever fires regardless of actual P&L.\n\n**Reconciliation script:** `\u002Fopt\u002Fcortexquant\u002Freconcile_demo.py` can be run\nstandalone via `pct exec 106 -- python3 \u002Fopt\u002Fcortexquant\u002Freconcile_demo.py`\n(wraps `reconcile_with_exchange()`). Useful for manual reconciliation outside\nthe service lifecycle.\n\n### ML Training Reality (2026-09)\n\n`GradientBoostingRegressor` on 365-day 1h OHLCV for BTC\u002FETH\u002FSOL\u002FAVAX yields\nR² ≈ -0.04 — no predictive power. The model is saved but fails validation gates.\nUse `ML_SKIP_VALIDATION=true` (systemd drop-in) to bypass the gate for demo\npurposes, or improve features\u002Fmodel before relying on ML signals.\n\n**ML persistence must survive restart.** After a training run, verify the model\nfile exists: `pct exec 106 -- ls -la \u002Fopt\u002Fcortexquant\u002Fmodels\u002Fml_predictor.pkl`.\nIf the file is absent after a training cycle, the `train()` method is not\ncalling `save()` — the trained model is lost and the pipeline loads nothing.\nFix: add a `save()` call at the end of `train()` (both the mean-fallback and\nensemble\u002Fgbm success paths).\n\n**Systemd drop-in for ML bypass:**\n```bash\nssh root@192.168.1.11 'pct exec 106 -- bash -c \"\n  mkdir -p \u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexquant.service.d\n  echo -e \\\"[Service]\\\\nEnvironment=ML_SKIP_VALIDATION=true\\\" > \u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexquant.service.d\u002Fml-skip.conf\n  systemctl daemon-reload\n  systemctl restart cortexquant\n\"'\n```\n\n### Existing positions (2026-09-20)\n\n| Symbol | Direction | Entry | Size | Source |\n|--------|-----------|-------|------|--------|\n| BTC | LONG | $77,142.90 | 0.001 | Reconciliation |\n| AVAX | LONG | $7.39 | 811.91 | CKPscanner |\n\nTwo more (ARC, BAS, EGLD) exist as reconciliation artifacts and push total to 5 — above MAX_CONCURRENT_TRADES=3. Must close at least 2 to accept new signals.\n\n### Reconciliation on Startup\n\n`demo_trader.positions` is in-memory only — service restart loses all tracked positions while BingX retains the real ones. Add reconciliation to `start_demo()` BEFORE the background task starts:\n\n```python\npositions = await demo_trader.adapter.get_positions()\nfor pos in positions:\n    symbol = pos['symbol'].replace('\u002FUSDT', '').replace(':USDT', '')\n    if symbol not in demo_trader.positions:\n        demo_trader.positions[symbol] = {\n            'exchange_order_id': pos['id'],\n            'direction': pos['side'],\n            'entry_price': pos['entryPrice'],\n            'size': pos['contracts'],\n        }\n```\n\nWithout this, the first pipeline run after a restart sees 0 internal positions and may try to re-open existing BTC\u002FAVAX positions.\n\n## BingX transient: `timestamp is invalid` (code 109400)\n\nThe demo trading log repeatedly logs `BingX positions error: bingx {\"code\":109400,\"msg\":\"timestamp is invalid\"}`. This is **transient** — the CCXT adapter sometimes gets a clock-skewed timestamp on the first call after restart. It does NOT mean the integration is broken. Confirm via a direct CCXT test:\n```bash\npython3 -c \"\nimport ccxt, time\nex = ccxt.bingx({'apiKey': '...', 'secret': '...', 'enableRateLimit': True, 'options': {'defaultType': 'swap'}})\nex.set_sandbox_mode(True)\nprint('Markets:', len(ex.load_markets()))\nprint('Positions:', len(ex.fetch_positions()))\n\"\n```\nIf markets load and positions return, the connection is healthy. The errors stop on retry. Do NOT treat a few `timestamp is invalid` log lines as a config bug.\n\n## Supervisor guard: `LIVE_TRADING_GUARD`\n\n`src\u002Fworkers\u002Fsupervisor.py` has a hard guard at module level:\n```python\nLIVE_TRADING_GUARD = True\n```\nThis means `WorkerSupervisor.start_all()` **refuses to start any workers** if `LIVE_TRADING=true`, regardless of `DEMO_TRADING`. If the user says \"start live trading\" and you flip `LIVE_TRADING=true` in `.env`, the supervisor will dead-stop. The demo path uses `DEMO_TRADING=true` and leaves `LIVE_TRADING=false`. To actually enable real BingX trading, the supervisor guard logic must be explicitly changed (not just `.env`), and this requires explicit per-session approval.\n\n## VST demo balance starts at ~100,000\n\nThe BingX VST sandbox account starts with **~100,000 VST** (not 0). The `fetch_balance()` returns `{'VST': {'free': 99693.0, 'used': 302.9, 'total': 99996.0}}`. Demo trades execute immediately once the pipeline is wired.\n\n## Full Signal-to-Execution Pipeline\n\nThe pipeline wires: Telegram parsing → market snapshot → ML prediction → strategy selection → classical optimization → quantum optimization → risk check → BingX execution → decision record → post-trade analytics.\n\n**Two execution paths must converge.** Historically this system had two parallel\npaths to demo execution: (a) the orchestrator's 12-step alpha validation +\nshared `FullPipeline`, and (b) the Telegram publisher's direct `FullPipeline`\ncall per signal. When both are active, a signal's validation depends on which\npath receives it — inconsistent and untestable. The correct wiring: **the\npublisher's `_safe_demo_call` must route through the orchestrator's\n`process_signal`**, not create a fresh `FullPipeline`. The orchestrator owns the\nshared pipeline instance; the publisher is a delivery mechanism only.\n\n### Architecture\n```\ntg_publisher → orchestrator.process_signal(signal_dict)\n  ├─ 12-step alpha validation (AlphaExtractionPipeline)\n  ├─ shared FullPipeline (single instance, not fresh per call)\n  │   ├─ idempotency check (DecisionRecord.by signal_id)\n  │   ├─ market snapshot (OHLCV from BingX via demo_trader.adapter.exchange)\n  │   ├─ ML prediction (MLPredictor — observation-only until trained+saved)\n  │   ├─ strategy selection (StrategyEngine with deterministic fallback)\n  │   ├─ classical optimization (RiskfolioAdapter)\n  │   ├─ quantum optimization (QuantumSolver)\n  │   ├─ risk check (RiskEngine — accepts optional config param)\n  │   ├─ duplicate position check\n  │   └─ BingX VST execution (demo_trader.process_signal)\n  ├─ DecisionRecord persisted to database\n  └─ demo_trader.reconcile_positions() updates daily_pnl from fills\n\n\u002Fapi\u002Fdemo\u002Ftest-signal → orchestrator.process_signal(signal_dict)  # same path\n```\n\n### DecisionRecord Schema\nThe `decision_records` table captures every signal's complete journey:\n- `signal_id` (unique, idempotency key)\n- `signal_parsed`, `market_snapshot`, `ml_prediction`, `ml_confidence`\n- `strategy_selected`, `strategy_params`\n- `classical_optimizer_output`, `quantum_optimizer_output`\n- `risk_decision` (approved\u002Frejected), `risk_reason`\n- `order_params`, `exchange_order_id`, `fill_price`, `fill_quantity`\n- `fees`, `funding`, `slippage`\n- `exit_price`, `exit_reason`, `gross_pnl`, `net_pnl`\n- `status` (pending, executed, closed, rejected, error)\n- `error_classification`, `market_regime`\n\n### Idempotency Pattern\nAlways check for existing DecisionRecord before processing. A signal that was rejected yesterday must not be re-processed on restart.\n\n### API Routes\n- `GET \u002Fapi\u002Fpipeline\u002Fdecisions` — list recent decisions\n- `GET \u002Fapi\u002Fpipeline\u002Fdecisions\u002F{signal_id}` — full decision chain\n- `GET \u002Fapi\u002Fpipeline\u002Fstats` — execution statistics\n\n## User Workflow Preferences (Always-On)\n\nThese are standing rules the user explicitly stated. They apply to every session.\n\n- **Do not increase risk limits to force a trade.** If `PER_TRADE_RISK_PCT=1.0%` and the pipeline submits 2.0%, the rejection is correct behavior. Record the mismatch, add a regression test, and stop.\n- **Treat rejections as integration tests.** A `\"rejected\"` status is a successful pipeline execution, not a bug.\n- **The demo path sizes on notional, not on risk-at-stop — do not report\n  `MAX_POSITION_SIZE_PCT` as the per-trade risk.**\n  `demo_trading_service.process_signal` computes\n  `size = balance * MAX_POSITION_SIZE_PCT\u002F100 \u002F price`, then multiplies by\n  `LEVERAGE_MAX`. So notional is `balance × 2% × 3 = 6%` of the account, and with a\n  2% stop the actual loss at the stop is about `6% × 2% = 0.12%` of the account —\n  nowhere near the configured percentage. `RiskEngine.calculate_position_size()`\n  DOES implement true risk-at-stop sizing (`risk_amount \u002F risk_per_unit`, where\n  `risk_per_unit = entry − stop_loss`), but the demo execution path never calls it.\n  When asked to \"verify risk is X% per trade measured as loss at the stop-loss\",\n  compute the loss from the sizing expression actually used and state the real\n  number; do not echo the config constant back as the answer.\n- **Fix blockers in this order:** (1) make risk authoritative, (2) replace hardcoded Binance with BingX market resolver, (3) implement `StrategyEngine.select_strategy()`, (4) put ML in observation-only mode, (5) add synthetic e2e test mode, (6) process one real signal only when fully validated.\n- **Label momentum_ma as a fallback, not an AI decision.** When ML is untrained or confidence \u003C 0.6, the strategy MUST be labeled `\"fallback\"`.\n- **Never treat default 0.5 confidence as a validated prediction.** Untrained ML models MUST return `{\"confidence\": 0.5, \"observation_only\": True}`.\n- **Synthetic e2e test mode is mandatory before any real trade.** Implement a `test_e2e()` method that runs the full pipeline WITHOUT placing orders.\n- **Never allow an LLM to directly rewrite production trading code, bypass risk controls, or promote itself.**\n- **Process a real signal ONLY when ALL gates pass:** exact market exists on BingX, ML model is trained (or ckp_baseline is explicitly used), risk approves, no duplicate position\u002Forder would be created, and the signal is fresh.\n- **Report exact details, not summaries.** For every pipeline test or trade, report: signal_id, symbol, direction, prediction, strategy name + reason, classical\u002Fquantum optimizer outputs, risk decision + reason, order params, exchange response, fill details, fees, and final P&L.\n- **Do not optimize further until one complete real signal has traversed the entire pipeline.**\n\n## Verify\n\nWhen the signal path looks dead (`PARSE_ERROR` dominant, no recent\n`tg_parsed_signals`), work through\n`references\u002Fsignal-parser-maintenance.md` before touching any regex — it separates\n\"parser broke\" from \"feed carries nothing\", which need opposite responses.\n\n```bash\ncurl http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fdemo\u002Fstatus | python3 -m json.tool\ncurl -s -X POST http:\u002F\u002Flocalhost:8080\u002Fapi\u002Fdemo\u002Ftest-signal | python3 -m json.tool\ntail -50 \u002Ftmp\u002Fcq.log | grep -a demo\\|BingX\\|callback\\|order\n```\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fquant-trading-experiment\u002Fquant-trading-experiment","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill quant-trading-experiment",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill quant-trading-experiment",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill quant-trading-experiment","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fquant-trading-experiment\u002Fquant-trading-experiment\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",365,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fquant-trading-experiment\u002Fquant-trading-experiment\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]