# Cron Job: CryptoTradingBot Shadow-v2 24h Lerningsbericht

**Job ID:** 918d868cdc86
**Run Time:** 2026-06-12 12:16:56
**Schedule:** once in 24h

## Prompt

[IMPORTANT: The user has invoked the "algorithmic-trading-bot-safety" skill, indicating they want you to follow its instructions. The full skill content is loaded below.]

---
name: algorithmic-trading-bot-safety
description: "Safety-first engineering workflow for API-based algorithmic trading bots: dry-run gates, runtime state separation, journals, daily risk limits, kill switches, panic guards, and side-effect-free alert plans."
version: 1.0.0
author: Hermes Agent
license: MIT
metadata:
  hermes:
    tags: [algorithmic-trading, trading-bots, risk-management, hyperliquid, safety, dry-run, testing]
    related_skills: [test-driven-development, github-pr-workflow, finance-system-architecture]
---

# Algorithmic Trading Bot Safety Engineering

Use this skill when modifying, refactoring, reviewing, or deploying an API-based crypto/market trading bot, especially one that can place live orders on an exchange such as Hyperliquid.

## Core rule

Treat trading code as production-financial software. Default to **no live side effects** until safety boundaries are explicit, tested, and intentionally enabled.

When the user asks for a trading decision, live/autonomy recommendation, or live-trade status, answer like a portfolio/risk manager first, not like a developer: be concise, name one strategy, state live/no-live clearly, give evidence for/against, and avoid raw JSON, commit/build logs, process dumps, or implementation chatter unless explicitly requested. Routine trading reports should be short plain-language summaries with positions, PnL, stops/reconcile status, and a clear yes/no on whether the bot is currently profitable.

For tiny autonomous crypto live mode, use the gate/reporting pattern in `references/tiny-autonomous-live-gates-and-reporting.md`: final preflight must pass, Mainnet account and API-wallet credentials must be separated and validated, read-only reconcile must be clean, loss/reconcile/stop gates must fail closed, and normal mini-trades should be summarized in the daily report rather than spammed.

## Standard workflow

1. **Start from a clean branch**
   - Verify git status and current branch.
   - Work on a feature/safety branch.
   - Keep remotes token-free.

2. **Use TDD for behavior changes**
   - Write failing tests first for entry decisions, exit decisions, risk gates, journal metrics, alert formatting, and panic guards.
   - Keep exchange/network calls out of unit tests.
   - Prefer pure functions and small dataclasses for decisions.

3. **Separate runtime data from source code**
   - Keep logs, journals, account health, cooldowns, reports, CSV exports, and portfolio state out of Git.
   - Write runtime state under a user-local runtime directory, e.g. `~/.local/state/<BotName>/`.
   - `.gitignore` runtime artifacts aggressively.

4. **Centralize configuration**
   - Use a typed config object loaded from JSON/env.
   - Include explicit flags for:
     - `dry_run`
     - `tls_verify`
     - `runtime_dir`
     - max open positions/trades
     - max daily loss
     - max daily trades
     - cooldown period
   - Default `dry_run` to true.

5. **Add an execution boundary**
   - Wrap exchange calls behind a small executor.
   - In dry-run mode, return structured intended actions without calling the exchange.
   - In live mode, delegate to the exchange client.

6. **Keep strategy/risk pure and testable**
   - Extract entry logic into a pure strategy function returning an `EntryDecision`.
   - Extract exit logic into a pure strategy function returning an `ExitDecision`.
   - Extract risk gates into a separate function returning a `RiskDecision`.
   - Do not bury risk checks inside a large infinite loop if they can be tested independently.

7. **Implement hard safety gates**
   - Kill-switch file blocks new entries.
   - Daily loss limit blocks new entries once realized PnL breaches threshold.
   - Daily trade limit blocks new entries after the configured count.
   - Panic-close requires an exact wallet-specific confirmation string.

8. **Journal every trading decision**
   - Append JSONL events for entry/exit.
   - Include UTC timestamp, event type, coin, side, price, size, dry-run flag, reason, realized PnL when known, and structured extras.
   - Daily metrics must ignore dry-run events when calculating live realized PnL.

9. **Plan alerts before sending them**
   - Build side-effect-free alert plans first.
   - Assert alert plans have `side_effects=()` in tests.
   - Ensure alert text never contains credentials, API keys, private keys, raw wallet secrets, or token paths.
   - Only after the plan boundary is green should a Telegram/email adapter perform actual sending.
   - For Telegram topic bots, require an explicit thread/topic ID before sending; missing topic ID should skip/fail closed.

10. **Prefer paper trading before live strategy work**
   - Add a paper exchange/executor that matches the subset of the real exchange interface the bot uses (`set_leverage`, `create_order`, `fetch_positions`).
   - Persist paper state under the runtime directory, not Git.
   - Keep live market-data reads separate from order execution so the bot can use live prices with simulated fills.
   - Distinguish `dry_run` from `paper_trading`: dry-run means no execution at all; paper trading means execution is allowed but lands in local paper state.

- Collect market context for strategy learning, not blind execution
- Before moving from toy paper sizes to a planned live wallet, add wallet-aware risk-based position sizing: derive notional from wallet equity, risk-per-trade percent, stop distance, leverage caps, margin/notional caps, and journal the sizing decision. See `references/risk-based-position-sizing.md`.
- During paper-trading runs, collect chart/exchange context into runtime JSONL separate from the trade journal.
    - Include indicators such as RSI-14, SMA fast/slow, ATR-14, Bollinger bands, VWAP, funding, open interest, volume/liquidity, and derived tags.
    - Track source/reliability metadata for every context source; news, listings, social, or rumor-like signals are context only until measured against outcomes.
    - Correlate each paper/live trade to the most recent preceding context snapshot and score tags/sources by hit rate, average return, drawdown, time-in-trade, and exit reason.
    - With fewer than ~5 closed paper trades, report observations only; do not recommend strategy changes from tiny samples.

12. **Supervise paper runs as experiments**
    - Start long-lived paper bot processes under managed background process tooling, then verify the startup mode from runtime logs before reporting success.
    - For multi-strategy paper fleets, do not rely on a launcher that starts child processes and exits; keep a long-lived supervisor parent or tracked background process so VM/session restarts do not silently leave `0` bots running.
    - After a VM/network interruption, check actual process count, recent log mtimes, and exchange connectivity before interpreting missing trades as a strategy signal.
    - If exchange market-data/API access is degraded during paper/live-preview learning runs, fail closed at the runtime iteration boundary: report `status=degraded`, journal health and blocked shadow signals with `api_degraded`, create no entries/fills/order intents, and do not weaken live gates. See `references/hyperliquid-paper-api-degraded-fail-closed.md`.
    - Pair a silent/script-only market-context collector with a slower LLM-backed analyst monitor that reports to the correct trading topic.
    - Monitor jobs must fail safe: no live orders, no config/code changes, and no strategy tuning without explicit user approval. For paper-only fleets, a watchdog may alert or restart only after explicitly verifying mode flags remain paper-only.
    - Prefer a read-only dashboard after journal/context/correlation are stable; dashboards should inspect runtime state only and never place orders or mutate config.
    - See `references/paper-fleet-supervisor-watchdog.md` for a concrete supervisor/watchdog pattern and restart-status checklist.

13. **Run strategy tournaments as isolated paper/backtest portfolios**
    - When comparing old Git strategies, reconstruct parameter presets instead of running historical commits directly.
    - Group near-duplicate commits into strategy families and label hand-picked challengers as candidates.
    - Give every strategy its own runtime directory, paper state, journal, metrics, logs, and PID file under `~/.local/state/<Bot>/experiments/<strategy_id>/`.
    - Include `strategy_id` in every journal event so tournament metrics and context correlation can separate outcomes.
    - Before launching parallel bots, cap API load: filter exchange-internal pseudo-symbols (for example `@123`), stablecoins, malformed symbols, blacklists, and illiquid assets; use a liquid whitelist and `max_scan_coins` for live paper runs.
    - Cache expensive baseline/indicator requests, set request timeouts, throttle repeated error logs, and use unbuffered logging for background processes.
    - Rank by risk-adjusted metrics (expectancy, drawdown, profit factor, win rate, time-in-trade) and keep reports observation-only for tiny samples.
    - When live paper signals are rare, add a side-effect-free historical replay layer with walk-forward segments, per-coin attribution, exit-reason stats, coin-leakage checks, and small parameter sweeps around the current champion.
    - When paper bots produce zero trades, add near-miss telemetry before loosening thresholds: record closest rejected signals, trigger distance, reject reason, and strategy ID into runtime JSONL, then surface it in the read-only dashboard.
    - Do not overfit only to previous bot versions: add an independent strategy lab with tested archetypes (for example momentum breakout, RSI mean reversion, trend pullback, volatility-squeeze breakout) and rank them against the same cached candles before promoting any candidate.
    - If the user wants to explore non-mean-reversion approaches, add a separate paper-only strategy-family sampler rather than stretching the flash-crash entry path. Use a `strategy_family` dispatch, family-specific config/env mappings, replay parity tests, and research-only dashboard labeling; see `references/non-drop-strategy-samplers.md`.
    - When prior human/AI development notes contain durable trading lessons, encode them as explicit paper-only candidate constraints and regression tests (for example short dead-fish exits, hard unlevered stops, early break-even snap), not as live settings.
    - Make long-horizon replay data quality explicit: handle API rate limits with bounded retry/backoff, use stale-cache fallback only with reporting, and mark missing/fresh/stale coin coverage.
    - Promote sweep winners only as new paper-only candidate presets; never live-trade from replay alone.
    - Add read-only dashboards after journals/reports exist; dashboards may inspect runtime state but must not place orders, mutate config, or restart bots. If the user needs phone/PC access, serve only the runtime reports directory over the Tailscale IP and make the static dashboard refresh explicit.
    - For long-running paper fleets after VM/network restarts, add a script-only hourly watchdog that is silent when healthy, verifies exact expected strategy IDs and paper-only env flags, avoids restart thrashing when the exchange API/DNS is down, and restarts only the focused paper fleet when processes are missing/unsafe/unexpected. Before enabling the watchdog, remove scorecard-blocked strategy IDs from the running fleet rather than wasting scan/API capacity on known losers. Use a canonical focused runner outside Git, verify actual child process environments, and probe Hyperliquid `/info` with a JSON POST such as `{"type":"meta"}` rather than a bare GET. When pruning a noisy fleet into a focused paper set, patch the runner, watchdog, and monitor prompt together, run the runner, regenerate the read-only scorecard, and remove any initially selected strategy that the latest scorecard marks Blocked. See `references/paper-fleet-watchdog-and-focused-strategies.md`, `references/focused-paper-fleet-repair.md`, and `references/focused-paper-fleet-pruning.md`.
    - Before live-preview/live discussion, dashboard open exposure as well as closed trades: open count, unrealized PnL, notional, margin, leverage, entry/current price, and strategy ID. Persist enough paper/live position metadata (`entryTs`, `highPrice`, `atrSlPx`, `beActive`, `trailingActive`) so restarted bots can recover exit state; conservatively reconstruct legacy positions and log throttled warnings. See `references/open-position-dashboard-restart-state.md`.
    - For Hyperliquid v76 live-preview hard gates, prove Mainnet read-only reconciliation, expanded market context/DataQualityGate, API health/degraded mode, testnet ALO+Cancel, scheduleCancel, Fill+Stop, NonceManager/API-wallet isolation, and final preflight before any live-preview recommendation. Keep scorecard verification VM-safe: use a journal-only fast path with `--max-bots`, short timeouts, and isolated terminal commands rather than full dashboard snapshots or chained monster commands. See `references/hyperliquid-v76-hard-gates-and-vm-safe-verification.md`.
    - After Testnet execution is technically proven but live-preview is still blocked, run v76 as a **paper-runtime learning harness** instead of weakening live gates: Mainnet market data read-only, local `PaperExecutor`, strict and research-probe variants, `signal_journal.jsonl` for every blocked/accepted signal, replay/ablation against old paper journals, and a v76 learning block in the fast scorecard. Research-probe variants must be marked paper-only/research and never auto-promoted to live. See `references/hyperliquid-v76-paper-runtime-learning-harness.md`.
    - Before any Hyperliquid signed smoke, validate the account-vs-agent credential model: `HL_ACCOUNT_ADDRESS` is the funded account/subaccount and SDK `account_address`; `HL_AGENT_PRIVATE_KEY` is the signer; `HL_AGENT_WALLET_ADDRESS` must exactly match the address derived from the agent private key; account and agent addresses must differ. Read-only reconciliation may run with only the account address and should report credential warnings with `private_key_used=false`, but `scheduleCancel`, ALO+Cancel, Fill+Stop, and live signed paths must fail closed until the agent-wallet check is green. See `references/hyperliquid-agent-wallet-credential-gate.md`.
    - When promoting a proven paper strategy toward **tiny autonomous live**, use a dedicated final preflight mode rather than generic live-preview. Hard-block on any red gate other than exchange-volume-only conditional `scheduleCancel`: signed mainnet credential consistency, clean read-only reconcile/no open exposure, API/DataQualityGate green, kill-switch off, daily/weekly/loss-streak gates active, reconciler active, real alert delivery proven, legacy live paths blocked, testnet forced-signal Fill+Stop clean, net paper scorecard gates green, and no mainnet order before final launch. If signed credentials are inconsistent, do not start even a tiny order. See `references/tiny-autonomous-live-gating.md`.
    - Once those final gates are green, do **not** improvise by calling a low-level executor directly. Build/start a minimal autonomous live runtime runner with shadow-by-default mode, explicit live env gate, persistent runtime state/nonce/signer lock, strategy-pure `OrderIntent` generation, live-only exchange side effects, immediate reduceOnly stop placement after fill, and post-start reconcile. Load runtime `open_entries` into the generic watchdog/reconciler so the first live position is not falsely flagged as `exchange_position_without_local_journal`. Split strict **start preflight** from **ongoing runtime gates**: `no_open_positions_or_orders_before_start` must block initial launch, but after launch managed positions with confirmed reduceOnly stops may continue and add entries up to configured max exposure. At each loop, prune local `open_entries` for coins no longer present on exchange before reconcile/preflight so stale local journals do not block healthy managed exposure. Add profit protection before claiming the live runner can “let winners run”: preserve initial stop distance, then manage break-even, profit-lock, trailing-stop, and dead-fish exits before scanning new entries; submit tighter reduceOnly stops before canceling older looser stops. See `references/tiny-autonomous-live-runtime-runner.md`.
    - If live trade history shows repeated negative closes or the user says most trades are losing, treat it as an **edge failure**, not a leverage/sizing problem: verify stops, stop/pause new entries, activate kill-switch or block-new-entries, analyze round-trip PnL/fees/holding-time buckets/coin attribution, and require a fresh positive shadow/paper sample before restarting live. Keep reports short and plain-language; see `references/live-trade-history-review-and-pause.md`.
    - When a shadow/paper run is roughly directionally right but net-negative after fees, create a new paper-only challenger rather than tweaking live settings: add a fee-aware entry hurdle, funding carry filter, anti-chase/overextension gate, separate runtime directory, and mark-to-market treatment for open positions before evaluating profitability. See `references/fee-funding-aware-shadow-v2.md`.
    - Separate Hyperliquid read-only credential checks from signed-action checks. Read-only reconciliation needs only `HL_WALLET_ADDRESS` and should warn, not fail, on `API Key`/private-key mismatch; signed Testnet probes may derive the signer from `HL_API_PRIVATE_KEY`, but Mainnet signed actions stay blocked. Use a masked credential matrix and no-position Testnet `scheduleCancel` probe before any order-path smokes. See `references/hyperliquid-env-separation-and-credential-probes.md`.
    - When the user clarifies the target as autonomous portfolio management rather than per-trade approval, keep live orders blocked until explicit live-autonomy approval, but design operations around hard risk limits, reconcile-first supervisors, critical-only immediate alerts, and a daily 19:00 Switzerland digest instead of mini-trade chat spam. See `references/autonomous-hyperliquid-operations-mode.md`.
    - Dashboards/scorecards must not trust `bot.pid` plus `os.kill(pid, 0)` alone for `running=yes`: stale PID files can point to unrelated reused PIDs. Verify `/proc/<pid>/environ` matches the exact `CTB_STRATEGY_ID`, `CTB_RUNTIME_DIR`, `CTB_PAPER_TRADING=true`, and `CTB_DRY_RUN=false`, and add a regression test using the current test-process PID as a reused stale PID. See `references/dashboard-process-identity.md`.
    - When the user asks for paper-bot status, trend, adjustments, or how much longer/margin before live, run a compact status review: verify process liveness and paper/live env flags, run tests if readiness is discussed, aggregate per-strategy journals, compute win rate/profit factor/PnL/coin distribution, and count true open exposure only from non-zero contracts rather than merely from `positions` keys. See `references/paper-status-review-playbook.md`.
    - After open-position dashboarding exists, add a read-only live-readiness scorecard before discussing live preview. Score each strategy on closed-trade sample size, win rate, profit factor, realized + unrealized PnL, max drawdown, consecutive losses, coin leakage, average journaled risk, and explicit blockers. Gate statuses as Research / Candidate / Live-preview-ready / Blocked; keep tiny samples and `research-sampler` presets in Research even when one trade looks excellent. See `references/strategy-readiness-scorecard.md`.
    - When paper bots make zero trades, diagnose market selectivity before changing thresholds: check process liveness, log ticks, journal count, recent rolling drawdowns versus trigger thresholds, and add near-miss telemetry before launching any looser paper-only sampler.
    - When reviewing a 24h shadow/paper run, always separate closed net PnL from open exposure, mark open positions to current exchange price, compute fee drag/gross-vs-net, and estimate funding only as a small filter unless the system is explicitly funding-arbitrage. Do not call a run profitable when unclosed positions would make it negative. See `references/shadow-run-fee-funding-review.md`.
    - When adding indicator expansion packs, keep each family as a pure entry function with tests and a visible `strategy_family` preset: trend-pullback SMA/VWAP, Bollinger+RSI mean reversion, confirmed squeeze breakout, and multi-day trend investment should remain `paper-only`, `research-sampler`, `not-champion` until replay + live-paper scorecards mature.

    - Paper alerting must be mode-aware: `dry_run=False` + `paper_trading=True` is `[PAPER]`, never `[LIVE]`, because paper execution intentionally simulates fills without exchange orders.
    - When the eventual live wallet size is known, do not treat current small paper notional as future live size. Add a pure position-sizing layer and replay/live parity around `wallet_equity_usdc`, `risk_per_trade_pct`, stop distance, leverage, margin caps, and notional caps; journal `notional_usd`, `margin_usd`, `risk_usd`, `stop_distance_pct`, and `sizing_cap` on entries. See `references/risk-based-position-sizing.md`.
    - When adding looser samplers, keep them isolated from champion presets: tag them `paper-only`, `research-sampler`, `not-champion`, make trade size small, keep hard stops/dead-fish timers tight, label them visibly in the read-only dashboard, and treat their results as data collection only; see `references/paper-signal-samplers.md`.
    - When a strategy/user describes crashes or stops in ROE terms (for example "15% crash") and coins use different leverage, normalize thresholds per coin: `required_unlevered_drop = max(strategy_flash_trigger_pct, target_roe_pct / coin_leverage)`. Record near-misses with leverage, ROE-equivalent drop, required drop, distance-to-entry, and reject reason before loosening thresholds.
    - For paper-only signal samplers that intentionally loosen entry thresholds, verify ROE normalization does not silently re-tighten them on low-leverage coins. Set sampler-specific `crash_roe_trigger_pct` so `target_roe_pct / coin_leverage` equals the intended unlevered trigger, map that field through launch/runtime environment, and add failing tests that assert `effective_required_drop_pct()` preserves the sampler thresholds for representative low-leverage coins such as WLD/HYPE.
    - For crash-frequency questions, count distinct threshold-crossing events over rolling windows, report per-coin data coverage, and flag coin leakage when events cluster in one/two alts; see `references/leverage-aware-crash-telemetry.md`.
    - See `references/strategy-tournament-pattern.md` for the full tournament pattern.
    - See `references/replay-leakage-parameter-sweep.md` for replay/leakage/sweep details.
    - See `references/replay-data-quality-dashboard.md` for robust candle fetching and read-only dashboard patterns.
    - See `references/crypto-strategy-lab-and-survival-lessons.md` for independent strategy-lab screening, flash-crash survival lessons, V64-style candidate constraints, and launcher interpreter invariants.
    - See `references/paper-fleet-watchdog-and-strategy-lab.md` for the concrete hourly paper-fleet watchdog pattern plus the TDD/replay pattern for adding a liquidation-reversal lab archetype.
    - See `references/strategy-lab-expansion-archetypes.md` for adding independent side-effect-free lab families such as relative-strength rotation, risk-managed trend-following, and Donchian/volume breakout, including RED/GREEN tests, grid coverage, replay reporting, and conservative non-promotion gates.
    - See `references/defensive-strategy-lab-filters.md` for tightening promising replay archetypes before paper promotion: ATR/chop guards for trend-following, market-breadth/cash guards for relative-strength rotation, grid coverage tests, and replay interpretation.
    - See `references/relative-strength-paper-promotion.md` for promoting a cross-sectional/relative-strength replay winner into a conservative paper-only candidate, including market-history parity, process-env verification, and read-only scorecard reporting.
    - See `references/non-drop-strategy-samplers.md` for adding separate paper-only strategy-family samplers such as volatility squeeze breakout, including config/env mappings and replay/live parity pitfalls.
    - See `references/paper-dashboard-and-near-miss-telemetry.md` for Tailscale read-only dashboard serving, static refresh loops, and zero-paper-trade / near-miss diagnostics.
    - See `references/open-position-dashboard-restart-state.md` for open-position exposure dashboards, unrealized PnL calculation, and restart-state recovery for active positions.

14. **Verify before committing/pushing**
    - Run unit tests.
    - Run Python compile checks.
    - Scan for unsafe patterns such as `verify=False`, `except Exception: pass`, stale hardcoded workspace paths, and token-bearing remotes.
    - Commit with a conventional message.
    - Push with token-safe askpass handling; if PR API returns 403 but push succeeds, provide the manual PR URL.

## Pitfalls

- **Live order paths hidden inside strategy code**: separate strategy decisions from execution.
- **Dry-run that still calls the exchange**: dry-run must not call `create_order`, `market_open`, or `set_leverage`.
- **Negative live expectancy after launch**: immediately pause new live entries/activate kill-switch, analyze real trade history, and require a fresh paper/shadow recovery gate before restart (for example: >=30 closed paper trades, positive total PnL, positive last-20 PnL, winrate >=45% or profit factor >=1.25, and no dominance by <15m scalps).
- **Runtime logs committed to Git**: trading logs and journals can contain sensitive financial data.
- **TLS disabled for convenience**: do not use `verify=False` or `ssl.CERT_NONE` unless explicitly configured and documented.
- **Silent exception handling**: replace `except Exception: pass` with bounded logging.
- **Panic-close without confirmation**: emergency scripts need explicit, wallet-specific confirmation to prevent accidental liquidation.
- **Alerting as hidden side effect**: build alert plans first, then wire actual senders behind an explicit flag/adapter.
- **Telegram alerts sent to the wrong place**: require explicit chat ID and topic/thread ID; fail closed when topic ID is missing.
- **Multi-strategy monitors reading only root runtime paths**: tournament/paper runs store per-strategy logs, journals, PIDs, and paper state under `runtime_dir/experiments/<strategy_id>/`; cron monitors and dashboards must aggregate those experiment paths, not just `runtime_dir/Tradeanalyse`.
- **Runner/watchdog/monitor drift**: when focusing or pruning a paper fleet, update the canonical runner, watchdog expected list, and cron/LLM monitor prompt in the same change. If they disagree, healthy paused strategies get reported as failures or watchdogs restart intentionally stopped losers.
- **Keeping a newly checked Blocked strategy**: after pruning recommendations, regenerate the scorecard before finalizing. If a candidate in the proposed focused set is now `Blocked` due to poor profit factor, negative PnL, high drawdown, or coin leakage, remove it from the running focused fleet unless the user explicitly wants it as a research sampler.
- **Topic bleed from previous sessions**: in a Telegram topic/chat dedicated to the trading bot, do not pivot to unrelated repositories or tasks from adjacent session recall. If the user asks for status, answer the CryptoTradingBot status first and only use trading-bot context.
- **Developer-log reflex during trading decisions**: when the user asks for a trader/portfolio/risk-manager decision, give a concise trading recommendation, assumptions, risks, and gates. Do not lead with commit lists, implementation logs, or long engineering narration unless explicitly requested.
- **Manual-approval trap for autonomous trading**: after the user defines an autonomous-but-risk-bounded target mode, do not keep recommending approval for every mini-trade as the permanent operating model. Build/verify hard preflight, limits, watchdogs, and reporting so autonomy can be granted once safely, while still blocking when gates fail.
- **Developer-log overload when a trading decision is requested**: if the user asks for a professional trader/risk-manager recommendation, do not lead with commits, modules, long technical status, or build logs. Answer with strategy choice, trading logic, realistic scenarios, current evidence, blockers, next risk-bounded stage, and one explicit recommendation; keep code details in journals unless asked.
- **Confusing dry-run with paper trading**: dry-run should not create even simulated orders; paper trading requires dry-run off and a paper exchange on.
- **Heavy scorecard commands destabilizing the VM**: do not run full dashboard snapshots just to refresh paper scorecards, and do not chain scorecard + grep + preflight + exchange smokes into one terminal command. Prefer journal-only fast scorecard paths, `--max-bots`, short timeouts, and separate evidence commands.
- **Hyperliquid SDK `status=err` mistaken for success**: order/schedule/cancel calls can return structured responses with `status: "err"` even when the Python call itself does not raise. Testnet smoke tools must mark these gates red, journal the exchange response, and avoid reporting `ok` unless the exchange response itself is successful.
- **Testnet wallet not registered**: `User or API Wallet ... does not exist` on Hyperliquid testnet means the provided signer/address is not usable for that testnet proof. Do not weaken gates or call it a tool failure; ask for a dedicated registered testnet API wallet/address and keep Mainnet untouched.
- **Confusing account and agent wallet credentials**: Hyperliquid Info/read-only calls should use the funded account/subaccount address, while signed calls use the API/agent private key plus `account_address` set to the funded account. If the address derived from the agent private key does not exactly match the configured agent wallet public address, block all signed smokes. Keep read-only reconciliation separate so it can still inspect the account without touching the private key.

- **Context overload becomes false confidence**: collect indicators/news/listing/social context with tags and source metadata, then score reliability against actual paper/live outcomes before using it in strategy.
- **Auto-adjusting strategy too early**: with fewer than ~5 closed paper trades, collect data and state hypotheses only; do not tune parameters from anecdotes.

## Reference patterns

- `references/hyperliquid-bot-safety-refactor.md` — concrete pattern from a Hyperliquid bot hardening session: config, dry-run executor, runtime paths, journal metrics, risk gate, panic guard, and PR-token caveat.
- `references/market-context-paper-trading.md` — pattern for adding chart indicators, funding/open-interest context, source tags, reliability tracking, and dashboard-ready runtime files during paper-trading strategy development.
- `references/paper-run-supervision.md` — pattern for launching, monitoring, and analyzing managed paper-trading runs with collector/analyst cron jobs and a read-only dashboard boundary.
- `references/paper-fleet-watchdog-and-focused-strategies.md` — pattern for focusing a multi-strategy paper fleet after scorecard results and adding an hourly silent script-only watchdog that restarts only safe paper processes.
- `references/hybrid-paper-strategy-consolidation.md` — pattern for turning paper-trade learnings into a new paper-only hybrid challenger, including module selection, falling-knife gates, coin-leakage controls, launcher/watchdog updates, and verification.
- `references/trading-bot-concept-report-and-drive-delivery.md` — pattern for producing an outsider-readable AutoTradingBot concept/live-readiness report from current runtime evidence, including process/test/scorecard verification, coin-leakage interpretation, and Google Drive delivery via `gog` with verified artifact IDs.
- `references/hyperliquid-v76-live-preview-architecture.md` — pattern for migrating the legacy monolithic Hyperliquid `AutoTrader.py` into a safe v76 live-preview `src/` architecture with pure `OrderIntent` strategies, SDK executor boundaries, risk gates, reconciliation/missing-stop checks, and TDD verification.
- `references/hyperliquid-v76-technical-proof-pattern.md` — phase-by-phase proof workflow for v76: legacy live guards, read-only Hyperliquid adapters, payload/testnet dry-run smokes, reconciliation, paper cost/scorecard net metrics, and verification checklist.
- `references/hyperliquid-env-separation-and-credential-probes.md` — env-specific Mainnet/Testnet credential loading, read-only vs signed validation modes, masked credential matrix output, and safe Testnet-only legacy credential probes.
- `references/hyperliquid-testnet-agent-wallet-smoke-gates.md` — Testnet agent-wallet credential validation, scheduleCancel volume-limit interpretation, ALO+Cancel proof, Fill+Stop cleanup, reduceOnly protection recognition, and final reconcile checklist.
- `references/hyperliquid-testnet-strategy-harness.md` — Pattern for pushing a pure v76/strategy candidate through real Testnet execution with forced `OrderIntent`, PretradeRiskGate/DataQualityGate, reduceOnly stop reconciliation, cleanup, bounded natural-signal sessions, Mainnet-paper-only parallel tracking, and Telegram alert smoke reporting.
- `references/tiny-autonomous-live-runtime-runner.md` — Minimal safe Mainnet autonomous runner pattern after final preflight: shadow mode, explicit live env gate, persistent runtime state/nonce/signer lock, pure strategy intents, live-only side effects, immediate reduceOnly stop confirmation, watchdog state integration, and post-start verification.
- `references/live-trade-history-review-and-pause.md` — Pattern for responding when live trade history shows repeated negative closes: pause entries, keep protected stops, compute round-trip/fee/holding-time/coin attribution, and move strategy changes back to shadow/paper before restarting live.
- `references/crypto-trader-idea-testing-and-reporting.md` — Pattern for proactively proposing/testing professional crypto-trading ideas in paper/shadow mode, using market-regime long/short logic, concise user reporting, and evidence gates before restarting live.

The user has provided the following instruction alongside the skill invocation: [IMPORTANT: You are running as a scheduled cron job. DELIVERY: Your final response will be automatically delivered to the user — do NOT use send_message or try to deliver the output yourself. Just produce your report/output as your final response and the system handles the rest. SILENT: If there is genuinely nothing new to report, respond with exactly "[SILENT]" (nothing else) to suppress delivery. Never combine [SILENT] with content — either report your findings normally, or say [SILENT] and nothing more.]

Erstelle einen kurzen deutschen Status-/Lerningsbericht zum CryptoTradingBot Shadow-v2 Paper Run. Kontext: Repo `/home/agent/projects/CryptoTradingBot/Crypto_Agent`, Runtime `runtime/experiments/market_regime_shadow_v2`, Hintergrundprozess wurde mit `CTB_PAPER_TRADING=true CTB_DRY_RUN=false CTB_SHADOW_RUNTIME_DIR=runtime/experiments/market_regime_shadow_v2 .venv/bin/python -m src.tools.market_regime_shadow_trader --iterations 1440 --interval-seconds 60 --json` gestartet. Aufgabe: 1) Prüfe Prozess/Runtime-Dateien read-only. 2) Aggregiere `trade_journal.jsonl`, `signal_journal.jsonl`, `state.json`: closed trades, win/loss, realized PnL, unrealized/open positions wenn möglich anhand aktueller Hyperliquid mids, Profit Factor, wichtigste Reject-Reasons, Funding- und Fee-Learnings. 3) Beurteile klar: live ja/nein. 4) Nenne konkrete nächste Strategieanpassung, aber ändere nichts ohne Auftrag. Kurz, plain German, keine raw JSON/log dumps, keine Secrets. Wenn keine Trades entstanden sind, erkläre ob der neue Filter zu selektiv war oder Markt choppy war und welche Near-miss Daten fehlen.

## Response

**CryptoTradingBot Shadow-v2 Paper Run – Kurzstatus**

- **Prozess:** aktuell **nicht laufend**. Die PID-Datei ist vorhanden, aber der Prozess existiert nicht mehr.  
- **Runtime:** `market_regime_shadow_v2` enthält nur `state.json` und `bot.pid`; `trade_journal.jsonl` und `signal_journal.jsonl` fehlen.
- **Letzter Runtime-Stand:** `state.json` wurde zuletzt ca. **00:48** aktualisiert; der gestartete 24h-Run scheint also nicht sauber bis zum Ende weitergelaufen zu sein.

**Trading-Ergebnis**

- **Closed Trades:** 0  
- **Wins/Losses:** 0 / 0  
- **Realized PnL:** 0 USDC  
- **Offene Paper-Positionen:** keine  
- **Unrealized PnL:** nicht vorhanden, da keine offenen Positionen  
- **Profit Factor:** nicht aussagekräftig / 0, weil keine abgeschlossenen Trades

**Warum keine Trades?**

Der aktuelle Marktcheck ergibt **choppy / gemischt**: BTC und ETH sind kurzfristig über 1h-EMAs, aber die 4h-Struktur ist noch nicht sauber bullisch. Der Shadow-v2-Runner scannt Coins nur, wenn das Regime **nicht choppy** ist. Deshalb ist sehr wahrscheinlich der **Regime-Filter zu selektiv für gemischte Marktphasen**.

Wichtig: Weil bei choppy Regime offenbar gar keine `signal_journal.jsonl` geschrieben wurde, fehlen Near-miss-Daten. Dadurch lässt sich nicht sauber sagen, welche Coins knapp gescheitert wären oder ob Fee/Funding-Filter zusätzlich blockiert hätten.

**Fee- und Funding-Learnings**

- Keine echten Paper-Fills, daher **keine belastbaren Fee- oder Funding-Learnings** aus diesem Run.
- Die Strategie hat zwar eine Kostenhürde und Funding-Gegenwind-Filter eingebaut, aber ohne `signal_journal` gibt es keine Auswertung, wie oft diese Filter relevant waren.

**Live-Einschätzung**

**Live: Nein.**  
Es gibt 0 Trades, keine Signalhistorie, keinen Profit-Nachweis und der Prozess läuft nicht mehr. Dieser Shadow-v2-Run ist aktuell nur ein Research-/Diagnose-Signal, keine Live-Grundlage.

**Konkrete nächste Strategieanpassung — noch nicht ändern ohne Auftrag**

Als nächste Paper-only-Anpassung würde ich **Near-miss-Telemetrie auch in choppy Regimes schreiben**: pro Coin Regime, Trend-Abstand, RSI, Momentum, Spread, Funding, Kostenhürde und Reject-Reason loggen, auch wenn keine Order erlaubt ist. Danach kann man entscheiden, ob ein „mixed-regime“-Modus mit kleinerer Paper-Größe sinnvoll ist, statt den Live-Gate zu lockern.
