Repository navigation
Releases
Latest build — 2026.11.30-1257 (ad9fa52)
Automatic build of ad9fa52 from master - published after the tests workflow went green, or on a manual dispatch.
This page keeps a single build entry; every build keeps its date tag, so git checkout build-2026.11.30-1257 is the rollback point.
Changes
- chore(repo): 2026-11-30 — keep planning notes out of the published tree (ad9fa52)
- feat(prompt): 2026-11-29 — anchor v2.10 claims to observed data (b94d6d6)
- feat(prompt): 2026-11-29 — one reasoning flow that reaches every data section (de296b4)
Full diff: https://github.com/qrak/LLM_trader/compare/build-2026.11.28-2240..build-2026.11.30-1257
v1.1.5 - cycle checkpoint, approval gate, prompt hardening, verifiable suite
What changed since v1.1.4
28 commits, 182 files, +11,557 / −5,682. Grouped by area; each line is a commit in this range.
Trading loop and safety
- Cycle checkpoint — one checkpoint persisted per cycle; a duplicate intent is suppressed by decision hash before any local booking, so a restart cannot open the same position twice.
- Human approval gate (opt-in,
require_approval_above_usdc) — above the threshold an order waits for approval;/api/admin/approvalsserves approve/reject, and an expired request counts as a refusal. - Prompt budget policy —
PromptBudgetPolicy+ a sharedTokenCountersize the whole request before every provider call; protected sections are untouchable, lower-priority context is trimmed instead of the call failing. - Execution quality per entry —
Position/TradeDecisioncarry the entry fill quality, persisted throughPersistenceManagerand SQLite; divergent fills are excluded from statistics and from brain lessons. - Brain evidence — historical MAE evidence and post-mortem lessons feed the prompt; entry trend direction is stored separately from the exit market regime; executor handler shuts down gracefully.
- Read-only MCP server over trade history (
mode=ro+query_only).
Executor and reconciliation
- Incomplete fill evidence on entry intents no longer books a position.
- Entry fill handling and reconciliation reworked; late UPDATE confirmations are settled instead of silently dropped.
- Executor connection failures now surface with warnings and a defined path back, instead of a bare exception.
Analyzer and prompts
- Canonical TTM squeeze — Carter's published pairing: KC(20, 1.5 × Wilder ATR), one smoothing shared by band and printed ATR; the detector returns the run length and a fired event instead of a flag.
- Pattern-state durations — MACD histogram, volatility trend, Bollinger squeeze and accumulation/distribution report how long a state has held ("for N bars"), re-evaluated per bar.
- Explicit labels — "momentum shift", "breakout imminent", "(strong signal)" and "reversal confirmation" removed; the prompt legend names the calculator's fixed windows and every detector threshold.
- R/R narrative false positive fixed —
RR_CHECKspans are stripped before counting quoted ratios, sorisk=819.51is no longer read as a second, unverified R/R that warned on every cycle. - Prompt injection hardening — external news/Reddit text is treated as data: instruction-shaped lines quarantined, code fences defused, invisible characters stripped, block wrapped in per-cycle nonce markers.
- Reddit assessments quoting title IDs as decimal strings are accepted instead of discarding the whole sentiment block; one-shot corrective retry when a parsed decision breaks the contract.
Dashboard and observability
- Cycle journal — append-only
metrics/cycles.jsonlwith latency p50/p95 and signal mix, summarised byGET /api/performance/cycles. - Per-provider circuit breaker — 3 consecutive failures open the circuit for 120 s, then a half-open probe; when every circuit is open the primary gets one fail-open attempt.
- Per-visitor limits —
/api/*rate limiting, the WebSocket cap and the admin login limiter resolve the visitor throughresolve_client_ip(), so Cloudflare-tunnel traffic is limited per visitor; the header is trusted only on a loopback peer. Writes have their own budget and 429s carryRetry-After. - Load shedding — heavy endpoints are capped in concurrency; excess work is refused immediately and a slow GET is cancelled, so a flood cannot queue unbounded work in the event loop that runs the analysis cycle.
- Shared price refresh —
/api/brain/refresh-priceshares one exchange attempt across all dashboard callers for 10 s. - Chart revision URLs stay stable between polls and rotate on analysis, so a late response cannot replace a newer image; news previews are lightweight and no longer ship the full payload.
Data freshness
- CoinGecko — the source's own
updated_attravels with the payload assource_updated_at, a warning fires when it is older than 48 h, and a response served from the HTTP cache without an expiry is warned about once per endpoint. The timestamp is shown in the Market Overview prompt block.
Dependencies, CI and docs
constraints.txtfor the eight non-imported floors/caps;aiosqlite,scipyandbitsandbytesdropped fromrequirements.txt(nothing imports them, they arrive through used dependencies). Every launcher passes the constraints file.- CI — a unit-test workflow (
ruff+pytest -m "not integration"), live/Playwright suites markedintegrationso CI stays offline,config.iniseeded from the tracked template, andruffpinned after 0.17 promoted rules and flagged 178 untouched lines. gitignorecleanup: dead boilerplate and unanchoredlib/pattern removed, local-only files (scripts/start_script_{develop,futures}.ps1,.hermes/,.agents/) now ignored for every clone, not just this one.- Older changelog entries archived into
docs/; README and the site re-measured (79 Numba indicator functions, real pre-execution checks instead of an "R:R gate", providerdeepseek), the duplicated architecture article deleted, the private executor repo no longer linked. - Dead suites deleted —
test_shutdown_real.py(zero assertions) andtest_admin_live.py(needed the production admin password); CSP/HSTS coverage moved totests/domain_infra/test_dashboard_brain.py. The suite now runs with 0 skipped. - Four untested paths closed by mutation testing: narrative R/R tolerance (
2.35claimed vs verified1.953), BUY bracket ordering (stop < entry < target),position_size > 1, and a fill divergence above 1% (a 50% tolerance had passed all 182 tests in that file). - Agent documentation trimmed 117.6 KB → 70.0 KB, with false statements corrected (paper-only execution while
[executor_api] enabled = true, a1.50R:R gate againstmin_rr_entry = 0.0, Gemini as the provider whileprovider = deepseek).
Verification
- Full Windows-venv suite: 2419 passed, 0 skipped, 0 failed (~160 s)
- CI gate
pytest -m "not integration": 2385 passed, 34 deselected - Mutation probe: 9 realistic mutants in
src/— 5 killed before the new assertions, 9 killed after ruff check src start.py scriptsclean; GitHub ActionstestsandCodeQLgreen on this commit
v1.1.4 — unrestricted update timing and optional secrets file
Changes
- Removed the bot-side minimum UPDATE interval completely: valid consecutive LONG/SHORT
protection updates are no longer delayed by the former 4h → 8h policy. - Added environment-only credentials and optional keys.env support. Process variables take
precedence. Only the selected provider's credentials are needed; the example explains
optional integrations and no longer ships fake enabled keys. - Kept the mathematically verified ADX correction and clarified that the response must copy
actual ADX readings, not subjective trend scores. - Removed the orphaned .trivyignore file. CodeQL remains enabled and unchanged.
Verification
- Full Windows-venv suite: 1948 passed, 17 skipped.
- Ruff, compilation and startup-import smoke test pass.
- Pyright: 16 pre-existing errors, identical to the pre-change snapshot; no new diagnostics.
- Independent Wilder ADX(14) matches the bot on historical public Binance candles to <7e-14.
- Tests left live position and execution journals unchanged. No running services restarted.
Upgrade
Restart the bot to load the code/config changes; the executor does not need a restart for
these changes. Existing keys.env remains supported. Prefer OS/service environment variables
if you want to avoid keeping a plaintext secrets file in the project. On Windows reopen the
launcher terminal after changing persistent environment variables.
Existing price-progress SL tightening/widening policies and execution-evidence checks remain
in place. This change does not promise better profitability or alter historical results.
See CHANGELOG.md for the complete history of changes included since v1.1.3.
v1.1.3 — codebase cleanup, executor safety, dependencies hardened
🧹 Code health — the big cleanup
A month of accumulated low-value code removed in one pass, with no behaviour change except the four cases listed at the bottom. Net −687 lines in the refactor commit alone.
- Dead code gone: RL policy, audit module, their tests, the
[rl_training]config section and a dead wrapper inTradingMemoryService - Deduplicated copy-pasted blocks: dashboard WS auth + log pump, support/resistance resolution, RAG knowledge refresh, writable-config meta lookup
MarketSnapshotdataclass replaced the 19-field argument blob threaded through brain / brain_context / analysis_engine- Largest functions split into named steps: dashboard app factory (435 → 37 lines), brain decision summary, chart generation, PositionExtractor
- ~17 blanket
except Exceptionguards around pure arithmetic/formatting removed; the rest narrowed to what can actually be raised - Comments and docstrings: perf-narration (
# Bolt: …,# Optimization: …) and code-restating comments stripped (73 → 3 long comments); 15 bloated docstrings compressed, −239 lines ofArgs:/Returns:boilerplate, keeping the domain facts and the returned-dict key lists - Dashboard
main.js: now guards missing DOM nodes, logs the previously swallowed brain-status failure, and routes every poller/listener through a rejection handler (try { updateAll(); } catchcould never fire — async call, not awaited)
🛡️ Executor safety
- Entry notional clamped to the executor's limit; a rejected entry rolls back instead of leaving a ghost position
- Position query URL fixed (was requesting
/decision/position→ 404) - Stale
latest_decision.jsoncleared after a successful HTTP forward, so a restarted executor cannot re-read an old decision - Disabling the executor in config now also stops the file fallback from being written
- Post-mortem journal linked to the CLOSE row in trade history
🤖 Analysis and behaviour
- Contract repair: an AI response missing its JSON block is recovered instead of silently degrading
- EV fees now scale with position notional, not portfolio capital
- Removed staged/conditional entry framing — decisions are made on the latest closed candle only
- R/R gate loosened, confirmed breakouts acted on
- Startup tickers validated against live symbols; provider name reported accurately in the logs
- DeepSeek official API support + provider transport consolidation
🔌 Operations
- In-place reload via SHIFT+R (graceful shutdown → launcher restart)
- Version-aware launcher dependency check
🔒 Dependencies and security
- Requirement floors raised to the versions this environment actually runs and was tested with:
accelerate>=1.15.0,chromadb>=1.5.9,python-dotenv>=1.2.2,requests>=2.34.2,torch>=2.13.0,transformers>=5.14.1,urllib3>=2.7.0. The previous floors (chromadb>=1.0.0,transformers>=4.46.0,urllib3>=2.2.2, …) still allowed a fresh install to resolve to versions carrying 30+ advisories. - accelerate 1.14.0 → 1.15.0 in the environment: fixes CVE-2026-69112 (path traversal / denial of service when loading sharded checkpoints). Verified after the bump: the brain's vector store opens (3 collections), a full add/query/delete cycle passes on a copy, and
bge-base-en-v1.5encodes 768-dimensional embeddings. - chromadb carries four advisories (CVE-2026-45829 / 45830 / 45831 / 45833) that no release fixes — 1.5.9 is the newest on PyPI and every version sits inside the affected range. All four are server-mode issues (HTTP API, RBAC, cross-tenant access), while this project only ever uses an embedded
PersistentClientagainst a local directory, so they are not reachable here. Recorded with the reasoning in.trivyignore.
⚙️ CI
- Removed both auto-fix workflows — one opened zero pull requests across 25 branches (the repo does not allow Actions to create PRs and the failure was swallowed by
|| echo ...), the other never had a real issue to fix. All 25 deadci/auto-fix-*branches deleted. - Repaired the Codacy scan — it had been failing at its init step for days because Codacy's own installer calls an undefined
fatal— got the first successful run, then removed it too: 711 findings of which 319 wereno-undefon browser globals that the engine cannot be configured to accept, 371 complexity metrics, and 8 logger false positives on token counts. The repository now runs no CI workflows: dead weight removed rather than kept green. - Website Dependabot alerts cleared (9)
⚖️ Deliberate behaviour changes (4)
- No-JSON response → HOLD instead of a guessed decision
- Non-numeric
confidence→ 50 / MEDIUM position_size > 1→ rejected instead of silently clamped- Trend is no longer inferred from free text
Verified: 1402 passed / 0 failed / 17 skipped · pyright 0 errors · ruff clean over src and start.py, and no new findings over tests/scripts (49 → 39 across the release).
🧱 Refactor pass — 1000-line cap, god-class splits, no behaviour change (PR #13)
- Every module and class is now under 1000 lines.
start.py1397 → 502,src/dashboard/routers/brain.py1238 → 702,src/trading/trading_strategy.py1209 → 480,tests/test_trading_strategy_branches.py1522 → 996. Each split moves method bodies verbatim into mixins the existing classes already inherit, so no call site, MRO or test seam changed (strategy._open_new_position, the brain helpers, the launcher imports ofstart.pyall keep working). - New modules (all well under the cap):
src/composition/provisioners.py+src/composition/startup_support.py(the 9 provisioning stages and the env/GPU/dialog/banner helpers),src/trading/executor_reconciliation.py(position verification, verdict journal, phantom rollback),src/trading/position_management.py(entry, SL/TP updates, existing-position decisions),src/dashboard/decision_presenter.py(the pure view-model builders out of the brain router). _open_new_position(235 lines) decomposed into_reject_intent/_store_risk_frictions/_check_entry_thresholdsplus the entry body; the three exit-check entry points now share_close_on_exit.- Comments: every prose
#comment removed — 1 980 full-line + 339 trailing. Only machine directives remain (# noqa,# type: ignore,# pylint:,# pragma:); removing those would re-break the lint and type gates. - Docstrings:
Args:/Raises:boilerplate that restated signatures removed across 75 files (2 136 lines);Returns:sections and returned-dict key documentation kept. - Last type introspection on known types removed: 8 ×
getattr(self.config, KEY, default)(each key is a realConfigproperty whose own default already matched), 3 ×hasattronCoinGeckoAPI.symbol_to_id_map/RagEngine.news_manager/TradingStrategy.guard_pipeline, andgetattr(decision, "order_id", None). Notry/exceptwas added anywhere; the config stubs in 8 test files now declare the six attributes production reads directly, at the loader's own defaults. - Fixed:
_provision_dashboard_layerderivedconfig/config.inifromPath(__file__).parent, which resolved insidesrc/composition/once the method moved — now anchored on aPROJECT_ROOTconstant. - Left alone deliberately:
notifiers/filehandler.pyFILE_MESSAGE_EXPIRY, where the two defaults disagree (0= never expire vs the loader's604800= 7 days). That is a behaviour decision, not a cleanup.
Verified: 1402 passed / 0 failed / 17 skipped · pyright 0 errors / 0 warnings · ruff clean over src, start.py.
Full diff: v1.1.2...v1.1.3
v1.1.2 — 22 bug fixes + self-improving CI
🔧 Bug-Fix Release — 22 fixes from AI audit + full CI automation
🐛 Fixes (from the 3-agent audit of the trading path)
Critical
- CoinGecko: API failure no longer caches an EMPTY payload as fresh data for 24h (LLM market context poisoning); cache writes are now atomic
High
- Dead-letter replay keeps failed entries — a lost CLOSE order can no longer strand an unprotected position
leveragefrom LLM output sanitized —int(null)no longer aborts order forwardingreduce_onlyparsed correctly —bool("false") == Truebug eliminatedentry_priceNaN guard — NaN can no longer bypass<= 0checks and poison PnL/position sizing- Market overview
published_onnow reflects the REAL data age, not fetch time - Sync JSON writes moved off the asyncio event loop (persistence, dead-letter, news, SQLite export)
Medium
- 12
logger.exception("...%s")sites fixed — error text actually reaches the logs now asyncio.gatherisolation — one flaky subtask no longer kills the whole analysis cycle- "Error retrieving market context." no longer injected into the LLM prompt as market data
- Nested
trend.strength_4hNaN/None sanitized (was bypassing the parser sanitizers) current_priceNaN guard in trading strategy"Sortino: inf"never injected into prompts on winning streaks- Non-atomic cache writes →
os.replace(CoinGecko, DefiLlama) - Soft-exit skips logged loudly when ticker data is missing
"analysis": nullfrom LLM degrades to neutral instead of crashing the cycle
🤖 Self-Improving CI (the "code improves itself" claim, made real)
- auto-fix-pr.yml — ruff autofix runs on every push to master + weekly; produces an automatic PR
- agent-fix.yml — every new issue is automatically picked up by Hermes Agent (DeepSeek), fixed per
.ai/bugfixing.mdrules, and delivered as a PR for human approval - Agent docs (
.ai/supervisor.md,.ai/bugfixing.md) updated with the CI pipeline
📝 Other
- Landing page claims aligned with code: 1,270+ tests, 50-level order book, 10 dashboard tabs, 6 pipeline stages, Full HD charts
- New feature from v1.1.1 cycle: regime-based risk profile selector (choppiness + ATR)
✅ Quality
- Full test suite: 1297 passed, 17 skipped, 0 failed
- ruff clean
Human-in-the-loop: all PRs require human approval — nothing merges itself.
v1.1.1 — Showcase Website, Codacy Security CI, SARIF Remediation & Core Hotfixes
Release v1.1.1 — Showcase Website, Codacy Security CI, SARIF Remediation & Core Hotfixes
This release applies major documentation consolidation, introduces the project showcase website, configures Codacy Security CI with full SARIF remediation, refactors regime risk profiles, and rolls out critical core trading & risk system fixes.
🌐 Project Showcase & Documentation
- Showcase Website (
website/):- Built Astro static site showcase with interactive landing and project story pages (
src/pages/index.astro,src/pages/story.astro,src/layouts/Layout.astro).
- Built Astro static site showcase with interactive landing and project story pages (
- AGENTS.md Single Source of Truth:
- Consolidated all 8 subsystem-specific
AGENTS.mdfiles into the single masterAGENTS.mdin root directory. - Added structural documentation for workspace customizations and multi-agent workflows.
- Consolidated all 8 subsystem-specific
🛡️ Codacy Security CI & SARIF Remediation
- Codacy CI Workflow (
.github/workflows/codacy.yml):- Configured automated security scanning and SARIF report upload using
github/codeql-action/upload-sarif@v4.
- Configured automated security scanning and SARIF report upload using
- SARIF Remediation Engine & Test Suite (
scripts/fix_sarif.py,tests/test_fix_sarif.py):- Resolved GitHub Code Scanning upload failures by fixing null
tool.driver.rulesarrays and normalizing non-standard result level enums ("info","critical","high") to SARIF standard enums ("none","note","warning","error"). - Ensured in-place SARIF processing for seamless GitHub Code Scanning integration.
- Resolved GitHub Code Scanning upload failures by fixing null
⚙️ Core Trading & Risk Architecture
- Regime Risk Profile Refactor:
- Replaced
risk_profile_selector.pywithregime_risk_profile.pyfor regime-aware profile selection integrated intoRiskManager,BrainContext, andMarketConditions.
- Replaced
- WebSocket DI Compliance:
- Enforced dependency injection for
ConnectionManagerinstantiated at composition root instart.pyand passed down toDashboardServer.
- Enforced dependency injection for
- R/R Gate Contradiction (1.2 vs 1.5):
- Fixed discrepancy by enforcing a strict minimum default threshold of
1.5dynamically derived from learned Brain performance parameters.
- Fixed discrepancy by enforcing a strict minimum default threshold of
- ATR-Based SL Distance & 0.0% Wiring Fix:
- Refactored stop loss distance to scale dynamically with profile-driven ATR multiples (1.5x aggressive, 2.0x neutral, 2.5x conservative) and patched initialization bug in
brain.pyandanalysis_engine.py.
- Refactored stop loss distance to scale dynamically with profile-driven ATR multiples (1.5x aggressive, 2.0x neutral, 2.5x conservative) and patched initialization bug in
- HOLD JSON Schema Fix:
- Resolved JSON parsing errors for
HOLDsignals by ensuring response schema contains correct semantics andnullfields where attributes are omitted.
- Resolved JSON parsing errors for
- EV-Over-Bias Priority:
- Re-aligned decision weighting in
ev_formatter.pyso that Expected Value (EV) calculation takes priority over raw direction biases.
- Re-aligned decision weighting in
- News Double-Ingestion Guard:
- Implemented title-based deduplication in
rss_primitives.pyandrss_provider.pyto prevent duplicate articles in RAG context.
- Implemented title-based deduplication in
- Dependency Upgrades & Deprecations:
- Updated
beautifulsoup4(>=4.15.0) andcrawl4ai(>=0.9.2). - Removed deprecated
NitterSentimentAnalystmodule and associated tests.
- Updated
v1.0.4 — Public Live Console View + Vector Memory 768D Upgrade
Release v1.0.4 — Public Live Console View + Vector Memory 768D Upgrade
What's Changed
📊 Public Dashboard & Live Console
- Live Console tab on public dashboard — real-time log streaming via WebSocket, styled like
richterminal output with level-based color coding (ERROR=red, WARNING=yellow, INFO=gray, DEBUG=dim). - ConsoleBuffer (
src/dashboard/console_buffer.py) — in-memory day-grouped ring buffer, max 7 days, clears on restart. - ConsoleRouter (
src/dashboard/routers/console.py) — public REST endpoints (/api/console/recent,/api/console/pages,/api/console/page/{n}) + WebSocket (/api/console/live).
🛡️ Security & Dependencies
- Resolved 19 Dependabot vulnerabilities across Pillow (CVE-2026-59199, CVE-2026-59205, etc.), Astro (CVE-2026-59729, CVE-2026-59727), js-yaml (CVE-2026-59869), sharp, and svgo.
- Hardened executor payload forwarding with dead-letter queue (
data/trading/failed_forwards.jsonl) and exponential backoff retry.
🧠 Vector Memory & Engine Architecture
- Upgraded embedding model to
BAAI/bge-base-en-v1.5(768D). - Resolved graceful shutdown crash cascades and multi-module resource cleanup.
- Implemented AST codebase vector indexer and 8-stage autonomous agent pipeline with journal rotation.
⚡ Trading Logic & Risk Guards
- Supported Futures LONG/SHORT signals across prompt templates, position extraction, and order execution.
- Enforced SL widening cap (max 150% of initial SL distance) and position verification before sending close/update commands.
Full Changelog: v1.0.3...v1.0.4
v1.0.3 — Security, Futures & Executor Safety
v1.0.3 — Security, Futures & Executor Safety
Security (19 Dependabot alerts resolved)
- Pillow 12.2.0 → 12.3.0 — 12 CVEs (heap OOB write, decompression bomb, TGA heap leak, DoS, command injection)
- astro ^6.4.6 → ^7.1.0 — 3 XSS CVEs (spread attrs, transition:*, View Transition)
- js-yaml → 4.3.0 override — YAML DoS (CVE-2026-59869)
- sharp → 0.35.3, svgo → 4.0.2 — transitive deps
- openrouter 0.9.1 → >=0.11.0
Futures LONG/SHORT Signals
MARKET_TYPEconfig (spot/futures) +ENTRY_ORDER_TYPE(market/limit)- Prompts emit LONG/SHORT for futures mode; regex + valid_signals accept both
- OpenRouter reasoning_effort support (none→max)
Executor Safety Hardening
- CLOSE guard: verify executor has position before closing (prevents double-close on unfilled limit orders)
- UPDATE guard: verify position exists before SL/TP update
- SL widening cap: rejects widening beyond 150% of original distance
- Dead-letter queue: failed forwards persisted to JSONL for replay
- Retry: @retry_async(3, backoff×2) on executor forward
- Payload hardened: uses strategy_decision fields, not raw LLM analysis
- Executor forward happens BEFORE notify/persist
Other
- Chart resolution 4K → 1080p (~75% Google image token savings)
- Google image token estimation (tile-based, 258 tokens per 75×75 tile)
- Ambiguous position_size >1.0 without % rejected
- DRY refactors: MarketConditionsExtractor, timeframe arithmetic, market knowledge fallback
- Position gap context in prompts (time since last closed + direction)
- Decision Pathways panel: zoom/layout/deferred init
- Google thinking tokens counted in billing
- 1210 tests passing (0 failures)
v1.0.2
v1.0.2 — BlockRun AI (optional) + Post-Mortem llm_analysis + Dashboard Resilience
Added
- BlockRun.AI provider (fully optional) — x402 micropayment-based AI provider via
blockrun-llmSDK. Gated behindBLOCKRUN_WALLET_KEYenv var; no-op when unset. llm_analysisfield in post-mortem API response —get_recent_post_mortems()now returns the full LLM analysis text that was already stored but missing from the query result.- 96 new tests: BlockRun provider unit/integration tests, post-mortem API endpoint tests, trading strategy check_position/exit handling tests.
Fixed
- Dashboard resilience — each panel initializer now has its own try/catch. A single panel failure no longer cascades and kills the entire dashboard.
- SL/TP logging crash —
trading_strategy.pyno longer crashes when formatting a position update withNonestop_loss or take_profit.
v1.0.1 — Critical SHORT position bug fix
Critical Bug Fix
SHORT position price_progress always 0% in SL tightening context
The Bug
For SHORT positions, the sentinel SL value in get_position_context() was always nudged upward (+1e-8). Since SHORT stop-loss sits above entry, moving it up widens the SL rather than tightening it. The tightening evaluation returned is_tightening=False for every SHORT position, causing price_progress to always read 0.0% — regardless of actual price movement toward targets.
Impact: The LLM never saw evidence of price progress for SHORT positions, so it never suggested SL tightening via UPDATE_SL for SHORT trades.
The Fix
Direction-aware sentinel SL — changed from 1 line to 2:
Before (broken for SHORT):
proposed_sl=pos.stop_loss + 1e-8
After:
sentinel_sl = pos.stop_loss - 1e-8 if pos.direction == "SHORT" else pos.stop_loss + 1e-8
proposed_sl=sentinel_sl
- SHORT: nudges SL down (-1e-8 toward entry) -> tightening
- LONG: unchanged (+1e-8) — no regression
Verified
- 25/25 SL tightening tests pass
- Full suite: 1097 passed, 3 pre-existing live-admin failures (unrelated)
- Direction-aware sentinel confirmed correct for both LONG and SHORT in a full codebase audit (no other directional bugs found)
Commit
81a5f90 on master