[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EDQ4WBGY5SD55S75KTC299":3,"skill-same:01M7EDQ4WBGY5SD55S75KTC299":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},"01M7EDQ4WBGY5SD55S75KTC299","trading-intelligence-platform",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\u002Ftrading-intelligence-platform\u002Ftrading-intelligence-platform\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# trading-intelligence-platform\n\n---\nname: trading-intelligence-platform\ndescription: \"Build trading intelligence platforms with canonical data.\"\n---\n\n# Trading Intelligence Platform\n\nQuantitative research organization with 12 rooms, 24 agents, SSE dashboard, Telegram signal ingestion, and a supervised 24\u002F7 worker fleet.\n\n## Architecture Overview\n\nThe CortexQuant Trading Intelligence Platform is a persistent, self-healing system built on:\n- **FastAPI + uvicorn** for the REST API (port 8080)\n- **systemd** for service management (auto-start on boot, restart on failure)\n- **WorkerSupervisor** for independent worker lifecycle (heartbeat, retry, escalation)\n- **Telethon MTProto** for Telegram channel ingestion (CKPscanner)\n- **BingX VST demo** for order execution\n- **PostgreSQL** for all persistent state\n\n## 24\u002F7 Worker Fleet\n\nThe platform runs 19 supervised workers, each with its own asyncio task, heartbeat tracking, and exponential backoff. Workers are defined in `src\u002Fworkers\u002Fjobs.py` and managed by `src\u002Fworkers\u002Fsupervisor.py`.\n\n### Worker Groups\n\n| Group | Workers | Cadence |\n|-------|--------|--------|\n| core | dashboard_feed, monitor | 5s–60s |\n| trading | demo_reconcile | 30s |\n| ingestion | tg_ingestion | 120s |\n| research | market_data, hypothesis, walkforward, strategy_version, backtest_adapter | 120s–600s |\n| gates | red_team, risk_committee | 240s |\n| rooms | room_tasks | 45s |\n| ml | ml_predict | 300s |\n| quantum | quantum_optimize | 600s |\n| portfolio | portfolio_optimize | 300s |\n\n### Failure Classification\n\nEach worker failure is classified into one of four categories with different retry policies:\n\n| Class | Meaning | Backoff Multiplier |\n|-------|---------|-------------------|\n| TRANSIENT | Network, timeout, rate limit | 1.0x |\n| RESOURCE | Memory, disk pressure | 4.0x |\n| UNKNOWN | Unclassified error | 1.5x |\n| PERMANENT | Bad config, missing column | 3.0x (no retry) |\n\nPERMANENT failures do not retry — they escalate to the human.\n\n### Escalation\n\nAfter 3 consecutive failures, a worker enters ESCALATED state. The monitor worker sends alerts (Telegram bot, WorkerEvent). Maximum escalation level is 3.\n\n### Heartbeat Staleness\n\nA worker is STALE if no heartbeat for `max(60s, interval * 3)`. The monitor worker tracks stale workers and raises CRITICAL alerts.\n\n## Startup Recovery Procedure\n\nOn service startup, the system must recover full state before processing any new signals. The recovery sequence is:\n\n1. **Database schema** — `init_db()` creates all tables if missing\n2. **Experiment state** — load last `ExperimentRun` from DB\n3. **Exchange reconciliation** — `exchange.fetch_positions()` → sync to `demo_trader.positions` → create `DemoTrade` DB rows for any positions not tracked\n4. **Telegram reconnect** — Telethon auto-reconnects; `tg_ingestion_worker` monitors liveness\n5. **Worker fleet start** — `supervisor.start_all()` launches all 19 workers\n6. **Publisher callback** — `tg_publisher.set_demo_callback(orchestrator.process_signal)` wires signal routing\n\n**Critical:** Without reconciliation, the internal position state is empty after restart, and the duplicate-position check cannot see existing BTC\u002FAVAX positions — leading to duplicate orders.\n\n## Signal Freshness Gate\n\nEvery Scout signal must satisfy ALL gates before execution:\n\n| Gate | Check | Rejection Reason |\n|------|-------|-----------------|\n| Freshness | Signal timestamp within 5 minutes | `stale_signal` |\n| Market | Symbol exists on BingX as `BASE\u002FUSDT:USDT` or `BASE\u002FUSDT` | `no_market` |\n| ML | Model is trained OR `ML_SKIP_VALIDATION=true` is set | `ml_gate` |\n| Risk | `RiskEngine.check_signal()` passes with real risk\u002Fsize values | `risk` |\n| Idempotency | No existing `DecisionRecord` for this signal_id | `duplicate` |\n| Duplicate | Symbol not already in `demo_trader.positions` | `duplicate_position` |\n| Concurrent | Open positions \u003C `MAX_CONCURRENT_TRADES` | `max_concurrent_trades` |\n\n### Pipeline Must Pass Real Values to Risk Engine\n\n**BUG:** The original pipeline hardcoded `risk_pct=2.0, position_size_pct=2.0` instead of reading from `signal` or `settings`. This caused every signal to be rejected when `PER_TRADE_RISK_PCT=5.0`.\n\n**Fix:** In `FullPipeline.process_signal()`, the risk check must use:\n```python\nrisk_result = self.risk.check_signal(\n    {\"position_size_pct\": signal.get(\"position_size_pct\", settings.MAX_POSITION_SIZE_PCT),\n     \"risk_pct\": signal.get(\"risk_pct\", settings.PER_TRADE_RISK_PCT)},\n    portfolio_state,\n)\n```\n\n## Exposure Management\n\n### Emergency Rebalancing\n\nWhen exchange positions exceed `MAX_CONCURRENT_TRADES` or exposure exceeds safe thresholds, the system must:\n\n1. Identify positions to keep (BTC, AVAX, and other deliberate positions)\n2. Close all other positions via BingX market orders\n3. Mark closed positions in DB with `exit_reason='EMERGENCY_REBALANCE'`\n4. Verify exposure returns to safe levels (\u003C 25%)\n\n**Command pattern for closing positions:**\n```python\n# Fetch all positions from exchange\npositions = await exchange.fetch_positions()\nfor pos in positions:\n    symbol = pos['symbol'].replace('\u002FUSDT', '').replace(':USDT', '')\n    if symbol not in KEEP:\n        close_side = 'sell' if pos['side'] == 'long' else 'buy'\n        await exchange.create_order(symbol=pos['symbol'], type='market',\n                                   side=close_side, amount=pos['contracts'],\n                                   params={'positionSide': 'LONG', 'leverage': 3})\n```\n\n### Meme-Coin Inflation\n\nCKPscanner Scout messages can produce positions in low-value meme coins (BIKETYSON, FLYBRAIN, PIPEDOG, etc.). These positions accumulate rapidly because the pipeline executes every Scout signal without concentration limits beyond `MAX_CONCURRENT_TRADES`.\n\n**Mitigation:**\n- Regular exposure checks (every reconcile cycle)\n- Emergency rebalancing when exposure exceeds threshold\n- Do not trust `demo_trader.positions` alone — always reconcile with `exchange.fetch_positions()` for ground truth\n\n## Systemd Service Configuration\n\n### Service File\n```ini\n[Unit]\nDescription=CortexQuant Trading Intelligence Platform\nAfter=network.target postgresql.service redis-server.service\n\n[Service]\nType=simple\nWorkingDirectory=\u002Fopt\u002Fcortexquant\nExecStart=\u002Fopt\u002Fcortexquant\u002Fvenv\u002Fbin\u002Fpython \u002Fopt\u002Fcortexquant\u002Fmain.py\nRestart=on-failure\nRestartSec=5\nUser=root\n\n[Install]\nWantedBy=multi-user.target\n```\n\n### Environment Drop-in\n\n`systemctl edit` fails without a TTY. Use the drop-in directory directly:\n\n```bash\n# Create drop-in to set environment variables:\nmkdir -p \u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexquant.service.d\ncat > \u002Fetc\u002Fsystemd\u002Fsystem\u002Fcortexquant.service.d\u002Fml-skip.conf \u003C\u003C 'EOF'\n[Service]\nEnvironment=ML_SKIP_VALIDATION=true\nEOF\nsystemctl daemon-reload\nsystemctl restart cortexquant\n```\n\n### Auto-Start on Boot\n\n```bash\nsystemctl enable cortexquant  # Enable auto-start\nsystemctl is-enabled cortexquant  # Verify\n```\n\n### Restart Throttle Trap\n\nAfter ~5–8 rapid restart failures, systemd rate-limits further restarts. Reset before retrying:\n```bash\nsystemctl reset-failed cortexquant && systemctl restart cortexquant\n```\n\n## Health Verification\n\n### Health Endpoint\n\nThe `\u002Fapi\u002Fsystem\u002Fhealth` endpoint returns a comprehensive health snapshot:\n- Worker fleet status (healthy\u002Fstale\u002Fescalated counts)\n- Last signal (id, symbol, direction, confidence, timestamp)\n- Last trade (id, symbol, direction, status, timestamp)\n- Open positions (count and symbols)\n- Experiment status (id, day, start_time)\n- Model version and approval status\n- Recent signals count (last hour)\n\n### Verify Without SSH\n\n```bash\n# From any machine on the network:\ncurl http:\u002F\u002F192.168.1.19:8080\u002Fapi\u002Fsystem\u002Fhealth\ncurl http:\u002F\u002F192.168.1.19:8080\u002Fapi\u002Fworkers\u002Fhealth\ncurl http:\u002F\u002F192.168.1.19:8080\u002Fapi\u002Fdemo\u002Fstatus\ncurl http:\u002F\u002F192.168.1.19:8080\u002Fapi\u002Ftg\u002Fhealth\n```\n\n## Worker Persistence Schema\n\nAll worker state is persisted in PostgreSQL. Key tables:\n\n| Table | Purpose |\n|-------|--------|\n| `worker_states` | Live heartbeat, status, counters per worker |\n| `worker_runs` | One row per execution (success or failure) |\n| `worker_events` | Escalations, retries, recoveries |\n\nThe `WorkerSupervisor.snapshot()` method returns live status including staleness computed from heartbeat age.\n\n## Post-Trade Learning\n\nAfter every completed trade, the system:\n\n1. Persists full `DecisionRecord` with all pipeline stages\n2. Classifies errors into categories (prediction_error, execution_error, risk_stop, profit_target, funding_cost, slippage_cost)\n3. Updates the learning dataset\n4. Generates improvement hypotheses (stored in `research_memory`)\n5. Hypotheses must pass walk-forward validation before promotion\n6. Promotion requires human approval — never auto-promote\n\n## Testing Recovery Scenarios\n\n### Reboot Recovery\n1. `systemctl enable cortexquant` — service starts on boot\n2. On startup, `demo_lifecycle.start_demo_experiment()` runs reconciliation\n3. All workers restart with fresh heartbeats\n\n### Worker Crash Recovery\n1. `supervisor._loop()` catches the exception\n2. Failure is classified and recorded in `worker_runs`\n3. Exponential backoff (TRANSIENT: 1x, RESOURCE: 4x, UNKNOWN: 1.5x)\n4. After `max_retries`, enters DEGRADED or ESCALATED state\n5. Monitor worker sends alert\n\n### Telegram Disconnect\n1. Telethon auto-reconnects (built-in)\n2. `tg_ingestion_worker` checks heartbeat age every 120s\n3. If no heartbeat for 5 minutes, reports `connected: false`\n4. Monitor worker raises CRITICAL alert\n\n### Exchange API Failure\n1. `classify_error()` catches CCXT exceptions\n2. TRANSIENT errors (timeout, rate limit) trigger retry with backoff\n3. PERMANENT errors (auth failure, bad symbol) escalate to human\n4. After reconciliation, positions are restored from exchange\n\n### Duplicate Signal Handling\n1. `DecisionRecord.signal_id` is UNIQUE\n2. `_check_idempotency()` returns existing record before processing\n3. Signals marked `published_to_bus=True` are skipped on reprocessing\n\n### Position Reconciliation\n1. `exchange.fetch_positions()` returns ground truth\n2. Internal `demo_trader.positions` is rebuilt from exchange data\n3. Missing DB rows are created; stale rows are closed\n4. Idempotency key: `symbol` + `signal_id`\n\n## Silent Bug Patterns\n\n### Pipeline Risk Hardcoding\n**Symptom:** Every signal rejected with \"Per-trade risk exceeds limit\"\n**Cause:** Pipeline submits `risk_pct=2.0` but `settings.PER_TRADE_RISK_PCT=5.0`\n**Fix:** Read from `signal` or `settings` dynamically\n\n### Missing Freshness Check\n**Symptom:** Stale signals from days ago are executed\n**Cause:** No timestamp validation before execution\n**Fix:** Check `(now - signal_timestamp).total_seconds() \u003C 300` before execution\n\n### Missing Market Check\n**Symptom:** Signal for symbol not on BingX is executed, causing order failure\n**Cause:** No verification that `BASE\u002FUSDT:USDT` exists in `exchange.symbols`\n**Fix:** Check market existence before risk check\n\n### Meme-Coin Accumulation\n**Symptom:** 19+ positions with >200% exposure\n**Cause:** Every Scout signal executes without concentration limits\n**Fix:** Emergency rebalancing + exposure monitoring\n\n### In-Memory State Loss\n**Symptom:** After restart, `demo_trader.positions` is empty, duplicate orders placed\n**Cause:** Positions only stored in memory, not persisted\n**Fix:** Reconciliation from `exchange.fetch_positions()` on startup\n\n## Deployment to CT106\n\nSee `references\u002Fcortexquant-ct106-deployment.md` for the full deployment procedure.\n\n## Production Audit\n\nTo audit a running CortexQuant install without modifying it, follow\n`references\u002Fproduction-audit.md` — the read-only method, evidence standard,\nand report shape for this system. Use it before any code changes.\n\n## References\n\n| File | Purpose |\n|------|---------|\n| `references\u002Fcortexquant-ct106-deployment.md` | CT106 directory layout, env loading, startup lifecycle, restart, verification checklist, agent-host→CT106 access recipe |\n| `references\u002Fproduction-audit.md` | Read-only audit method, evidence standard, and report shape |\n| `references\u002Fsignal-pipeline.md` | Stage-by-stage pipeline contract and decision-record schema |\n| `references\u002Fsignal-parser-maintenance.md` | How to tell \"parser broken\" from \"feed empty\" when auditing ingestion |\n| `references\u002Fquant-hq-orchestration.md` | Monitoring loop: decay → HMM → DSR → permission graph |\n| `references\u002Fdemo-trading-experiment.md` | Demo trader wiring, VST balance, live-with-demo tradeoffs |\n| `references\u002Flxc-operations.md` | Proxmox LXC file transfer, inspection, and debugging recipes |\n\n## User Workflow Preferences (Always-On)\n\n- **Do not trade stale signals.** Scout signals must pass the 5-minute freshness gate.\n- **Funding-outlier messages are a separate signal class.** Store raw, do NOT parse as Scout.\n- **Never convert meme-coin positions into \"features\".** Close them via BingX API.\n- **Reconcile on every startup.** Never start the experiment clock before reconciliation.\n- **Verify from PVE host, not localhost.** A CT can serve HTTP 200 on `127.0.0.1` but be unreachable from the network.\n- **Use systemd, not pkill+nohup.** `systemctl restart cortexquant` is the correct restart method.\n- **Use `pct exec \u003CCT> -- bash -c \"...\"`, not `pct enter`.** `pct enter` doesn't work well with `bash -c` and long commands.\n- **Use drop-in files for env vars.** `systemctl edit` fails without a TTY.\n- **asyncpg connections don't have `.commit()`.** Use SQLAlchemy or direct `execute()` for writes.\n- **Report exact details, not summaries.** Signal_id, symbol, direction, risk decision, order params, fill, P&L.\n\n### Rooms (12)\n| Room | Purpose |\n|------|--------|\n| QUANT_RESEARCH | Hypothesis generation |\n| WEIRD_EDGE | Anomalous edge detection |\n| MATH_SIGNAL | Mathematical analysis |\n| STRATEGY_EG | Strategy engineering |\n| REGIME_DETECTION | HMM regime identification |\n| BACKTEST | Historical backtesting |\n| OPTIMIZATION | Parameter optimization |\n| SELECTION | Portfolio selection |\n| RED_TEAM | Risk review, veto |\n| TRADING_JOURNAL | Performance logging |\n| AI_COACH | Agent quality analysis |\n| RISK_COMMITTEE | Risk oversight |\n\n### Pipeline (Loop, not Linear)\n\nBased on the RuujSs alpha engine article: Discovery → Validation → Deployment → Monitoring → Discovery.\n\nMonitoring feeds decay alerts and regime divergence back to research, closing the loop.\n\n### Agents (24)\n\n2 agents per room. Registered in `research_agents` table via `initialize()`.\n\n### Monitoring Layer (NEW)\n\nDecay detection, HMM regime, Deflated Sharpe Ratio, and permission graph.\nSee `references\u002Fquant-hq-orchestration.md` for details.\n\n### Permission Graph\n\nEnforces write\u002Fread access per room at the data level. Prevents research from writing APPROVED, etc.\n\n### Monitoring API\n\n- `POST \u002Fapi\u002Fquant-hq\u002Fmonitoring\u002Fcheck\u002F{id}` — full check (decay + regime + DSR)\n- `POST \u002Fapi\u002Fquant-hq\u002Fmonitoring\u002Fdecay-check` — rolling Sharpe decay\n- `POST \u002Fapi\u002Fquant-hq\u002Fmonitoring\u002Fregime` — HMM regime\n- `POST \u002Fapi\u002Fquant-hq\u002Fmonitoring\u002Fdsr` — Deflated Sharpe Ratio\n- `GET \u002Fapi\u002Fquant-hq\u002Fmonitoring\u002Fpermissions-matrix` — full permission matrix\n\n## External Signal Ingestion\n\n### Telegram Channels (Telethon MTProto)\n- Session at `.tgsessions\u002Fckp_scanner.session` (gitignored)\n- Parser extracts SYMBOL, DIRECTION, RSI15\u002F4H, TSI15\u002F4H, funding, divergence\n- Signals create ALTCOIN_SIGNAL_RECEIVED events → 10 rooms\n- `POST \u002Fapi\u002Ftg\u002Freparse` to re-run parser on all messages\n\n### Signal Classes\n\nCKPscanner emits **two distinct signal classes** that must NOT be mixed:\n\n| Class | Pattern | Action |\n|-------|--------|--------|\n| **Scout Opportunity** | `🔴\u002F🟢 Scout Opportunities LONG\u002FSHORT` + numbered `SYMBOL-USDT | RSI...` list | Parse, route to rooms, eligible for demo execution |\n| **Funding Outlier** | `Funding Alert - Outliers:` + `SYMBOL: funding=X%` | Separate future signal class — store raw, do NOT auto-convert to Scout |\n\nThe Scout parser's header regex (`🔴\\s*Scout\\s+Opportunities`) deliberately rejects funding-outlier messages. If you need a funding-outlier parser, build a separate `FundingOutlierParser` — never shim outlier detection into the Scout path.\n\n### Deduplication\n\nSignals are deduplicated by `dedup_key = f\"{channel_id}:{telegram_message_id}:{symbol}\"`. A parsed signal that fails validation is NOT marked `published_to_bus=True` — it will be re-attempted on the next publisher tick. Only mark published after successful routing to rooms AND demo execution (or explicit rejection with a recorded reason).\n\n## Operations Console\n\n- SSE at `\u002Fapi\u002Fquant-hq\u002Fevents` (heartbeat + audit_log)\n- State at `\u002Fapi\u002Fquant-hq\u002Fstate`\n- UI at `\u002Fconsole`\n\n## 12-Step Alpha Pipeline\n\nBefore a signal is eligible for execution, it must pass:\n\n1. Linear demeaning (remove drift)\n2. Variance estimation (realized vol)\n3. Return normalization (z-score)\n4. Time-series truncation (observation window)\n5. Cross-sectional demeaning (remove market bias)\n6. Final trimming (time horizon)\n7. Expected return estimation (forward-looking)\n8. Return normalization (vol-scaled)\n9. Residual extraction (factor orthogonalization)\n10. Signal weighting (inverse volatility)\n11. Weight normalization (|w| = 1)\n12. Combined signal construction\n\nImplemented in `src\u002Fquant_hq\u002Falpha_pipeline.py`.\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### Architecture\n\n```\ntg_publisher → FullPipeline.process_signal(signal_dict)\n  ├─ idempotency check (DecisionRecord.by signal_id)\n  ├─ market snapshot (OHLCV from Binance\u002FBingX)\n  ├─ ML prediction (MLPredictor)\n  ├─ strategy selection (StrategyEngine)\n  ├─ classical optimization (RiskfolioAdapter)\n  ├─ quantum optimization (QuantumSolver)\n  ├─ risk check (RiskEngine)\n  ├─ duplicate position check\n  ├─ BingX VST execution (demo_trader.process_signal)\n  └─ DecisionRecord persisted to database\n```\n\n### DecisionRecord Schema\n\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\n\nAlways check for existing DecisionRecord before processing. A signal that was rejected yesterday must not be re-processed on restart:\n\n```python\nexisting = await self._check_idempotency(signal_id)\nif existing:\n    return {\"status\": \"duplicate\", \"decision_id\": existing.id}\n```\n\n### API Routes\n\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## Reconciliation Procedure (On Startup)\n\nWhen the demo service restarts, internal position state is lost but BingX retains the real positions. Always reconcile before starting the background task:\n\n```python\n# Fetch exchange positions\npositions = await demo_trader.adapter.get_positions()\n\n# Sync to internal state\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            'stop_loss': None,  # BingX demo may not expose\n            'take_profit': None,\n        }\n```\n\nAdd this to `start_demo()` before `asyncio.create_task(_run_experiment())`.\n\n## Risk Config Mismatch Pitfall\n\nPipeline submits `risk_pct=2.0` but `settings.PER_TRADE_RISK_PCT=5.0%`. Result: every signal is rejected with \"Per-trade risk exceeds limit\".\n\nFix: align the pipeline's risk submission with `settings.PER_TRADE_RISK_PCT`, or override via `signal.get('risk_pct', settings.PER_TRADE_RISK_PCT)`.\n\n## Silent bug patterns (parser + risk)\n\n- **Loop-variable name collision.** A parser that assigns to `parsed_results` then loops `for p in parsed:` will NameError on the first successful parse. Grep the loop target against the assignment target whenever you touch a parse-then-iterate block — the two names drifting apart is the bug, not the parse logic.\n- **Scout message leading indentation.** CKPscanner list items are indented 2+ spaces (` 1. ALCH-USDT | ...`). A line pattern anchored at column 0 (`^(\\d+)`) misses every item. Anchor with `\\s*(\\d+)` or `.lstrip()` the line before matching.\n- **Risk position cap must not bind below the target.** `PER_TRADE_RISK_PCT=5.0` with a 2% stop requires 250% position size to hit — if `MAX_POSITION_SIZE_PCT=5.0`, the cap binds first and actual risk is 1%. Set `MAX_POSITION_SIZE_PCT` high enough that the cap only triggers on genuine concentration risk, not on the risk-target math.\n- **Demo RiskEngine refuses LIVE_TRADING.** The demo `RiskEngine` reads `PER_TRADE_RISK_PCT`, `MAX_POSITION_SIZE_PCT`, etc. — limits calibrated for VST. It MUST refuse to operate when `settings.LIVE_TRADING=True` and `settings.DEMO_TRADING=False` (raise in `__init__`, reject in `check_signal`). Never let demo risk limits gate a live trade.\n\n## Dashboard Panel Append Pattern\n\nTo add panels to `fleet.html` without breaking the existing layout:\n- Append new `\u003Cdiv class=\"panel\" style=\"flex:X\">` elements before `\u003C\u002Fmain>`\n- Match existing `.ptitle`, `.body`, `.panel` CSS classes\n- Do NOT rewrite the file wholesale — patch in place\n- SSE panels must reference real API endpoints, not placeholders\n\n## CKP Signal Format\n\nReal parsed signals from CKPscanner have this structure:\n\n```python\n{\n    \"signal_id\": \"CKP-676EB7F29132\",\n    \"symbol\": \"ALIGN\",\n    \"direction\": \"LONG\",\n    \"confidence\": 1.0,\n    \"timestamp\": \"2026-09-12T21:35:12+00:00\",\n    \"parser_version\": \"2.0.0\",\n    \"rsi\": None,\n    \"indicators\": {\n        \"rsi15\": 61.4,\n        \"tsi15\": 13.2,\n        \"rsi4h\": 42.31,\n        \"tsi4h\": -33.99,\n        \"bull_divergence\": 0.094\n    }\n}\n```\n\nNote: `rsi` is top-level; other indicators live in `indicators` dict. Always use `.get(\"rsi\") or 50` for fallback (key may exist with None value).\n\n## Pipeline Test Result Interpretation\n\nA `\"rejected\"` status is **correct behavior**, not a bug. The pipeline is working as designed when it rejects:\n- Low-cap tokens not on Binance (ALIGN\u002FUSDT not found)\n- Signals exceeding risk limits\n- Signals with stale timestamps\n- Signals for symbols with existing positions (duplicate check)\n\nDo not \"fix\" a rejection — verify the reason is correct. Only investigate if a clearly valid signal is rejected.\n\n## Adapter Isolation Pattern\n\nEach optional adapter MUST be loaded lazily with its own try\u002Fexcept:\n\n```python\ntry:\n    from src.ml.predictor import MLPredictor\n    self.ml = MLPredictor()\n    self.has_ml = True\nexcept Exception as e:\n    logger.warning(f\"ML adapter unavailable: {e}\")\n```\n\nOne failing adapter must not crash the pipeline. Log and continue with degraded capability.\n\n## Database Tables\n\n| Table | Purpose |\n|-------|--------|\n| `research_experiments` | Core experiment data |\n| `research_agents` | Agent registry |\n| `research_messages` | Inter-agent messages |\n| `research_tasks` | Task queue |\n| `research_audit_log` | Immutable audit trail |\n| `research_strategies` | Strategy versions |\n| `research_budget` | Budget tracking |\n| `research_memory` | Shared persistent memory |\n| `research_promotions` | Promotion history + vetos |\n| `tg_raw_messages` | Raw Telegram messages (immutable) |\n| `tg_parsed_signals` | Parsed signals |\n| `tg_backfill_checkpoints` | Backfill progress |\n| `tg_ingestion_metrics` | Channel health |\n| `demo_trades` | Demo trade records |\n| `experiment_runs` | 7-day experiment metadata |\n| `signal_validations` | 12-step results |\n| `execution_errors` | Error log |\n\n## Container Layout (Proxmox ninyi)\n\n| CT | Name | IP | Purpose |\n|----|------|----|--------|\n| 100 | adguard | 192.168.1.10 | DNS ad blocking |\n| 101 | nextcloud | 192.168.1.10 | File sync (NOTE: same IP as adguard — conflict) |\n| 102 | plex | dhcp | Media server |\n| 103 | hermes | 192.168.1.13 | Hermes Agent host |\n| 104 | odysseus | dhcp | |\n| 105 | cortexcloud | 192.168.1.15 | AI gateway, x402 payments |\n| 106 | cortexquant | 192.168.1.19 | Trading Intelligence Platform |\n| 107 | n8n | stopped | Workflow automation |\n| 108 | network-optimizer | 192.168.1.17 | UniFi Network Optimizer |\n\n## Access Pattern (Agent Host → CT106)\n\nThe agent host (`hermes@192.168.1.13`) **cannot route directly to CT106** (`192.168.1.19`) — different subnet. The only path is via the PVE host:\n\n```bash\n# Execute command inside CT106 from agent host:\nssh -o StrictHostKeyChecking=no root@192.168.1.11 'pct exec 106 -- bash -c \"\u003Ccommand>\"'\n\n# Pipe a script into CT106:\ncat \u002Ftmp\u002Fscript.py | ssh root@192.168.1.11 'pct exec 106 -- bash -s'\n\n# Install Python deps (system pip blocked by PEP 668):\nssh root@192.168.1.11 'pct exec 106 -- bash -c \"\u002Fopt\u002Fcortexquant\u002F.venv\u002Fbin\u002Fpip install \u003Cpkg>\"'\n```\n\n## Systemd Service Drop-in (bypass ML gate)\n\n`systemctl edit` fails without a TTY. Use the drop-in directory directly:\n\n```bash\n# Create drop-in to bypass ML validation gate (demo only):\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\nThe `MLPredictor.is_approved` property checks `os.environ.get(\"ML_SKIP_VALIDATION\")` and returns `True` when set. This lets the strategy engine use `momentum_ma` instead of `ckp_baseline` even when the model fails validation gates (R² \u003C 0, etc.).\n\n### Static IP Assignment\n\n```bash\n# Pin static IP (avoid DHCP drift)\nssh pve 'pct set \u003CCTID> -net0 \"name=eth0,bridge=vmbr0,hwaddr=\u003Cmac>,ip=192.168.1.X\u002F24,gw=192.168.1.1,type=veth\"'\nssh pve 'pct restart \u003CCTID>'\n```\n\nDHCP drift is silent — CT keeps old IP until reboot, then gets a new one. Always pin static IPs for externally-reachable services.\n\n## Deployment\n\nCT106 directory layout, env loading pattern, restart procedure: see `references\u002Fcortexquant-ct106-deployment.md`\n\nLoop architecture (decay → HMM → DSR → permission graph): see `references\u002Fquant-hq-orchestration.md`\n\nProcess management, file transfer, debugging: see `references\u002Flxc-operations.md`\n\n7-day experiment pre-flight, ML training, signal flow decision tree: see `references\u002Fdemo-experiment-runner.md`\n\n## LIVE_TRADING=false Always\n\nResearch agents isolated from execution credentials. No trades placed.\n\n## Risk Configuration (2026-09 update)\n\n| Setting | Old | New | Why |\n|---------|-----|-----|-----|\n| `PER_TRADE_RISK_PCT` | 2.0 | 5.0 | User-requested 5% per-trade risk target |\n| `MAX_POSITION_SIZE_PCT` | 5.0 | 50.0 | Old cap bound before risk target reached (2% stop needs 250% position to hit 5% loss); new cap only triggers on genuine concentration risk |\n\nThe `RiskEngine` guards `LIVE_TRADING` mode: raises in `__init__` and rejects in `check_signal` when `LIVE_TRADING=True` and `DEMO_TRADING=False`. Never remove this guard.\n\n## Reconciliation Overflow Pitfall\n\nThe startup reconciliation script creates `DemoTrade` DB rows for every open exchange position. If reconciliation runs when more than `MAX_CONCURRENT_TRADES` positions are open on the exchange (e.g., 5 positions vs 3 limit), the demo trader immediately hits `Max concurrent trades reached` and rejects **every** fresh Scout signal — even though some pre-existing positions are desirable (BTC, AVAX) and others are noise (BAS, ARC, EGLD).\n\n**Fix:** reconciliation must count existing positions against `MAX_CONCURRENT_TRADES` and only mark the oldest N as open; close (or skip) the rest. Or, explicitly close stale reconciliation artifacts via BingX API before starting the experiment clock.\n\n## Training on CT106 (lessons from 2026-09)\n\n- System pip is blocked by PEP 668 — always use `\u002Fopt\u002Fcortexquant\u002F.venv\u002Fbin\u002Fpip`\n- A training script that imports `src.*` pulls in `src.utils.config` → `pydantic-settings`, `src.utils.logger` → `python-json-logger`. These must be in the venv.\n- **Simpler:** write a standalone script with no `src.*` imports (only `ccxt`, `sklearn`, `pandas`, `numpy`, `joblib`). Pipe it in and run with the venv Python.\n- `GradientBoostingRegressor` on 365-day 1h OHLCV for BTC\u002FETH\u002FSOL\u002FAVAX yields R² ≈ -0.04 — no predictive power. The model is saved but fails validation. Use `ML_SKIP_VALIDATION=true` to bypass the gate for demo purposes, or improve features\u002Fmodel before relying on ML signals.\n\n## Dashboard Deployment Safety\n\n- **Verify from PVE host, not localhost.** A CT can serve HTTP 200 on `127.0.0.1` but be unreachable from the PVE host due to stale ARP tables, wrong subnet, or firewall. Always `ssh pve 'curl http:\u002F\u002F\u003CCT_IP>:8080\u002Fhealth'` after a dashboard change.\n- **Restart via systemd, not pkill+nohup.** Use `pct exec \u003CCT> -- systemctl restart cortexquant`. `pkill -9` + `nohup` bypasses systemd and can leave the service in a zombie state where restart throttling kicks in.\n- **Clear `__pycache__` after HTML\u002Ftemplate changes.** uvicorn with `--reload` may pick up file changes, but a running uvicorn without reload will serve stale cached templates. Restart + clear cache: `find \u002Fopt\u002Fcortexquant -name __pycache__ -type d -exec rm -rf {} +` then restart.\n- **Rebuild-and-deploy without preview = broken dashboard.** The reference-images workflow (rebuild from screenshots) is high-risk: a subagent can drop 2–5KB of existing functionality, change the file size, and break the live site. Always diff the rebuilt file against HEAD before deploying, and verify the deployed result reaches the PVE host before telling the user it's done.\n- **A subagent-built full HTML replacement is a delete-by-another-name.** Replacing `fleet.html` wholesale via a subagent (even from reference images) has broken the live dashboard multiple times — the server dies, the user reports 'Nothing is up' or 'unreachable', and the fix is `git checkout -- dashboard\u002Ftemplates\u002Ffleet.html` + systemd restart. The safe pattern is to PATCH the existing file (append new panels before `\u003C\u002Fmain>`, add CSS in the existing `\u003Cstyle>` block) rather than rewrite it. If a full rebuild is unavoidable, the subagent MUST: (1) preserve every existing CSS class and JS function, (2) keep the existing SSE\u002Fauth flow intact, (3) diff against HEAD to verify nothing was dropped, (4) push to a staging path first and verify HTTP 200 from PVE host before swapping in.\n\n## Pitfalls\n\n### Background Task Startup Ordering (uvicorn `await server.serve()` blocks forever)\n- In FastAPI with `uvicorn.Server.serve()`, any code AFTER `await server.serve()` never executes\n- Background tasks (demo experiment, Telegram scheduler) MUST be started BEFORE `await server.serve()`\n- Pattern: `demo_task = asyncio.create_task(supervised_demo_task())` before `await server.serve()`\n- The task reference MUST be retained for shutdown: cancel it in `shutdown_event` handler\n- If demo startup code runs after `serve()`, it will silently never start — no error, just no demo\n\n### BingX API Secret Required\n- BingX requires **both** API key AND secret for HMAC-SHA256 signing\n- Without secret → CCXT `AuthenticationError: bingx requires \\\"apiKey\\\" credential` (misleading — apiKey IS set)\n- Always verify both present before `BingXDemoAdapter.initialize()`: `if not api_key or not secret: raise RuntimeError(...)`\n\n### Demo Orchestrator `is_active` Bug\n- `DemoExperimentOrchestrator.start()` sets `self.is_running = True` but `demo_trader.is_active` stays False\n- The `demo_trader.start_experiment()` is called but doesn't set `demo_trader.is_active`\n- Fix: ensure `demo_trader.is_active = True` after `start_experiment()`\n\n### Publisher→Demo Bridge Gap\n- `tg_publisher.publish_pending()` routes signals to research rooms, NOT to `demo_trader.process_signal()`\n- To wire demo execution: after routing to rooms, also call `await demo_trader.process_signal(signal)` for each parsed signal\n- Without this bridge, demo trader never receives signals\n- Register the callback BEFORE `server.serve()` blocks: `tg_pub.set_demo_callback(demo_trader.process_signal)`\n\n### CCXT BingX Sandbox Mode\n- Must call `exchange.set_sandbox_mode(True)` after initialization\n- Without this, orders go to production (real money)\n- CCXT bingx has no `sandboxMode` attribute — use `getattr(exchange, 'sandboxMode', 'N\u002FA')` to avoid AttributeError\n- Verify with `exchange.urls['test']` vs `exchange.urls['api']`\n\n### BingX Demo Balance is VST (not USDT)\n- BingX VST demo accounts use VST (Virtual Stable Token), not USDT\n- Demo balance shows in `balance.get(\"VST\", {})` — NOT `balance.get(\"USDT\", {})`\n- A 0 USDT balance does NOT mean the account is unfunded — always check VST first\n- Verify with raw CCXT: `fetch_balance()` then inspect `bal.get(\"VST\", {}).get(\"total\", 0)`\n- The demo API endpoint must explicitly surface VST — if it only queries USDT, it will report 0 for a fully-funded demo account\n\n### Position Sizing (DEMO only)\n- Risk-driven size: `position_size = (balance * PER_TRADE_RISK_PCT \u002F 100) \u002F |entry - stop_loss|`\n- Hard cap: `position_size \u003C= balance * MAX_POSITION_SIZE_PCT \u002F 100 \u002F entry`\n- Take the MIN of the two. For a 2% stop, the cap binds first (1% actual risk); for a 10%+ stop, the risk target binds.\n- Final size is then multiplied by leverage for notional exposure.\n- Notional = position_size * price \u002F leverage (actual capital at risk)\n- **DEMO ONLY**: This formula uses `settings.PER_TRADE_RISK_PCT` (5%) and `settings.MAX_POSITION_SIZE_PCT` (50%) — VST-calibrated. `RiskEngine` refuses to operate in `LIVE_TRADING` mode. For live trading, a separate `LiveRiskEngine` with live-calibrated limits is required.\n- Never use `LIVE_TRADING` flag for position sizing — it's always False; use `DEMO_TRADING` for demo mode\n\n### `.get(key, default)` with `None` values\n- `signal.get(\"rsi\", 50)` returns `None` if `signal[\"rsi\"]` is `None` (key exists, value is null)\n- Use `signal.get(\"rsi\") or 50` to fall back when value is falsy\n- Common in JSON data from parsers — fields exist but are null\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. Never silently modify either value to make a trade go through.\n- **Treat rejections as integration tests.** A `\"rejected\"` status is a successful pipeline execution, not a bug. Verify the reason is correct. Only investigate if a clearly valid signal (major market, fresh timestamp, no duplicate, risk within limits) is rejected.\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\"` with `\"reason\": \"ml_untrained\"` or `\"low_confidence\"`. Never present a default strategy as an AI-selected one.\n- **Never treat default 0.5 confidence as a validated prediction.** Untrained ML models MUST return `{\"confidence\": 0.5, \"observation_only\": True}`. The pipeline MUST check `observation_only` before using any ML output for trading decisions.\n- **Synthetic e2e test mode is mandatory before any real trade.** Implement a `test_e2e()` method that runs the full pipeline WITHOUT placing orders. Verify: market resolution, ML handling, strategy selection, optimizer handling, risk approval, idempotency, persistence, and dashboard tracing. Run this first.\n- **Never allow an LLM to directly rewrite production trading code, bypass risk controls, or promote itself.** Improvement hypotheses must be evaluated through chronological walk-forward validation against the current model before promotion. The LLM proposes; the pipeline disposes.\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.** No new tools, no new adapters, no performance tuning until a real CKP signal has gone from Telegram → database → BingX order → decision record → dashboard.\n\n### BingX VST (Demo) Account Balance\n- BingX demo uses `VST` as the balance currency, NOT `USDT`\n- `fetch_balance()` returns `{'VST': {'free': 99693.0, 'used': 302.9, 'total': 99996.0}}` — NOT `USDT`\n- Access demo balance: `balance['VST']['total']`, NOT `balance['USDT']['total']`\n- **Always check raw CCXT response first**: `bal = exchange.fetch_balance(); bal.get('VST', {}).get('total', 0)`\n- A 0 USDT balance does NOT mean the account is unfunded — always check VST first\n- The demo API endpoint must explicitly surface VST — if it only queries USDT, it will report 0 for a fully-funded demo account\n\n### BingX Position Desync on Service Restart\n- `demo_trader.positions` is in-memory only — service restart loses all tracked positions\n- BingX exchange retains the real positions → desync: exchange shows 2 positions, internal state shows 0\n- **Fix**: On service startup, reconcile internal state from `exchange.fetch_positions()`\n- For each exchange position without a matching internal record, create the internal record\n- For each internal position not on exchange, mark as closed\n- Add this to `start_demo()` before the background task starts\n\n### Backtest Engine Validation\n- The walkforward engine is NOT broken — it correctly returns +9.47% on synthetic uptrend data and 0% on downtrend\n- A 0% win rate on real market data is NOT necessarily a bug — choppy\u002Fflat markets produce losing trades\n- **Always test with synthetic data first** to verify engine correctness before trusting real-market results\n- Use `run_strategy()` with known trending data to validate: uptrend should be positive, downtrend should be flat\u002Fnegative\n\n### Adapter Compatibility (Python 3.13)\n- VectorBT 1.1.0 fails with plotly 7.x ('mapbox' template removed) — wrap in try\u002Fexcept, set `available=False`\n- Riskfolio-Lib API changed: `rp_optimization` `l` kwarg renamed, `performance` attribute missing — use `getattr` with fallback\n- tsfresh 0.21.2 requires Python \u003C3.11 — use 0.21.1 for Python 3.13\n- alphalen fails to build on Python 3.13 — use pure pandas fallback for factor analysis\n- **Isolate each adapter behind try\u002Fexcept with availability flags** — one failing adapter must not crash the others\n\n### Subagent Long-Run Failure Pattern\n- Subagents on complex multi-file builds (adapters + quantum + ML + dashboard) can fail silently with \"Delegation owner exited before recording a terminal result\" or timeout\n- Mitigation: dispatch ONE focused subagent per concern (tools-only, quantum-only, ML-only) rather than a single mega-build\n- After dispatch, verify completion by checking `git status` and the expected file count — don't assume success from the dispatch returning\n- For mission-critical paths, follow up with a direct terminal audit (`ls src\u002Ftools\u002F`, `pytest tests\u002Ftest_tools.py`) rather than trusting the subagent report\n\n### Callback verification: in-process vs out-of-process\n- A Python script importing `demo_trader` creates a FRESH singleton — not the one the running FastAPI service holds\n- To audit the live state, use the API endpoints (`\u002Fapi\u002Fdemo\u002Fstatus`, `\u002Fapi\u002Fdemo\u002Fbalance`) or query the DB directly\n- A standalone script will show `demo_trader.is_active = False` even when the service has it active\n\n### Market Data Must Come From the Execution Exchange\n- **Pitfall**: The pipeline used Binance (`MarketDataFetcher`) for market snapshots, but execution is on BingX. Result: signals for coins listed on BingX but not Binance (e.g. PORTAL, KAVA, UMIA) were rejected with \"No market data\" even though they're perfectly tradeable.\n- **Fix**: Always fetch market data from `demo_trader.adapter.exchange` (BingX) first, fall back to Binance only if the symbol isn't on the execution exchange. Use the correct swap symbol format: `BASE\u002FUSDT:USDT`.\n- **Mechanism**: BingX has ~1,200 perpetual swap markets; Binance has ~1,800 spot. For a VST demo account, only BingX swap markets are tradeable. A signal for PORTAL exists on BingX (`PORTAL\u002FUSDT:USDT`) but not on Binance — the old code path rejected it.\n- The fix is in `FullPipeline._fetch_market_data()`:\n```python\nasync def _fetch_market_data(self, symbol: str) -> Optional[pd.DataFrame]:\n    # Try execution exchange (BingX) first\n    if demo_trader.adapter and demo_trader.adapter.exchange:\n        swap_symbol = f\"{symbol}\u002FUSDT:USDT\"\n        if swap_symbol in demo_trader.adapter.exchange.symbols:\n            ohlcv = await asyncio.to_thread(exchange.fetch_ohlcv, swap_symbol, \"1h\", limit=100)\n            # ... return df\n    # Fallback to Binance\n    return await self.market.fetch_ohlcv(f\"{symbol}\u002FUSDT\", \"1h\", limit=100)\n```\n\n### Subagent File-Mutation Limitation\n- Subagents cannot push files into CTs — the file-mutation verifier blocks it with \"1 file(s) were NOT modified this turn\"\n- **Workaround**: The parent agent must SCP files to the PVE host, then `pct push` into the CT, then verify with a marker grep\n- Pattern:\n```bash\nscp \u002Ftmp\u002Ffile.py pve:\u002Ftmp\u002Ffile.py\nssh pve \"pct push 106 \u002Ftmp\u002Ffile.py \u002Ftmp\u002Ffile.py\"\nssh pve \"pct exec 106 -- grep -q 'UNIQUE_MARKER' \u002Ftmp\u002Ffile.py && echo OK\"\n```\n- Never trust a subagent's claim of \"pushed to CT\" — verify with a direct terminal audit\n\n### venv pip Only (PEP 668)\n- System pip on CT106 hits PEP 668 externally-managed guard\n- Always use `\u002Fopt\u002Fcortexquant\u002Fvenv\u002Fbin\u002Fpython3 -m pip` or `\u002Fopt\u002Fcortexquant\u002Fvenv\u002Fbin\u002Fpip`\n- Background `nohup pip install` processes tend to hang — kill stuck PID and retry in foreground\n\n### BingX API Credentials Verified (2026-09)\n- Key: 2URgZJv3... (redacted in logs)\n- VST demo balance confirmed at ~100,000 VST\n- BingX perpetual swap symbols: BASE\u002FUSDT:USDT format\n- set_sandbox_mode(True) required; no sandboxMode attribute — use getattr\n\n### Deployment: `git stash -u` wipes untracked source files\n- When deploying NEW files to a remote target via tar\u002Fpush, never run `git stash -u` on the target. The `-u` (include untracked) flag deletes files that were never committed — which is exactly the code you just pushed.\n- Use plain `git stash` (tracked files only) or commit before stashing on a deployment target.\n\n### FastAPI route ordering: literal before path-param\n- `\u002Fapi\u002Fworkers\u002Fhealth` registered AFTER `\u002Fapi\u002Fworkers\u002F{worker_id}` will be captured by the param route, returning `{\"error\": \"worker not found\"}`.\n- Always register literal routes BEFORE path-param routes with the same prefix.\n\n### Pipeline stage ordering: promotions must verify the prior stage passed\n- A worker that advances an item to stage N+1 (e.g., RISK_REVIEW) MUST include the previous stage's pass condition (e.g., `red_team_result[\"verdict\"].astext == \"PASS\"`) in its query filter.\n- Without this, the gate is silently skipped and unvetted items flow through.\n\n### pytest-asyncio session-scoped event loop\n- Async tests with `pytest-asyncio` need a session-scoped `event_loop` fixture\n- Without it: `RuntimeError: no running event loop` on module-scoped async fixtures\n- Pattern: `@pytest.fixture(scope=\"session\") def event_loop(): loop = asyncio.new_event_loop(); yield loop; loop.close()`\n- Mark async tests with `@pytest.mark.asyncio`\n- Verify with: `python3 -m pytest tests\u002F -v`\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Ftrading-intelligence-platform\u002Ftrading-intelligence-platform","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 trading-intelligence-platform",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill trading-intelligence-platform",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill trading-intelligence-platform","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Ftrading-intelligence-platform\u002Ftrading-intelligence-platform\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",409,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Ftrading-intelligence-platform\u002Ftrading-intelligence-platform\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",[],[]]