โš–๏ธ Strictly AS-IS Archival Documentation: Provided free of charge under the MIT License without warranty, financial/gambling advice, or technical support of any kind.

TITAN HFT (SHARK V7 RELOADED) โ€” Full User Manual

Disclaimer: Educational and research material only โ€” not financial or investment advice. Trading involves substantial risk of loss; past or simulated results do not indicate future results. Titan HFT is provided AS-IS, with no liability and no support. No API keys are included.

Version: V7 Reloaded

Engine: Rust (Tauri) + WGPU + HTML/JS Frontend

Platform: Alpaca Markets (Paper + Live)

Supported Assets: Crypto (BTC/USD, ETH/USD, etc.) + US Stocks

Date: April 2026 (updated April 3 โ€” Session 69: Wave 2B SmartTrend Correctness โ€” 108 Chapters)


CONTENTS

  1. Startup and Initial Configuration
  2. System Architecture
  3. User Interface (UI)
  4. Restructured Sidebar (Full Audit)
  5. System of Strategy (3 Modes)
  6. How the Bot Chooses Assets
  7. TITAN Oracle โ€” 7 AI Indicators
  8. GPU Nexus โ€” 150,000 Agents
  9. L2 Orderbook and OFI (Order Flow Imbalance)
  10. Autopilot โ€” Automatic Trading Engine
  11. Safety Filters (Safety Gates)
  12. Genetic Optimizer โ€” Automatic Evolution of Parameters
  13. Circuit Breaker โ€” System of Safety
  14. Dry Run Mode โ€” Simulation without Risk
  15. Watchdog and Telemetry
  16. Logging and Reports
  17. Backtesting
  18. Professional Chart
  19. New Tabs (AI News, Journal, HFT Engine, Performance)
  20. AI Scanner โ€” FUSION Asset Discovery
  21. Positions and Funds Management
  22. All Background Loops
  23. All Available Commands
  24. Structure Files
  25. Frequent Problems and Solutions
  26. Catalyst Watchdog โ€” Sentient News Feed
  27. Chart Signals and Arrows
  28. Telegram Alerts โ€” Notifications Mobile
  29. Risk Correlation Matrix
  30. Portfolio Performance & Rebalancing
  31. ATR Dynamic Stop-Loss & Partial Profit Taking
  32. Web Dashboard โ€” Remote Mobile Access
  33. State Persistence โ€” Crash Recovery
  34. Smart Score V4 โ€” Institutional Ranking
  35. Auto Entry โ€” Entry Control Automatic
  36. Signal Alignment โ€” FUSION-Aware Autopilot & Causal Chart
  37. Auto-Resume Scan โ€” Continue from Breakpoint
  38. Multi-Symbol Entry Fix & DEL ALL
  39. Entry Gate Scoring Pipeline โ€” Debottlenecking
  40. Scalping Mode โ€” Toggles per Strategy
  41. Regime-Adaptive Trading Signals
  42. Autopilot Alignment โ€” check_entry + Oracle Exits
  43. WARRIOR PRO โ€” Ross Cameron Scanner
  44. Position Sizing Safety โ€” Hardcaps & Duplicate Prevention
  45. Scalping Position Marker
  46. AI Scanner Enhancements โ€” Cancellation, Shared Scoring, Rate Limiting
  47. SMART PICKS 3-Pillar Scoring
  48. Market Discovery โ€” Advanced Parameters and Auto-Scan
  49. Manual Trade โ€” Manual USD Transaction
  50. Force Manual Override โ€” Total Control
  51. Live Positions โ€” Auto/Manual Mode per Asset
  52. Drawing Tools V2 โ€” All Tools
  53. Aggressive Mode โ€” Full Audit
  54. Extended Hours โ€” Full Audit
  55. Session 7 Eliminations
  56. AI Scanner Parallel Scoring (Rayon)
  57. Deep Audit Reasoning โ€” Modal Window
  58. Manual Trade USD vs Shares Toggle
  59. SIGNAL Scalping Kit โ€” Alerts and Exact Journal
  60. All Configurable Trading Parameters (Session 18)
  61. Deep Audit + 12 Smart Features + Styling (Session 19)
  62. Session 26: TA Entry Gates with Soft/Hard Mode (RF-B)
  63. Portfolio VaR Engine + HHI Concentration Gate (S9)
  64. Microstructure Alpha Signals โ€” Stream VPIN, Spread Regime, Dual VPIN Divergence (S10-lite)
  65. Microstructure Alpha Signals โ€” Stream VPIN, Spread Regime, Dual VPIN Divergence (S10-lite)
  66. N4 Strategy Configurable Thresholds (Session 35-36)
  67. CI Hardening + Criterion Benchmarks (S19, Session 37)
  68. Online Oracle Weight Adaptation (S15, Session 38)
  69. Exit Inflight Guard โ€” Anti-Loop Protection (Session 39)
  70. Configuration Coherence โ€” apply_runtime_config (Session 44)
  71. Wave 1 MUST-FIX โ€” 9 Critical Fixes + 4 Bonuses (Session 67)
  72. Wave 2A SmartTrend Safety โ€” 8 Fixes + 4 Bonuses (Session 68)
  73. Wave 2B SmartTrend Correctness โ€” 9 Fixes + 5 Bonuses (Session 69)

1. START-UP AND INITIAL CONFIGURATION

1.1 System Requirements

1.2 Starting the application

~/titan_hft_rust/src-tauri/target/release/titan_hft_rust

1.3 At startup, Titan does automatically

  1. Initialize logging โ€” write in ~/titan_hft_rust/logs/titan.log.YYYY-MM-DD
  2. Load API Keys from ~/titan_hft_rust/titan_keys.json
  3. Full Health Check โ€” check:
  1. Start all loops (9 loops + watchdog supervisor)
  2. Synchronize positions on Alpaca (Reconciliation)
  3. Displays the Health Check result in the Activity Log

1.4 Configuring API Keys

In the interface, in the left sidebar, expand the section API & WALLET:

  1. Enter API KEY ID (26 characters)
  2. Enter API SECRET (44 characters)
  3. Click SAVE KEYS

The keys are saved in ~/titan_hft_rust/titan_keys.json and persist between sessions.


2. SYSTEM ARCHITECTURE

2.1 Rust Modules (Backend)

FileResponsibility
main.rsCentral orchestrator, state management, ~70 Tauri commands, 14 background loops
titan_oracle.rs7 advanced AI indicators (Kalman, Hurst, Entropy, Wavelet, VPIN, Lyapunov, BOCPD)
gpu.rsWGPU compute shaders, 150K GPU Nexus agents, EMA/RSI on GPU
risk.rsCircuit Breaker (4 levels), SessionAnalytics, OFI, risk-based positioning
genetic.rsGenetic optimizer with walk-forward backtest (70/30 IS/OOS)
l2_heatmap.rsL2 orderbook live, OFI from full depth, crypto v1beta3 + SIP stocks
watchdog.rsHeartbeat monitoring, telemetry per loop, session reports
titan_log.rsStructured logging with tracing, daily rotation
indicators.rsClassic technical indicators (EMA, RSI, MACD, ADX, BB, VWAP)
strategy.rsThe logic of strategy and signals
streamer.rsPrice streaming and heatmap
scanner.rsMarket scanner (quant_prefilter + warrior_prefilter)
monitor.rsHardware monitoring (CPU, GPU, RAM, Network)
Sentiment analysis + Catalyst checkSentiment analysis + Catalyst check
app_state.rsDefinition of application states
Pearson correlation, portfolio performance, rebalancingPearson correlation, portfolio performance, rebalancing
telegram.rsTelegram Bot alerts (fill, breaker, catalyst, daily)
journal.rsPersistent trade journal (JSON, stats, CSV export)

2.2 GPU Shaders (WGSL)

Shaderswhat is he doing
nexus_kernel.wgsl150K agents: each calculates intent (buy/sell), votes, adjusts capital
gpu_indicators.wgslEMA fast, EMA slow, RSI for a single series
gpu_indicators_batch.wgslThe same thing but for several series simultaneously
gpu_dot.wgslParallel dot product (GPU reduction)

2.3 Front end


3. USER INTERFACE (UI)

3.1 Header

3.2 Central Area โ€” Tabs

TabContent
Complex Chart (tab-0)Professional OHLC chart with EMA, BB, VWAP, RSI, MACD, ADX, Oracle
News AI (tab-1)News feed with sentiment analysis (gauge, timeline, cards)
Backtest (tab-2)Backtesting engine with multi-timeframe and multi-symbol sweep, equity curve
Diary (tab-3)Persistent transaction history with filters, CSV export, equity/PnL graphs
HFT Engine (tab-4)Advanced HFT engine settings: entry/exit params, Discord alerts, safety limits

3.3 Upper Central Panel

GPU Nexus โ€” 150K Agents:

3.4 The TITAN SAFETY panel

Displays in real time:

3.5 EVOLUTION panel

3.6 OFI LIVE panel

3.7 ACTIVITY LOG panel

Log in real time with color-coding:

3.8 LOOP HEARTBEATS panel

3.9 Control Buttons

ButtonFunction
DRY RUN: OFF/ONActivate/deactivate simulation (do not send orders to Alpaca)
SHUTDOWNGraceful stop โ€” saves the report, stops all loops
LIQUIDATE ALLClose ALL open positions and cancel orders

3.10 Left Sidebar (Summary)

The sidebar has been completely restructured into 8 logical sections (see Section 4 for full details).


4. THE RESTRUCTURED SIDEBAR (FULL AUDIT)

The left sidebar has been completely reorganized into 8 logical sections, each with a visible header and consistent content.

4.1 Section 1 โ€” SYMBOL & FAVORITES

4.2 Section 2 โ€” SYMBOL TABS (WATCHLIST / HFT ENGINE)

Two sub-tabs with interactive buttons:

TabContent
WATCHLISTList of favorite symbols with quick selection
HFT ENGINETarget symbol list for multi-symbol autopilot

HFT ENGINE tab displays:

4.3 Section 3 โ€” HARDWARE MONITOR (Collapsible)

Section <details> open by default. Display:

GPU:

CPU:

Network:

4.4 Section 4 โ€” BANK & ACCOUNTS

Show funds in real time:

FieldDescription
Cash (Power)Available purchasing power
Equity (Total)Bot Alloc
Bot AllocFunds allocated to the bot
User DepositThe user's virtual storage
PnLDaily profit/loss
Bot Trade SizeOrder size (persistent in the backend)
Circuit Breaker LimitCircuit breaker limit (persistent in backend)

Transfer buttons:

4.5 Section 5 โ€” API & WALLET (Foldable)

Section <details> open by default.

4.6 Section 6 โ€” RISK & PARAMS (Collapsible)

Section <details> open by default. Contain:

Toggles (checkboxes):

ToggleEffect
Scan ActiveActivate the market scanner
KellyKelly Criterion positioning
Extended HoursTrading outside normal hours
Manual ResultManual result per trade
Force ManualForce manual mode (disable autopilot)
WarriorAggressive mode
Auto-PilotEnable/disable autopilot
AggressiveAggressive parameters
Short SellingAllows short selling
Multi-SymbolEnable simultaneous trading on multiple symbols

Sliders:

4.7 Section 7 โ€” MARKET DISCOVERY (Collapsible)

Section <details> open by default.

4.8 Section 8 โ€” CONTROL BUTTONS

Control buttons at the base of the sidebar:

ButtonColorEffect
DRY RUN: OFF/ONYellowActivate/deactivate simulation
SHUTDOWNGrayShutdown with save report
LIQUIDATE ALLRedKill switch โ€” close everything

4.9 Persistence of Settings

After Full Audit, the following settings are persistently stored in titan_settings.json (Rust backend), NOT in localStorage:

SettingDescription
dry_run_enabledDry Run Status (true/false)
strategy_mode_nameStrategy Mode (ORACLE/GPU/FUSION)
bot_trade_sizeOrder Size
circuit_breaker_limitCircuit breaker limit
favoritesList of favorite symbols

Settings are loaded automatically at startup and saved instantly when modified.

4.10 Styling


5. STRATEGY SYSTEM (3 MODES)

Titan operates in 3 strategy modes, selectable from the UI:

5.1 ORACLE Mode

Exclusively uses TITAN Oracle (7 AI indicators):

5.2 GPU NEXUS Mode

Uses exclusively GPU Nexus (150K agents on RTX):

Combine Oracle + GPU Nexus with an adjustable blend:

Change mode


6. HOW THE BOT CHOOSES ASSETS

6.1 Two Modes of Selection

Titan does not scan the market itself to discover what to trade. Assets are defined by the user:

Module 1 โ€” Unique Symbol (Default):

Module 2 โ€” Multi-Symbol (HFT Engine):

6.2 Decision Flow (per symbol)

Simbol Activ โ†’ Fetch OHLCV bars
                    โ†“
            Calcul Oracle Score (7 AI indicators)
            Calcul GPU Nexus Consensus (150K agents)
                    โ†“
            Scor final (fusion_threshold check)
                    โ†“
         โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
         โ•‘  SAFETY GATES (toate trebuie trecute):โ•‘
         โ•‘  1. Circuit Breaker = NORMAL          โ•‘
         โ•‘  2. Spread Guard < limita             โ•‘
         โ•‘  3. OFI confirma directia             โ•‘
         โ•‘  4. Cooldown elapsed                  โ•‘
         โ•‘  5. Max positions nu e atins          โ•‘
         โ•‘  6. Sentiment filter (optional)       โ•‘
         โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
                    โ†“
            Risk-based position sizing
                    โ†“
            SEND ORDER (sau DRY RUN log)

6.3 Strategy โ€” Filters relationship

The strategy (Oracle/GPU/Fusion) generates the signal and the score. But the signal does NOT guarantee a trade. The safety filters are independent and can block the entry even if the score is high:

The strategy is the signal creator. Filters are the gatekeepers who protect the capital.


7. TITAN ORACLE โ€” 7 AI INDICATORS

The Oracle combines 7 advanced indicators into a final score (-100 to +100):

7.1 Kalman Adaptive Predictor (KAP) โ€” Weight 30%

7.2 Haar Wavelet Multi-Resolution โ€” Weight 25%

7.3 Fractal Hurst Momentum (FHM) โ€” Weight 20%

7.4 VPIN (Volume-Weighted Probability of Informed Trading) โ€” Weight 15%

7.5 Shannon Entropy Flow Regime Detector (EFRD) โ€” Weight 10%

7.6 Lyapunov Chaos Detector

7.7 Bayesian Online Changepoint Detector (BOCPD)

7.8 Final Fusion Formula

raw_signal = (Kalman * 0.30) + (Wavelet * 0.25) + (Hurst * 0.20) + (VPIN * 0.15) + (Entropy * 0.10)

regime_boost = 1.3 daca trending | 0.7 daca mean-reverting | 0.3 daca chaotic

meta_confidence = (predictability * clarity * stability_factor).cbrt()
                  ^ media geometrica previne colapsul catre zero

stability_factor = 0.3 daca changepoint_prob > 0.3 | 1.0 altfel

oracle_score = raw_signal * regime_boost * meta_confidence * 100

confidence = meta_confidence * (1 - noise_ratio * 0.5).max(0.25)
             ^ noise penalty injumatatit, floor 25%

Final range: -100 (extremely bearish) to +100 (extremely bullish)


8. GPU NEXUS โ€” 150,000 AGENTS

8.1 How it works

8.2 Consensus

At each tick (500ms):

  1. Send MarketState (price, volumes, indicators) to GPU
  2. All agents simultaneously calculate intent
  3. Summary buy_weight and sell_weight
  4. Calculate percentages and consensus
ConsensusCondition
STRONG BUYbuy_pct > 70%
BUYbuy_pct > 55%
NEUTRALNone of the above
SELLsell_pct > 55%
STRONG SELLsell_pct > 70%

8.3 Evolution of Agents

Agents do not have static parameters โ€” their capital adjusts automatically:


9. L2 ORDERBOOK AND OFI (ORDER FLOW IMBALANCE)

9.1 Data source

9.2 Automatic detection of crypto vs stocks

The symbol is detected automatically:

9.3 Orderbook Management (Crypto)

9.4 OFI (Order Flow Imbalance)

Formula:

OFI = ฮฃ(bid_size_deltas) - ฮฃ(ask_size_deltas)  pe top 10 nivele

OFI as input filter:

9.5 Spread Safety

9.6 Consolidation of the L2 Stream

L2 data is processed through a single WebSocket in streamer.rs. Initially there were two separate connections (streamer.rs and l2_heatmap.rs), which caused the "connection limit exceeded (code 406)" error. After consolidation:

9.7 What you see in the UI


10. AUTOPILOT โ€” THE AUTOMATIC TRADING ENGINE

10.1 Trading cycle (every 1.5 seconds)

  1. Check Circuit Breaker โ€” If it is not NORMAL, do not enter new positions
  2. Fetch bars (OHLCV) from Alpaca
  3. Calculate Oracle Score and/or GPU Nexus Consensus
  4. Check OFI โ€” The signal must be confirmed by the order flow
  5. Check Spread โ€” The spread must be within safe limits
  6. Check Cooldown โ€” Minimum time between entries
  7. Calculate the position โ€” Risk-based sizing
  8. Send the order or simulate (if Dry Run is ON)

10.2 Entries (Entry)

Cumulative conditions (ALL must be met):

10.3 Exits (Exit)

Checks on existing positions (at each tick):

10.4 Position Sizing (Risk-Based)

Formula:

risk_amount = equity * (risk_per_trade / 100) * breaker_multiplier
qty = risk_amount / |entry_price - stop_loss_price|

Safety checks:

10.5 Trailing Stop


10.6 Crypto vs Stocks โ€” Automatic Detection

When sending an order, the bot automatically detects the type of asset:

Crypto detection (any of):

Key Difference โ€” Time In Force:

Sending a crypto order with "day" causes error 422 Unprocessable Entity: invalid crypto time_in_force on Alpaca. Titan automatically manages this difference.

10.7 Handling Permanent Errors at Exit (Fix 403 Forbidden)

A critical issue was the 403 Forbidden: insufficient qty bug when the bot tried to close a position (Market Sell) while the stock was blocked by a previously opened Limit (Take Profit) order.

Titan V7 Solution (March 10, 2026):

At every Exit signal (Stop Loss, Take Profit or Manual Sell), the bot now performs a proactive "Blind Cancel":

  1. Wait 500 milliseconds (to ensure synchronization of Alpaca servers).
  2. Wait 500 milliseconds (to ensure synchronization of Alpaca servers).
  3. Send the liquidation Market Sell order.

This logic releases the blocked amount of shares and is designed to make the liquidation succeed reliably, eliminating the 403 error.

10.8 Seeding Price Cache at Exit

The autopilot uses state.last_prices for risk checks. When exiting a position, the current price may not be in the cache (if the symbol is no longer actively streaming). The solution:

Before sending the close command, the autopilot copies current_price from the Alpaca position data to last_prices. This prevents the "NO PRICE DATA for [SYMBOL]" error.


11. SAFETY GATES

The safety filters are independent of the strategy and run before each potential entry. Even if the strategy generates a strong signal, if a filter blocks, the entry is NOT made.

11.1 Full List of Filters

#FilterWhen it BlocksMessage in Log
1Circuit BreakerLevel != NORMALCIRCUIT BREAKER: [level]
2Spread GuardSpread > configured limitSPREAD GUARD: spread [x] > max [y]
3OFI FilterOFI does not confirm the direction of the signalOFI FILTER: signal blocked
4CooldownInsufficient time since last entryCOOLDOWN: [x]s remaining
5Max PositionsMaximum number of positions reachedMAX POSITIONS: [n] reached
6Feeling FilterFeeling too negative to buy (or too positive to sell)SENTIMENT FILTER: blocked
7Price ValidityThe price is 0 or invalidNO PRICE DATA

11.2 Spread Guard โ€” Details

What is the Spread? The difference between the best bid and the best ask in the orderbook.

Formula: spread_pct = (best_ask - best_bid) / midpoint * 100

Configurable threshold: The SPREAD GUARD threshold is controlled by max_spread_bps in the HFT Engine tab (Safety section). Default: 50 bps (0.50%). Configurable range: 1 โ€” 500 bps. Previously it was hardcoded to 15 bps; now it directly uses the value from settings.

Conversion: max_spread_bps / 100 = procent maxim spread acceptat. Example: 50 bps = 0.50%, 200 bps = 2.00%.

Why it's important: A large spread means you pay an "entry cost" high. On liquid markets (broad-cap, BTC/USD), the spread is 5-20 bps. On low-volume micro-caps, it can be 100-300 bps. Adjust max_spread_bps according to the type of traded assets.

SPREAD GUARD messages in the log:

Recommendations per asset type:

Overnight/No-Data Exception: If the reported spread is 0.0 bps (no data outside of business hours), the bot automatically becomes "safe" allowing transactions to position themselves instead of being artificially blocked by the lack of deep connection.

11.3 Advanced Safety Gates (S04.1) ๐Ÿ†•

Session 48 added 4 new configurable safety gates from the โฌก SAFETY GATES panel in the HFT Engine tab:

#trappingsSettingsEffectEffect
8VaR Fail-Closedvar_fail_closedMRBlock entry if there are no return data (fail-safe)
9Asset Check Hardasset_check_hard_gateMRReject orders when the assets API is unavailable
10Blackout Firstblackout_first_mins5Block entry in the first N minutes after open (9:30am ET)
11Blackout Lastblackout_last_mins5Block entry in the last N minutes before close (4:00 PM ET)

Blackout Exempt Symbols: Symbols that bypass the blackout (ex: SPY, QQQ). Configurable in the UI.

Min Dollar Volume: Scanner filter โ€” remove tickers with price ร— volume < $5M (default). Prevents trading on illiquid instruments.

Validation Layer: Automatic warnings if:

11.4 How to Interpret the Log

When you see many SPREAD GUARD or OFI FILTER messages, it does not mean that the bot is broken. It means:


12. GENETIC OPTIMIZER โ€” AUTOMATIC EVOLUTION OF PARAMETERS

12.1 What optimizes

ParameterDefaultrank
fusion_threshold50.0ยฑ15% of safety rails
tp_percent (Take Profit)2.5%0.5% โ€” rails*1.15
sl_percent (Stop Loss)2.5%0.5% โ€” rails*1.15
trail_gap_pct1.5%0.3% โ€” rails*1.15
min_confidence0.300.10 โ€” 0.90
ofi_filter_enabledfalse90% keep, 10% flip
nexus_buy_threshold_pct60%50 โ€” 90

12.2 How it works

Population: 20 individuals (sets of parameters)

Evolution cycle (every 60 seconds):

  1. Fitness evaluation on in-sample data (first 70% of candles)
  2. Sort by fitness
  3. Selection: Top 5 = elites (survive intact)
  4. Reproduction: 15 new offspring from combinations of elites
  1. Mutation: Each parameter ยฑ15% with random probability
  2. OOS validation: The champion is tested on the out-of-sample data (the last 30%)
  3. Promotion: The champion is ONLY promoted if:

12.3 Walk-Forward Backtest

12.4 Safety Rails

All parameters are clamped within strict limits:

12.5 What you see in the UI


Effect

13.1 The 4 Levels

LevelTriggerEffectUI color
NORMALDaily PnL > -2% and DD > -5%Normal trading, full sizeVerdant
WARNINGDaily PnL โ‰ค -2%Halved positions (50%)Yellow
HALTDaily PnL โ‰ค -3%New entries BLOCKEDOrange
PANICDD โ‰ค -5% OR Daily PnL โ‰ค -5%Kill switch โ€” LIQUIDATE EVERYTHINGRed

13.2 How it works

13.3 Reset

13.4 Emergency Liquidation

The LIQUIDATE ALL button in the UI:

  1. Activate the kill switch
  2. Block the entrances
  3. Cancel ALL open orders
  4. Close ALL positions
  5. Issue event "breaker-triggered" with PANIC level

14. DRY RUN MODE โ€” SIMULATION WITHOUT RISK

14.1 What it does

When Dry Run is activated:

14.2 Activation/Deactivation

Persistence: The Dry Run state is saved in titan_settings.json. When restarting, the bot remembers whether it was in Dry Run or not.

Default (S72): Fresh install starts with dry_run_enabled: true. Live trading must be activated explicitly.

Visual guard (S72): When dry_run is OFF (live trading), the UI displays a pulsating red border on the entire screen + banner LIVE TRADING โ€” DRY RUN OFF to prevent accidental trading.

14.3 What happens in Dry Run


15. WATCHDOG AND TELEMETRY

15.1 Watchdog โ€” Monitoring Loops

Each loop in the background sends a heartbeat at each iteration. The watchdog monitors:

Watched loops (13): autopilot, nexus, volatility, equity_sync, position_recon, trade_updates, ai_scanner, daily_reset, genetic_evo, catalyst_watchdog, streamer, news, telegram.

15.2 Dead Loop Detection

15.3 Cancel/Join Contract on Respawn (S03)

The watchdog stores one AbortHandle per loop. On respawn:

  1. Abort -- the old task is explicitly aborted (it no longer runs in parallel)
  2. Spawn -- newly started task and stored handle
  3. Log -- "Aborted old task handle before respawn"

This eliminates the risk of split-brain when a "dead" loop it is still running and a new spawn duplicates it.

15.4 Generation ID โ€” Automatic Invalidation (S03)

session_generation is a counter AtomicU64 on TitanState, incremented on respawn of critical loops: streamer, autopilot, trade_updates.

Each critical loop captures the generation at the start. At each tick, check state.current_generation() == my_generation. If it does not coincide, the loop automatically exits with a log:

"Generation mismatch โ€” exiting stale autopilot instance"

Effect: operations from the previous generation are automatically invalidated (fail-closed). There is no window in which two instances of the same loop process orders simultaneously.

15.5 What you see in the UI (LOOP HEARTBEATS)

LOOP HEARTBEATS  ALL ALIVE
autopilot      1s/214        (214 tick-uri, ultimul acum 1s)
nexus          0s/641        (641 tick-uri, ultimul acum <1s)
l2_stream      0s/79991      (79991 mesaje procesate)
trade_updates  13s/22        (22 mesaje, ultimul acum 13s)
news           120s/5        (5 fetch-uri, interval 300s)
telegram       0s/48         (48 poll-uri)
...

15.6 Detailed Telemetry

The command get_telemetry returns per loop:

15.7 Watchdog Health Event (S03b)

At every 30-second tick, the watchdog supervisor issues an event watchdog-health to the frontend with the complete snapshot of all loops, the current generation and the number of generation mismatches:

{
  "loops": [ { "name": "autopilot", "tick_count": 214, "uptime_secs": 3600.5, ... } ],
  "generation": 3,
  "generation_mismatches": 1
}

This gives continuous visibility on the status of all loops, not just the dead ones.

15.8 Generation Mismatch Counter (S03b)

generation_mismatch_count is a AtomicU64 on TitanState. Automatically increased in the 3 critical loops (autopilot, trade_updates, streamer) when it detects a generation mismatch and exits. The value appears in the watchdog-health event under the generation_mismatches key.

15.9 Snapshot Integrity Hash (S03b)

At each save_state_snapshot, after JSON serialization, SHA-256 is calculated on the payload and written in a .sha256 file along with the snapshot. At load_state_snapshot, if the file .sha256 exists, the hash is checked. Mismatch = log error + snapshot rejected (corrupted data is not restored).


16. LOGGING AND REPORTS

16.1 Structured Logging

16.2 Session Reports

At shutdown and daily reset (09:30 ET), a JSON report is saved:

Location: ~/titan_hft_rust/reports/session_YYYY-MM-DD.json

Content:

16.3 Activity Log (UI)

All important events appear in the ACTIVITY LOG panel:


17. BACKTESTING

17.1 Types of Backtest

TypeDescriptionCommand
Single BacktestA symbol, a timeframerun_backtest
TF SweepsOne symbol, all timeframesrun_backtest_sweep
Multi SweepMore symbols, all TFsrun_backtest_sweep_multi
Quick BacktestWith the active parameters and the current symbolrun_backtest_now

1m, 5m, 15m, 30m, 1h, 4h, 1d

1m, 5m, 15m, 30m, 1h, 4h, 1d

17.3 Export

17.4 Auto-Optimize

The AUTO TUNE TF button runs optimize_timeframe:


18. PROFESSIONAL SCHEDULE

18.1 Bookstore

TradingView LightweightCharts โ€” professional chart with:

18.2 Available Indicators

IndicatorfriedConfigurator
EMA 9Main chartPeriod
EMA 50Main chartPeriod
EMA 200Main chartPeriod
VWAPMain chart-
Bollinger BandsMain chartPeriod, StdDev
RSISub-chartPeriod (lines 30/50/70)
MACDSub-chartFast/Slow/Signal
ADXSub-chartPeriod (lines 20/25)
Oracle ScoreSub-chart-

18.3 Drawing Tools

18.4 Special Functions

18.5 TITAN Oracle Fullscreen

The Oracle histogram can be viewed fullscreen:

18.6 Live Feed

Below the chart is displayed:


19. NEW TABS (NEWS AI, JOURNAL, HFT ENGINE, PERFORMANCE)

19.1 News AI (tab-1)

Tab dedicated to monitoring news with sentiment analysis.

Components:

Sentiment Analysis:

19.2 Journal (tab-3)

Persistent transaction history.

Functionality:

19.3 HFT Engine (tab-4)

Advanced settings for the trading engine:

Entry Parameters:

Exit Parameters:

Safety:

Alerting:

Sliders in HFT Engine: They have reduced width (15% of normal) to take up less space and look compact.

SPREAD GUARD โ€” Connection to Settings:

Parameter max_spread_bps in HFT Engine directly controls the SPREAD GUARD threshold in the autopilot. Previously it was hardcoded at 15 bps (0.15%), now it uses the value from settings (default 50 bps = 0.50%). This value determines the maximum bid-ask spread accepted to enter a trade. Assets with low liquidity (micro-caps) have spreads of 100-300 bps and require an increase in this value.

19.4 Performance Dashboard

Integrated in the TITAN SAFETY panel and in the backtest tabs:

KPI Cards:


20. AI SCANNER โ€” FUSION ASSET DISCOVERY

20.1 What is AI Scanner

AI Scanner is an intelligent engine for discovering profitable assets. It combines quantitative filters (quant) with FUSION scoring (Oracle + GPU Nexus) and automatic backtest on all timeframes to find and classify the most promising US stocks.

Accessible from the AI Scanner tab (tab-6) in the tab bar in the central panel.

20.2 The Scanning Pipeline

Scanning takes place in 4 phases:

  1. Fetch Assets โ€” Download the complete list of active stocks from Alpaca (~8000+)
  2. Snapshots โ€” Load daily data (price, volume, previous day) in batches of 1000
  3. Pre-filter Quant โ€” Apply quantitative filters and sort by composite score
  4. FUSION Scoring + Sweep Backtest โ€” For each candidate:

20.3 Filters Quantitative (Pre-filter)

FilterCondition
Price$1 - $500
Minimum Volume500,000
Minimum Change> 1% (absolute)
RVOLvolume_today / volume_yesterday
Gap %Volume spikes
Volume spikesvolumes > 2x prev_volume

Pre-filter scoring:

20.4 AI Score โ€” Composite Formula

AI Score = 0.40 * FUSION_normalized +
           0.25 * Sharpe_normalized +
           0.20 * Win_Rate +
           0.15 * ProfitFactor_normalized

Conditions: minimum 3 trades in backtest and Oracle confidence > 0.15. Otherwise, AI Score = FUSION * 0.5.

20.5 Multi-Timeframe Sweep Backtest

Each scanned asset is backtested on all 8 timeframes. The timeframe with the best combined score (Sharpe + Return * 0.01) is kept. The BEST TF column in the table shows the optimal timeframe.

The depth of the backtest depends on the data available from Alpaca (up to 365 days, limit 1000 candles per timeframe).

20.6 AI Scanner Table Columns

ColumnDescription
#Rank by AI Score
SYMBOLAction symbol
PRICESCurrent price
CHG%Percentage change compared to the previous day
RVOLRelative Volume (today / yesterday)
GAP%Gap at the opening compared to the previous close
VOLVolume of the day
FLOATEstimated float category: LOW / MED / HIGH
ORACLESOracle Score (-100 to +100)
dietMarket regime: Trending / MeanReverting / Chaotic
NEXUSGPU Nexus buy % (150K agents)
FUSIONCombined FUSION Score (-100 to +100)
SIGNALSignal: LONG / SHORT / NEUTRAL
BEST TFThe optimal timeframe from the sweep backtest
BETRAYEDNumber of transactions from the backtest
WIN%Win rate from backtest
SNAKERET%
RET%Return % from backtest
EXPECTExpectancy per trade from backtest
YOU GOT SCOREFinal Composite Score (0-100)

20.7 UI Functionalities

20.8 SMART PICKS (Premium Filtered Assets)

The โšก SMART PICKS panel is a sub-section of AI Scanner that cleans out the noise and shows only the "cream" market.

The filter performs a POST-scan and retains exclusively the momentum (high-reward) candidates:

Smart Picks functionalities:

20.9 Auto-Scan (Background)

20.10 Injection into HFT Engine

After scanning, select the desired assets with the checkbox and press INJECT SELECTED โ†’ HFT. This:

  1. Add symbols to list hft_targets from titan_settings.json
  2. Activate multi_symbol_enabled = true
  3. The autopilot will start evaluating these symbols on the next iteration

21. MANAGEMENT OF POSITIONS AND FUNDS

21.1 Positions

21.2 Equity Sync

21.3 Trade Updates (Fill Notifications)

21.4 Funds

ActionButtonwhat is he doing
Top Up UserTOPUP USERAdd to the user's virtual storage
Top Up BotTOP UPAllocate funds to the bot from the user deposit
WithdrawWITHDRAWWithdraw funds from the bot to the user

22. ALL THE LOOPS IN THE BACKGROUND

#LoopIntervalwhat is he doing
1autopilot_loop1.5sAutomatic trading: analysis, entries, exits, trailing stop
2nexus_loop500 msGPU Nexus: 150K agents vote, calculated consensus
3update_volatility_loop30sUpdates the volatility cache
4equity_sync_loop30sSynchronize equity on Alpaca
5position_reconciliation_loop15s6
6trade_updates_streamcontinuouslyWebSocket: fill notifications in real time
7continuouslycontinuouslyL2 orderbook stream (crypto v1beta3 / stocks SIP)
8daily_reset_loop60s (check)Resets daily at 9:30am ET
9genetic_evolution_loop60sGenetic evolution of trading parameters
10watchdog_supervisor30sDetects dead loops
11startup_health_checkonce (boot)Check all dependencies
12streamer::run_streamerEvent DrivenPrice streaming and heatmap
13ai_scan_loop30min (heartbeat 60s)AI Scanner: pre-filter + FUSION + sweep backtest
14state_snapshot_loop30sSnapshot state on disk (crash recovery)

23. ALL ORDERS AVAILABLE

23.1 Trading

Commandwhat is he doing
submit_orderSend order (through safety checks + risk sizing)
liquidate_all_positionsClose all positions
cancel_all_ordersCancel all open orders
emergency_liquidateKill switch + liquidated
set_dry_runEnables/disables the simulation

23.2 Strategy

Commandwhat is he doing
set_strategy_modeSet Oracle / GPU / Fusion
toggle_strategy_modeCycle between modes
set_nexus_alphaAdjust the Fusion blend (0-1)
get_nexus_statusNexus GPU status

23.3 Genetic Optimizer

Commandwhat is he doing
freeze_evolutionStops Fusion evolution
resume_evolutionFusion evolution starts
get_evolution_statsFusion optimizer statistics
get_active_trading_paramsActive Fusion parameters
run_backtest_nowQuick backtest

SmartTrend Genetic (S13)

Commandwhat is he doing
get_st_evolution_statsSmartTrend optimizer statistics (gen, fitness, sharpe, diversity, champion params)
get_st_fitness_historyIS/OOS fitness history per generation (for convergence chart)
get_st_champion_paramsDrill-down champion: each param with value, default, delta%, min, max
run_comparison_backtest_cmdRun Fusion + SmartTrend on the same candle, return metrics side-by-side
freeze_st_evolutionStops SmartTrend evolution independently
resume_st_evolutionSmartTrend evolution starts

Conditional behavior: When StrategyMode::SmartTrend is active, genetic_evolution_loop automatically uses SmartTrendParams and smarttrend_walk_forward_backtest (real FSM: Flat/Stalking/Entry/InTrade/Trail). In any other mode, run the classic Fusion optimizer with TradingParams. The two optimizers are completely independent.

Evolvable SmartTrendParams (12): macro_weight, micro_weight, momentum_weight, entry_threshold, stalking_threshold, changepoint_reset, trail_tighten_pct, hysteresis_margin, bayesian_halflife, stabilization_window, dominant_cycle_filter, risk_per_trade. Each has safety rails (min/max) hardcoded.

Fitness SmartTrend: sharpe * min(PF, 5) + trade_count_bonus + win_rate_bonus + stability_bonus - dd_penalty. Win rate active bonus over 55%. Stability bonus when avg_bars_in_trade between 3-30. OOS validation: champion must be sharpe > 0 and total_pnl > 0 on 30% out-of-sample.

UI Evolution Panel (S13):

23.4 Risk & Safety

Commandwhat is he doing
get_risk_statusCircuit breaker + session analytics
reset_circuit_breakerManual breaker reset
reset_daily_analyticsReset daily analytics
get_ofi_statusOFI status live

23.5 Account & fund

Commandwhat is he doing
connect_api / update_api_keysConnect/update API keys
get_account_snapshotAlpaca account snapshot
topup_user / topup_bot / withdraw_botFund management
get_wallet_snapshotWallet status

23.6 Backtesting

Commandwhat is he doing
run_backtestBacktest alone
run_backtest_sweepSweep all TFs
run_backtest_sweep_multiMulti-symbol sweep
optimize_timeframeTF auto-optimization
export_backtest_csv/json/htmlExport results

23.7 Monitoring

Commandwhat is he doing
get_telemetryTelemetry loops
get_monitor_snapshotHardware (CPU, GPU, RAM, NET)
graceful_shutdownGracious stop

23.8 Settings & Persistence

Commandwhat is he doing
update_settingsUpdates any setting (field + value) โ€” includes bot_trade_size, circuit_breaker_limit, dry_run_enabled, strategy_mode_name
get_favoritesReturns the list of favorite symbols
add_favoriteAdd symbol to favorites (persistent)
remove_favoriteDelete symbol from favorites (persistent)

23.9 AI Scanner

Commandwhat is he doing
run_ai_scanStart AI scan with configurable number of candidates (50/100/200)
activate_scan_targetsInjects selected symbols into HFT Engine targets

24. STRUCTURE OF FILES

~/titan_hft_rust/
โ”œโ”€โ”€ titan_keys.json              โ† API keys (CONFIDENTIAL)
โ”œโ”€โ”€ titan_settings.json          โ† Setari persistente (dry_run, strategy_mode, favorites, etc.)
โ”œโ”€โ”€ titan_wallet.json            โ† Stare portofel (user deposit, bot alloc)
โ”œโ”€โ”€ titan_state_snapshot.json    โ† State snapshot (crash recovery, auto-resume)
โ”œโ”€โ”€ titan_position_blacklist.json โ† Blacklist pozitii force-closed
โ”œโ”€โ”€ TITAN_MANUAL.md              โ† This manual
โ”œโ”€โ”€ logs/
โ”‚   โ””โ”€โ”€ titan.log.YYYY-MM-DD    โ† Loguri zilnice (rotatie automata)
โ”œโ”€โ”€ reports/
โ”‚   โ””โ”€โ”€ session_YYYY-MM-DD.json โ† Rapoarte zilnice
โ”œโ”€โ”€ titan_hft_rust/
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ””โ”€โ”€ index.html           โ† Frontend UI (sursa)
โ”‚   โ”œโ”€โ”€ dist/
โ”‚   โ”‚   โ””โ”€โ”€ index.html           โ† Frontend build (embedded in binary)
โ”‚   โ””โ”€โ”€ src-tauri/
โ”‚       โ”œโ”€โ”€ Cargo.toml            โ† Dependente Rust
โ”‚       โ”œโ”€โ”€ tauri.conf.json       โ† Configurare Tauri (distDir โ†’ ../dist)
โ”‚       โ”œโ”€โ”€ src/
โ”‚       โ”‚   โ”œโ”€โ”€ main.rs           โ† Orchestrator (~60 comenzi Tauri, 12 loop-uri)
โ”‚       โ”‚   โ”œโ”€โ”€ titan_oracle.rs   โ† 7 indicatori AI
โ”‚       โ”‚   โ”œโ”€โ”€ gpu.rs            โ† GPU compute (WGPU)
โ”‚       โ”‚   โ”œโ”€โ”€ risk.rs           โ† Circuit breaker, risk management
โ”‚       โ”‚   โ”œโ”€โ”€ genetic.rs        โ† Optimizator genetic
โ”‚       โ”‚   โ”œโ”€โ”€ l2_heatmap.rs     โ† L2 orderbook module (date procesate in streamer.rs)
โ”‚       โ”‚   โ”œโ”€โ”€ watchdog.rs       โ† Loop monitoring, telemetrie
โ”‚       โ”‚   โ”œโ”€โ”€ titan_log.rs      โ† Logging structurat
โ”‚       โ”‚   โ”œโ”€โ”€ indicators.rs     โ† Indicatori clasici
โ”‚       โ”‚   โ”œโ”€โ”€ strategy.rs       โ† Logica strategie
โ”‚       โ”‚   โ”œโ”€โ”€ streamer.rs       โ† Price streaming + L2/OFI processing (WebSocket unic)
โ”‚       โ”‚   โ”œโ”€โ”€ scanner.rs        โ† Market scanner
โ”‚       โ”‚   โ”œโ”€โ”€ monitor.rs        โ† Hardware monitor
โ”‚       โ”‚   โ”œโ”€โ”€ sentiment.rs      โ† Sentiment analysis (keyword lexicon)
โ”‚       โ”‚   โ”œโ”€โ”€ journal.rs        โ† Jurnal tranzactii persistent (NOU)
โ”‚       โ”‚   โ”œโ”€โ”€ app_state.rs      โ† State definitions + AppSettings
โ”‚       โ”‚   โ”œโ”€โ”€ nexus_kernel.wgsl โ† GPU shader: 150K agenti
โ”‚       โ”‚   โ”œโ”€โ”€ gpu_indicators.wgsl
โ”‚       โ”‚   โ”œโ”€โ”€ gpu_indicators_batch.wgsl
โ”‚       โ”‚   โ””โ”€โ”€ gpu_dot.wgsl
โ”‚       โ””โ”€โ”€ target/
โ”‚           โ””โ”€โ”€ release/
โ”‚               โ””โ”€โ”€ titan_hft_rust  โ† EXECUTABIL FINAL

25. FREQUENT PROBLEMS AND SOLUTIONS

25.1 L2 Stream does not receive data

Symptom: OFI LIVE shows 0.0, BID/ASK = 0

Possible causes:

Verification: In the terminal, search for:

L2 SUB RESPONSE: [{"T":"subscription","orderbooks":["BTC/USD"],...}]

25.2 Trade Updates does not authenticate

Symptom: "Auth failed" in the Activity Log

Solution: Titan automatically tries two auth formats:

  1. authenticate with key_id/secret_key (format v2)
  2. auth with key/secret (legacy format)

Check the Activity Log for the exact message from the server.

25.3 Circuit Breaker activates

Symptom: TITAN SAFETY shows CAUTION/HALT/PANIC

Solution:

25.4 Dead loop (DEAD)

Symptom: LOOP HEARTBEATS shows a loop with > 120s

Solution: Restart the application. If it persists, check the logs for errors specific to the respective loop.

25.5 GPU is not detected

Symptom: Health Check shows "GPU (WGPU): FAILED"

Solution:

25.6 EGL spam in terminal

Symptom: Repetitive EGL/WebKit messages in terminal

Solution: Titan automatically sets WEBKIT_DISABLE_COMPOSITING_MODE=1 at startup. If it persists, add to .bashrc:

export WEBKIT_DISABLE_COMPOSITING_MODE=1

25.7 "Connection limit exceeded (code 406)"

Symptom: In Activity Log appears repeatedly:

L2 STREAM AUTH ERROR: [{"T":"error","code":406,"msg":"connection limit exceeded"}]
L2 STREAM: Quick disconnect โ€” failure #N, backoff Xs

Cause: Alpaca allows a limited number of simultaneous WebSocket connections per account. If two components open connections to the same stream, the limit is reached.

Solution: This problem was solved by consolidating all L2 connections in streamer.rs. If they reappear:

  1. Check that there are no multiple instances of the application
  2. Restart the application (kill โ†’ re-launch)
  3. Wait ~60 seconds for Alpaca to release the old connections

25.8 "AUTOPILOT EXIT FAILED: NO PRICE DATA"

Symptom: The autopilot repeatedly tries to close a position but fails.

Cause (resolved): The internal cache last_prices did not have the price of the symbol if it was not actively streaming.

Solution: The autopilot now automatically copies current_price from the cached Alpaca position data before sending the exit command. If it still appears:

  1. Check that the L2 stream is connected
  2. Check that the symbol is valid on Alpaca

25.9 "422 Unprocessable Entity: invalid crypto time_in_force"

Symptom: Crypto orders (BTC/USD, ETH/USD) fail with error 422.

Cause (resolved): Alpaca requires time_in_force: "gtc" for crypto, not "day".

Solution: Titan automatically detects crypto vs stocks and sets TIF correctly. This problem should not occur again.

25.10 The application runs old version after rebuild

Symptom: After changes in index.html, the application displays the old UI.

Possible causes:

  1. Tauri incremental build โ€” Do not re-embed the frontend if only HTML has changed
  2. WebKit cache โ€” The internal browser caches the old styles

Solution:

# 1. Sterge build cache-ul Tauri
rm -rf ~/titan_hft_rust/src-tauri/target/release/build/titan_hft_rust-*

# 2. Sterge WebKit cache
rm -rf ~/.cache/titan_hft_rust/WebKitCache

# 3. Rebuild
cd ~/titan_hft_rust/src-tauri && cargo build --release

# 4. Relanseaza aplicatia

25.11 Buttons/Tabs do not work (CSP)

Symptom: Clicking on a button (ex: HFT ENGINE tab) does nothing.

Cause: Tauri WebView blocks onclick="..." inline for reasons of Content Security Policy.

Solution: Use data- attributes and addEventListener instead of onclick:

<!-- Corect: -->
<button data-symtab="hft">HFT ENGINE</button>

<!-- Gresit (blocat de CSP): -->
<button onclick="switchSymbolTab('hft')">HFT ENGINE</button>

JavaScript attaches event listeners to DOMContentLoaded.

25.12 Invisible text in inputs/selections

Symptom: You cannot see the text in the input boxes in the sidebar.

Cause: WebKit applies native styles (white background, black text) that override the application's dark theme.

Solution: Applied with color-scheme: dark !important on all input/select elements in the sidebar:

#sidebar input, #sidebar select {
    background: #000 !important;
    color: #FFD700 !important;
    color-scheme: dark !important;
}

If it happens again after the rebuild, delete the WebKit cache (see 25.10).

25.13 SPREAD GUARD blocks all entries on an asset

Symptom: The log constantly shows SPREAD GUARD: X bps โ€” too wide, skipping entries and the bot never enters.

Cause: The asset has a natural spread higher than the configured max_spread_bps limit. Micro-caps (SOC, penny stocks) often have spreads of 100-300 bps.

Solution: Increase max_spread_bps from HFT Engine tab. Recommendations: 50 bps for large-caps, 100-200 bps for small/micro-caps. Alternatively, choose assets with better liquidity (volume > 2M, spread < 50 bps).

25.14 WATCHDOG: Dead loops โ€” ai_scanner or autopilot

Symptom: Red messages WATCHDOG: Dead loops: ai_scanner or autopilot in Activity Log.

Cause ai_scanner (resolved): Previously, ai_scan_loop sent heartbeat only every 30 minutes, exceeding the watchdog threshold of 120 seconds.

ai_scanner solution: The loop now sends a heartbeat every 60 seconds (under the 120s threshold), independent of the 30 minute scan interval.

Autopilot Cause: Autopilot may seem "dead" if SPREAD GUARD blocks constantly and the loop spends all the time in continue without reaching the effective execution. The heartbeat is sent at the beginning of each iteration (1.5s), so it shouldn't appear normally. If it appears, restart the application.

25.15 AI Scanner โ€” the scan takes a long time

Symptom: After clicking SCAN NOW, the progress bar advances very slowly (especially with 200 candidates).

Reason: Each candidate requires ~9 Alpaca API requests (1 for 5m candles + 8 for sweep backtest on all timeframes). With 200 candidates = ~1800 applications.

Solution: Alpaca rate limit is ~200 req/min. The scan with 200 candidates can take 10-15 minutes. Use 50 candidates for fast results (~3 minutes).


FINAL NOTE

Titan HFT is a complex system with multiple layers of security. The main recommendations:

  1. Always start in DRY RUN until you are comfortable with the behavior
  2. Monitor the Activity Log for anomalies
  3. Do not manually modify the thresholds Circuit Breaker without understanding the implications
  4. Let the Genetic Optimizer run for at least a few hours before trading live
  5. Check LOOP HEARTBEATS periodically โ€” all loops must be ALIVE
  6. Session Reports from ~/titan_hft_rust/reports/ are the source of truth for performance
  7. SPREAD GUARD messages are normal โ€” it means that the filters work and protect capital
  8. After frontend changes, delete WebKit cache and do a clean build (see section 25.10)
  9. Settings persist automatically in titan_settings.json โ€” dry_run, strategy_mode, favorites, trade size
  10. Strategy generates the signal, filters validate it โ€” see section 6 and 11 for details

26. CATALYST WATCHDOG โ€” SENTIENT NEWS FEED

Advanced real-time news monitoring system designed to identify "Black Swan" or major momentums in the Stocks market before they are fully digested by the market.

26.1 How it works

26.2 Severity Levels

slagSeverityColor
โ‰ฅ 0.85 or โ‰ค -0.85EXPLOSIVESGreen / Intense red
โ‰ฅ 0.50 or โ‰ค -0.50STRONGGreen / Red
โ‰ฅ 0.35MODERATEYellow
< 0.35MILDGray

26.3 Tab 7 โ€” Catalyst Watchdog Dashboard

Header:

Stats Bar (5 responsive cards):

Log Table (7 columns):

ColumnDescription
TIMEAlert time (HH:MM AM/PM)
SYMBOLTicker (click to open on the chart)
HEADLINENews title (clickable link)
SEVERITYColored badge (EXPLOSIVE/STRONG/MODERATE/MILD)
slagSentiment score (colored)
FEELINGBULLISH (green) / BEARISH (red)
actINJECT button (add to HFT Targets)

Filters: Symbol, Minimum Score, Sentiment (All/Bullish/Bearish)

Max rows: 100 (auto-eviction oldest)

26.4 Toast Notifications V3

26.5 Backend Commands

CommandDescription
test_catalyst_alertIssue bullish mock alert (NVDA, +0.98)
test_catalyst_bearishIssue bearish mock alert (TSLA, -0.92)
check_catalystCheck news by token, return CatalystCheckResult
get_news_feedReturns SentimentSnapshot with label_from_score()

27. SIGNALS AND ARROWS ON CHART

The visual signaling system is strategy-specific โ€” the arrows reflect the active strategy mode:

27.1 Oracle Mode โ€” Green/Red Arrows (Threshold ยฑ8.0)

27.2 Nexus GPU Mod โ€” Cyan/Pink Arrows (Momentum ยฑ0.02)

27.3 Fusion Mod โ€” Gold/Orange Arrows (Adaptive Threshold)

27.4 Changepoint Markers (All Modes)

27.5 Visibility Toggle

27.6 Colors per Mode (Quick Reference)

ModeBUYSellaThreshold
OracleGreen #00FF41Red #FF2B2Bยฑ8.0
GPU NexusCyan #00BFFFPink #FF6EC7ยฑ0.02 momentum
FusionGold #FFD700Orange #FF4500Adaptive (8.0ร—(1-ฮฑ) + 2.0ร—ฮฑ)
Changepointโ€”โ€”BOCPD prob > 0.7

28. TELEGRAM ALERTS โ€” MOBILE NOTIFICATIONS

Real-time alert system on the mobile phone via Telegram Bot API.

28.1 Initial Setup (BotFather)

  1. Open Telegram and search for @BotFather.
  2. Send /newbot and follow the steps to create a new bot.
  3. Copy Bot Token (format: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
  4. Send a message to your newly created bot (to initiate the conversation).
  5. Access https://api.telegram.org/bot<TOKEN>/getUpdates in the browser.
  6. Copy the chat_id from the JSON response (the number from "chat":{"id":123456789}).

28.2 Configuration in Titan

In the HFT Engine (tab-4) tab, the TELEGRAM ALERTS section:

28.3 Types of Alerts

EventWhen it is sentInformation included
Trade FillWhen executing an orderSymbol, side (BUY/SELL), quantity, price, PnL
Circuit BreakerUpon activation of PANICThe breaker level, the reason
CatalystWhen detecting a major newsSymbol, score, headline
Daily SummaryAt daily reset (9:30 a.m. ET)Total trades, win rate, PnL, profit factor

28.4 Security


29. RISK CORRELATION MATRIX

Correlation analysis between simultaneously traded symbols in Multi-Symbol mode, to avoid redundant exposure.

29.1 What is Correlation

The Pearson correlation measures how similar two assets move:

29.2 How it Works in Titan

At each entry attempt in Multi-Symbol mode:

  1. Titan downloads recent candles for the candidate symbol and already owned symbols.
  2. Calculates percentage returns from close prices.
  3. Apply pearson_correlation between the candidate and each existing position.
  4. If the correlation exceeds max_correlation (default 0.70), the entry is blocked.

Example: If you own AAPL and try to enter MSFT (correlation ~0.85), Titan blocks the entry because both are Large-Cap Tech and move similarly.

29.3 Configuration

In the HFT Engine (tab-4) tab:

29.4 Viewing in the UI

The RISK CORRELATION MATRIX section in tab-4 displays:


30. PERFORMANCE PORTFOLIO & REBALANCE

Analysis and optimization of the portfolio based on the historical performance in the Trade Journal.

30.1 Metrics Per Symbol

From the log data, Titan calculates for each symbol:

MetraDescription
TradesThe total number of transactions
Win RateThe percentage of profitable transactions
Total PnLCumulative profit/loss
Avg PnLAverage profit per transaction
Performance ScoreComposite score: win_rate * 40 + pnl_magnitude * 30 + trade_bonus * 30
TagClassification: STAR / GOOD / AVERAGE / UNDERPERFORMER

30.2 Risk Multiplier

Historical performance directly influences the size of future positions:

TagRisk MultiplierEffect
STAR1.5xHigher positions on performing symbols
GOOD1.2xSlightly higher positions
AVERAGE1.0xStandard size
UNDERPERFORMER0.5xHalved positions on weak symbols

30.3 Rebalancing

The REBALANCE button in tab-4 analyzes the portfolio and suggests:

30.4 Viewing in the UI

PORTFOLIO PERFORMANCE section from tab-4:


31. ATR DYNAMIC STOP-LOSS & PARTIAL PROFIT TAKING

Volatility adaptive exit system, replacing fixed stop-loss/take-profit with dynamic values โ€‹โ€‹based on ATR.

31.1 What is ATR (Average True Range)

ATR measures the average volatility of an instrument over a given period. True Range = max(High-Low, |High-PrevClose|, |Low-PrevClose|). ATR = average True Range over N periods (default 14).

31.2 How Stop-Loss ATR Works

Instead of a fixed stop-loss (eg -2.5%), Titan calculates:

stop_loss_price = entry_price - ATR * atr_stop_multiplier    (pentru LONG)
stop_loss_price = entry_price + ATR * atr_stop_multiplier    (pentru SHORT)

take_profit_price = entry_price + ATR * atr_take_multiplier  (pentru LONG)
take_profit_price = entry_price - ATR * atr_take_multiplier  (pentru SHORT)

Advantage: On volatile markets, the stop is automatically widened (prevents premature stop-out). In calm markets, the stop is tightened (protects the profit).

31.3 Configuration

In the HFT Engine (tab-4) tab, the ATR DYNAMIC STOPS section:

ParameterDefaultrankDescription
Stop-Loss (x ATR)2.00.5 - 5.0ATR multiplier for stop-loss
3.03.01.0 - 10.0ATR multiplier for take-profit
Partial Take %50%25% - 75%The percentage of the partially sold position
Partial Profit EnableOFFON/OFFEnables/disables partial profit

31.4 Partial Profit Taking

When the profit reaches 50% of the take-profit target:

  1. Titan automatically sells partial_take_pct (ex: 50%) of the position.
  2. The rest of the position continues with active trailing stop.
  3. "PARTIAL TAKE: balance X% of SYMBOL" is logged. in the Activity Log.
  4. Telegram alert is sent (if enabled).

Example: Entry AAPL $180, TP = $186 (ATR * 3.0 = $6). At $183 (50% of $6 = $3 profit), sell 50% of the position. The rest remains with a trailing stop.

31.5 Trailing Stop with ATR

The trailing stop is calculated based on ATR:

trail_pct = ATR / entry_price * atr_stop_multiplier * 0.5

trail_high (LONG) or trail_low (SHORT) is updated at each tick. Exit if the price withdraws by > trail_pct from peak.


32. WEB DASHBOARD โ€” LOCAL ACCESS

Web dashboard served by an embedded HTTP server (axum) directly from Titan, accessible on localhost.

32.1 Access

32.2 What It Displays

32.3 API Endpoints

EndpointMethodAuthDescription
/api/healthGETNotHealth check: status, uptime, version
/api/build-infoGETNotBuild info: version, git hash, build date, uptime (S04)
get_state_healthbulls--State decomposition health: lock contention per sub-state (S04.5)
/GETBearerComplete HTML cyber-HUD dashboard
/api/statusGETBearerEquity, autopilot, strategy, breaker, dry_run
/api/positionsGETBearerList of positions with PnL
/api/tradesGETBearerThe last 20 trades
/api/statsGETBearerWin rate, PnL, profit factor
/api/autopilotPOSTBearerToggle autopilot
/wsGETBearerWebSocket live push (status, trade, alert)

32.4 Security

32.5 Configuration

In the tab HFT Engine (tab-4), section WEB DASHBOARD:


32.6 State Architecture (S04.5)

Starting with V4.0, TitanState is decomposed into 4 distinct sub-states, each with documented internal lock ordering:

Sub-statesModuleFieldsPurpose
TradingStatetrading_state.rs10 MutexTrail tracking, entry metadata, exit inflight, blacklist, cooldowns
MarketDataStatemarket_state.rs5 Mutex + ArcSwapPrices, candle buffers, indicator cache, vol/bars cache, OFI
RiskStaterisk_state.rs3 Mutex + atomicsCircuit breaker, session analytics, drawdown, flash crash
ScanStatescan_state.rs5 MutexAI scan pipeline: best-TF, results, progress, prefilter, cancel

Lock ordering global: 40 slots in 9 groups, fully documented in state.rs. Any purchase of Mutex must respect the order.

State Health Dots: In the STATUS sidebar, 4 mini-dots (TRD/MKT/RSK/SCN) show the health of the sub-states in real time:

Hover on each dot displays details (locks free / contended, session generation).

Tauri command: get_state_health returns per sub-state: name, fields, locks_ok, locks_contended, plus session_generation and uptime.


33. STATE PERSISTENCE โ€” CRASH RECOVERY

Complete snapshot/restore system that ensures that the bot survives crashes and restarts without losing context.

33.1 What is Saved

Every 30 seconds, Titan writes a complete snapshot to ~/titan_hft_rust/titan_state_snapshot.json:

DateDescription
trail_highs / trail_lowsTrailing stop tracking per symbol
partial_takenPartial profit flags per symbol
last_pricesCache prices per symbol
symbol_best_tfOptimum timeframe per symbol from AI scan
nexus_fusion_alphaCurrent fusion alpha value
session_analyticsEquity, trades, PnL, drawdown, trade_pnls complete
dd_velocity_ringRing buffer drawdown velocity (timestamp, dd_pct) โ€” restored on restart (S03)
session_generationSession generation counter โ€” monotonic, stale order invalidation (S03)
last_scan_resultsAll AI scan table (all rows)
scan_metaWas there a scan in progress? How many processed? Total required?

33.2 Auto-Restore at Startup

At startup, Titan searches for the snapshot and restores it automatically:

  1. Read ~/titan_hft_rust/titan_state_snapshot.json
  2. Check age โ€” ignore snapshots older than 12 hours (data would be too stale)
  3. Populates trail stops, prices, analytics, scan results in memory
  4. Issues ai-scan-update to the frontend โ€” the scan table appears instant without re-scanning
  5. Displays in the Activity Log: "SNAPSHOT RESTORE: X scan results loaded, Y trail stops, Z cached prices"

33.3 Auto-Resume Scan (Continued from Point of Interruption)

If the snapshot indicates that a scan was in progress when the application stopped:

  1. Partial results appear instant in the UI (ex: 158 symbols already processed)
  2. Wait 5 seconds (for the APIs to connect)
  3. Continue the scan where it left off (ex: from 158/200), processing only the remaining symbols
  4. The progress bar starts from the breakpoint (eg: 158/200)
  5. At the end, it goes through the old + new results, re-sorts, and displays the complete list
  6. Displays: "AUTO-RESUME: Continuing scan from 158/200 (42 remaining)"

How it works technically: The pre-filter queue (the complete list of symbols to be processed) is saved in the snapshot. In summary, a HashSet is built from the already processed symbols and only the remaining ones are processed. The results are incremental (saved along the way in states for safety).

33.4 Graceful Shutdown

When pressing the SHUTDOWN button, Titan saves a last snapshot before shutdown, ensuring that absolutely all the state is on the disk.

33.5 Atomic Writing

The snapshot is written atomically (write to .tmp file, then rename) to prevent corruption during a crash during writing. The Journal (TradeJournal::save()) uses the same pattern (S72).

33.5b Delta Compression (S72)

save_state_snapshot compares the SHA-256 hash of the new snapshot with the previous hash (stored in .sha256 sidecar file). If they are identical, writing to disk is omitted. Significantly reduces I/O during idle periods.

33.6 What NOT to Save (Intentional)

DateReason
bars_cacheStale candles, re-fetch on request
gpu_score_cacheRecalculated per tick
ofi_stateLive L2 data, meaningless after restart
nexus_consensusRecalculated by GPU agents
news_cacheRe-fetch from background loop
circuit_breakerSafer to reset after crash

34. SMART SCORE V4 โ€” INSTITUTIONAL RANKING

The AI โ€‹โ€‹Scanner asset ranking formula, optimized to favor quality and consistency.

34.1 Basic Formula

base = 0.35 * Win% + 0.22 * Sharpe_norm + 0.15 * Trades_norm
     + 0.10 * PF_norm + 0.10 * Expect_norm + 0.08 * Fusion_norm

34.2 Multiplier Win% (Most Important)

Win RateMultiplierEffect
< 30%0.25xAggressive Removal
30-38%0.45xSevere Penalty
38-45%0.60xPenalty moderate
45-50%0.82xSub-par but acceptable
50-60%1.00xStandard
60-70%1.12xBonus
70%+1.20xMaximum Bonus

34.3 Other Multipliers

FactorConditionMultiplier
Trades< 50.35x
Trades5-80.60x
Trades8-120.85x
Trades20+1.05x (modest)
Sharpe< 0.30.45x
Sharpe0.3-0.70.70x
Sharpe0.7-1.00.88x
Sharpe2.0+1.12x
Profit Factor< 0.80.55x
Expectancy< 00.40x

34.4 Consistency Bonus (NEW in V4)

Symbols that excel on all axes receive an additional bonus:

ConditionBonus
Win >= 50% AND Sharpe >= 1.0 AND Trades >= 101.15x
Win >= 55% AND Sharpe >= 1.01.08x

34.5 Hard Kill

If any of the following conditions are true, the SMART score is reduced to fusion_normalized * 0.10:

34.6 Result

The formula produces a ranking where the top 20 SMART PICKS are predominantly symbols with Win% > 50%, Sharpe > 1.0, and enough trades for statistical significance. Symbols with Win% below 40% can no longer compensate by a large number of trades.


35. AUTO ENTRY โ€” AUTOMATIC ENTRY CONTROL

35.1 What It Is

The AUTO ENTRY toggle in the sidebar (TRADING CONTROLS section) controls whether the bot opens new positions automatically.

35.2 AUTOPILOT vs AUTO ENTRY distinction

ToggleWhat it doesDefault
AUTOPILOTManages exits: stop-loss, take-profit, trailing stop on existing positionsON
AUTO ENTRYOpen new positions automatically based on FUSION/Nexus signalsOFF

Important: Both must be ON for fully automatic trading. AUTOPILOT alone = the bot closes positions but does not open new ones.

35.3 Safety Gates for Entry

When AUTO ENTRY is ON, the bot checks the following before opening a position:

  1. Circuit Breaker = NORMAL
  2. Spread Guard < limit
  3. Cooldown elapsed
  4. Max positions not reached
  5. Strategy score >= threshold
  6. OFI confirms direction
  7. Nexus consensus >= threshold
  8. Correlation check (if Multi-Symbol)

35.4 Recommendation

Activate AUTO ENTRY only after what:


36. SIGNAL ALIGNMENT โ€” FUSION-AWARE AUTOPILOT & CAUSAL CHART

36.1 Previous Problem

Two distinct problems affected the quality of the signals:

  1. Autopilot ignores GPU/Fusion: Function compute_strategy_score generates the LONG/SHORT/NEUTRAL signal using ONLY Oracle with threshold +/-30. In FUSION mode, the Nexus GPU was completely ignored. On symbols with low Oracle score (~0.03), the signal was always NEUTRAL โ€” the bot never enters.
  1. Chart signals with hindsight: adaptive_thresholds calculates 80/20 percentiles on ALL scores in the visible window (hindsight). A SELL signal at $17.60 appeared only because the algorithm "saw" already the fall from $18.80 โ€” hindsight bias.

36.2 Solution: compute_strategy_score_with_mode

Function compute_strategy_score was refactored into compute_strategy_score_with_mode(candles, mode, alpha, gpu_momentum):

ModeSource SignalThreshold
ORACLEOracle score+/-8.0 (reduced from +/-15), confidence > 0.10
GPUGPU momentum+/-0.003 (reduced from +/-0.005)
FUSIONoracle_norm * (1-alpha) + gpu_signal * alphaAdaptive, max 6.0

36.3 Solution: Causal Rolling Lookback (Chart)

36.3 Solution: Causal Rolling Lookback (Chart)

Replaced adaptive_thresholds (retrospective) with rolling lookback on last 40 bars:

36.4 Impact


37. AUTO-RESUME SCAN โ€” CONTINUED FROM INTERRUPTION POINT

37.1 The problem

When restarting after an interrupted scan (eg: 158/200), auto-resume started from 0/200. The pre-filter pipeline (fetch assets -> snapshots -> quant_prefilter) is non-deterministic (depends on live data), so the same list of symbols on restart could not be guaranteed.

37.2 The solution

Saving the pre-filter queue (full list of symbols to be processed) in StateSnapshot:

  1. PreFilterCandidate receives Serialize, Deserialize derives
  2. scan_prefilter_queue added to TitanState and StateSnapshot
  3. The queue is saved after quant_prefilter and is deleted when completed
  4. auto_resume_scan completely rewritten:

37.3 Behavior on Restart

Stepwhat is happening
1The partial results (158) appear instantly in the UI
2Log: "AUTO-RESUME: Continuing scan from 158/200 (42 remaining)"
3Progress bar starts from 158/200
4Process only the remaining 42 symbols
5The complete list of 200 ranked symbols appears in the UI

37.4 Safety


38. MULTI-SYMBOL ENTRY FIX & DEL ALL

38.1 Multi-Symbol Entry Fix

Problem: With 21 symbols in HFT Engine and Multi-Symbol activated, no open position in 4 hours.

Identified causes:

  1. max_open_positions = 1 โ€” only 1 simultaneous position allowed
  2. OFI filter calculated on active_symbol but applied to ALL symbols
  3. Nexus consensus filter โ€” same, only on active_symbol but applied globally
  4. Applied solutions:

Applied solutions:

38.2 DEL ALL Button

Quick button to delete all symbols from the HFT Engine list:


39. ENTRY GATE SCORING PIPELINE โ€” DEBOTTLENECKING

39.1 The Problem (March 14, 2026)

The entry gate did not allow any entry. The analysis of 42 logs (sampled at 1%, representing ~4200 real evaluations) showed score=50.0 and signal=NEUTRAL on all symbols, in a window of 8 minutes (06:23-06:31). The score was stuck at the neutral baseline of 50.0 due to a chain of 5 multiplicative bottlenecks.

39.2 The 5 Bottlenecks (Before the Fix)

The scoring pipeline had the following steps, each reducing the signal:

Oracle Layers (Kalman, Wavelet, Hurst, VPIN, Entropy)
    โ†’ raw_signal (weighted sum, range [-1, +1])
    โ†’ final_signal = raw_signal * regime_boost * meta_confidence    โ† BOTTLENECK 1+2
    โ†’ oracle_score = final_signal * 100
    โ†’ confidence = meta_confidence * (1 - noise_ratio)              โ† BOTTLENECK 3
    โ†’ entry score = 50 + oracle_val * 0.5 * confidence              โ† BOTTLENECK 4
    โ†’ signal = LONG/SHORT/NEUTRAL (threshold check)                 โ† BOTTLENECK 5
    โ†’ entry_side = None daca NEUTRAL (blocat)

39.3 Applied Fixes

Fix 1 โ€” meta_confidence: product โ†’ geometric mean

BeforeAfter
predictability * clarity * stability(predictability * clarity * stability).cbrt()
Example: 0.4 0.5 0.3 = 0.06Example: (0.4 0.5 0.3)^(1/3) = 0.39

The geometric mean keeps the intent (all 3 must be reasonable) but does not collapse to near-zero.

Fix 2 โ€” noise_ratio: penalty halved with floor

BeforeAfter
meta_conf * (1 - noise_ratio).max(0)meta_conf * (1 - noise_ratio * 0.5).max(0.25)
noise_ratio=0.7 โ†’ factor 0.3noise_ratio=0.7 โ†’ factor 0.65

Floor of 0.25 prevents the total death of the signal in high noise conditions (pre-market).

Fix 3 โ€” score formula: removed redundant multiplier 0.5

ModeBeforeAfter
MathOracle50 + oracle_val * 0.5 * oracle_conf50 + oracle_val * oracle_conf
GpuNexus50 + gpu_scaled * 0.550 + gpu_scaled
Fusion50 + fusion_val * 0.5 * fusion_conf50 + fusion_val * fusion_conf

Fix 4 โ€” reduced signal thresholds

ModeBeforeAfter
MathOracleoracle_val > 8.0, conf > 0.10oracle_val > 8.0, conf > 0.10
GpuNexusgpu_momentum > 0.005gpu_momentum > 0.003
Fusionheadless fusion_threshfusion_thresh with .min(6.0)

Fix 5 โ€” correct log message

SituationBeforeAfter
NEUTRAL signalscore 50.0 < threshold 40.0 (misleading)signal NEUTRAL (score=50.0, no directional conviction)
Score below thresholdSame as abovescore X < threshold Y (signal=LONG)

39.4 Corrected Flow

Oracle Layers โ†’ raw_signal [-1, +1]
    โ†’ meta_confidence = (pred * clarity * stab).cbrt()        โ† geometric mean
    โ†’ final_signal = raw_signal * regime_boost * meta_conf
    โ†’ oracle_score = final_signal * 100
    โ†’ confidence = meta_conf * (1 - noise * 0.5).max(0.25)   โ† halved + floor
    โ†’ entry score = 50 + oracle_val * confidence              โ† no 0.5x
    โ†’ signal = LONG if oracle_val > 8.0 && conf > 0.10       โ† lower thresholds
    โ†’ entry_side = Some("buy") daca LONG && score >= threshold

39.5 Numerical Impact

With typical values โ€‹โ€‹(predictability=0.4, clarity=0.5, stability=0.3, noise_ratio=0.7, raw_signal=0.5):

MetraBeforeAfter
meta_confidence0.060.39
confidence (final)0.0180.25
oracle_score2.415.6
entry score50.0253.9
signalNEUTRAL (locked)LONG (pass)

39.6 Modified Files

FileLocationCHANGE
titan_oracle.rsline 1171meta_confidence: .cbrt()
titan_oracle.rsline 1202confidences: * 0.5, .max(0.25)
titan_oracle.rsline 1431series path: .cbrt() (consistent with fuse_oracle)
main.rslines 2690-2716formula score without 0.5, reduced thresholds
main.rslines 4905-4916log message differentiated NEUTRAL vs score<threshold

40. ORACLE HISTORY FIXES (S05)

40.1 What was fixed

Five critical bugs in calculate_history() (used for chart overlay, backtest, SmartTrend) were fixed:

BugEffect beforeFix
Entropy double-normalizationclarity ~0.88-1.0 constant (wrong)clarity = 1 - normalized_entropy (correct [0,1])
noise_ratio hardcoded 0.3Identical confidence regardless of noiseUses real noise_ratio from wavelet decomposition
VPIN buy_pressure = VPIN scorebuy_pressure was toxicity, not BVC fractionBVC buy fraction: (close-low)/(high-low) per-bara
Changepoint threshold 0.5 vs 0.3More permissive history with stabilityBoth paths use 0.3 (shared constant)
Backtest exit exact matchPrefixed exits ("O EXIT") not detectedcontains("EXIT") instead of == "EXIT"

40.2 Impact

40.3 New series available

OracleHistory now contains 5 additional series:

SeriesSourceUtility
kalman_gain_seriesKalman K[0] per-barHow much the filter adjusts to new data
price_surprise_seriesinnovation/predictedKalman unexpected price movements
run_length_seriesBOCPD MAP run lengthHow many bars since the last changepoint
dominant_cycle_seriesWavelet max-energy levelDominant cycle (2^n bars)
noise_ratio_seriesWavelet detail/total energyNoise/signal ratio

FINAL NOTE

Titan HFT is a complex system with multiple security layers. The main recommendations:

  1. Always start in DRY RUN until you are comfortable with the behavior
  2. Monitor the Activity Log for anomalies
  3. Do not manually modify the thresholds Circuit Breaker without understanding the implications
  4. Let the Genetic Optimizer run for at least a few hours before trading live
  5. Check LOOP HEARTBEATS periodically โ€” all loops must be ALIVE
  6. Session Reports from ~/titan_hft_rust/reports/ are the source of truth for performance
  7. SPREAD GUARD messages are normal โ€” it means that the filters work and protect capital
  8. After frontend changes, delete WebKit cache and do a clean build (see section 25.10)
  9. Settings persist automatically in titan_settings.json โ€” dry_run, strategy_mode, favorites, trade size
  10. Strategy generates the signal, filters validate it โ€” see section 6 and 11 for details
  11. Telegram Alerts โ€” configure BotFather and activate from tab-4 for alerts on mobile
  12. Correlation Matrix โ€” adjust Max Corr from tab-4 for optimal diversification in Multi-Symbol
  13. ATR Dynamic Stops โ€” leave the default multipliers (2.0x SL, 3.0x TP) until you understand the behavior on your assets
  14. State Persistence โ€” Upon crash/restart, everything is automatically restored from the snapshot (trail stops, analytics, scan results)
  15. AUTO ENTRY โ€” It must be activated explicitly from the sidebar for the bot to open new positions
  16. Signal Alignment โ€” Signals from the chart and autopilot are now aligned and FUSION-aware (Chap. 36)
  17. Auto-Resume Scan โ€” Upon restart, the scan continues from where it left off, not from 0 (Chap. 37)
  18. DEL ALL โ€” Deletes only IDLE symbols from HFT Engine; active positions are protected (Ch. 38)
  19. Entry Gate Scoring โ€” The scoring pipeline has been unlocked: meta_confidence with cbrt, noise floor, reduced thresholds (Ch. 39)
  20. Scalping Mode โ€” Enable scalping per strategy for more frequent signals on 1m-5m (Ch. 40)
  21. WARRIOR PRO โ€” Ross Cameron criteria filter strictly: RVOL>=5x, change>=10%, $1-$20, with catalyst check (Chap. 43)
  22. Position Sizing Safety โ€” Max 25% equity per trade, 1000 share cap, duplicate order prevention (Chap. 44)

40. SCALPING MODE โ€” TOGGLES PER STRATEGY

40.1 What It Is

Each of the 3 strategies (Oracle, GPU Nexus, Fusion) can be independently switched to scalping mode. Scalping mode generates more frequent signals, optimized for 1m and 5m timeframes with holding times from seconds to 30 minutes.

40.2 Toggles in the UI

In the NEXUS GPU panel in the interface:

ToggleSettingDefault
SCALP ORACLEscalping_oracleON
SCALP GPUscalping_gpuON
SCALP FUSIONscalping_fusionON

40.3 Differences Scalping ON vs OFF

ParameterScalping ONScalping OFF
Lookback15 bars30 bars
Cooldown3 bars8 bars
Score threshold0.40.55
Confidence gate0.080.15
Exit SL multiplier0.70x1.0x
Exit TP multiplier0.60x1.0x
Exit Trail multiplier0.50x1.0x

40.4 Impact on Chart

When scalping is active, the chart shows significantly more BUY/SELL/EXIT markers. When it is disabled, the signals are rarer and more conservative.


41. REGIME-ADAPTIVE TRADING SIGNALS

41.1 What It Is

Trading signals automatically adapt to the market regime detected by Oracle (Trending, MeanReverting, Chaotic, Unknown).

41.2 Thresholds per Regime

RegimeScore ThresholdConfidence MinBehavior
Trending0.35 (scalp) / 0.50 (swing)0.06 / 0.12More sensitive signals, follow the trend
MeanReverting0.50 / 0.600.10 / 0.18Moderate thresholds, stricter confirmation
Chaotic0.65 / 0.750.15 / 0.25Very selective, avoid noise
Unknown0.45 / 0.550.08 / 0.15Default balanced

41.3 Explicit Exit Signals

Special exit markers appear on the chart:

MarkerColorCondition
TRAILYellow #FFD700Trailing stop reached
EXITWhite #FFFFFFSL/TP or opposite signal
CHAOSOrange #FF6600Chaotic regime with loss

41.4 Multi-Timeframe Confirmation

Signals are validated against Oracle direction on higher timeframe. A BUY on 1m is stronger if Oracle on 5m is also bullish.


42. AUTOPILOT ALIGNMENT โ€” CHECK_ENTRY + ORACLE EXITS

42.2 Solution: check_entry()

The optimizations on the chart (adaptive regimes, scalping, VPIN gate) did not affect the live autopilot. The chart and the autopilot had different logics.

42.2 Solution: check_entry()

VPIN toxicity gate

42.3 Additional Exits

exitConditionDescription
Oracle FlipOracle score < -10 (long) sau > 10 (short), confidence > 0.20Oracle reversed itself strongly
Chaos ExitChaotic regime + negative PnL + confidence > 0.25Do not maintain position in chaos
Scalping ExitActive scalpingSL 0.70, TP 0.60, Trail * 0.50

43. WARRIOR PRO โ€” ROSS CAMERON SCANNER

43.1 What It Is

WARRIOR PRO is a scanning mode based on Ross Cameron (Warrior Trading) criteria, optimized for day trading on low-float stocks.

43.2 Pre-filter criteria (warrior_prefilter)

CriterionValueExplanation
Price$1 - $20Low-price stocks with high movement potential
Change%>= 10%Only stocks in significant movement
RVOL>= 5xRelatively extraordinary volume compared to the previous day
Volume> 1MMinimum liquidity

43.3 Catalyst Check

When WARRIOR PRO is active, each candidate is checked for recent news via the Alpaca News API:

conditionEffect on Score
With catalyst (news detected)+25% bonus to ai_score and smart_score
No catalyst-40% penalty

Additional bonuses:

43.4 Activation

Two activation modes (synchronized):

  1. Toggle WARRIOR PRO in AI Scanner panel (tab-6) โ€” red button
  2. Toggle Warrior in the sidebar Risk & Params

Both control the same warrior_mode in the backend.

43.5 Badge Catalyst

In the AI โ€‹โ€‹Scanner table, symbols with recently detected news have a newspaper icon next to their name.

43.6 Warrior Scanner Sidebar

In Market Discovery (sidebar), the WARRIOR scanner now has:


44. POSITION SIZING SAFETY โ€” HARDCAPS & DUPLICATE PREVENTION

44.1 The problem

The autopilot places repeated orders of 8000+ shares on the same symbol (95% of equity per trade), without checking pending orders or market hours.

44.2 Solutions

FixedDetails
Notional Maxequity * 0.25 (was equity * 0.95)
Share headMaximum 1000 shares per order
Pending order checkhas_pending_orders_for_symbol() โ€” query Alpaca /v2/orders?status=open
Market hours checkis_market_open() โ€” query Alpaca /v2/clock
Entry cooldown60 seconds (was 30)

44.3 Conduct


45. SCALPING POSITION MARKER

45.1 What It Is

Open positions in scalping mode have a distinct visual marker in the positions table.

Yellow "SCALP" badge โ€” next to the position symbol

45.3 Technical Implementation


46. โ€‹โ€‹AI SCANNER ENHANCEMENTS

46.1 Scan Cancellation

The CANCEL button in progress on the AI โ€‹โ€‹Scanner bar allows stopping a scan in progress. Backend: CancellationToken checked on each candidate.

46.2 Shared score_candidate()

The score_candidate() function centralizes the scoring logic (Oracle + GPU Nexus + Backtest Sweep + AI Score + Smart Score + Catalyst Check). Used by run_ai_scan, ai_scan_loop, and auto_resume_scan.

46.3 HFT Targets Cleanup

On auto-inject, symbols with smart_score < 10.0 are automatically removed from hft_targets. Max cap: 20 symbols.

46.4 Timezone Fixed

Market hours calculated correctly with DST: EDT (UTC-4) March-October, EST (UTC-5) November-February.

46.5 Rate Limiting

500ms delay between batches of snapshots (1000 symbols/batch) to respect Alpaca rate limits.


47. SMART PICKS 3-Pillar Scoring

47.1 Formula with 3 Pillars

The smart_score score determines the SMART PICKS ranking and the auto-inject in HFT targets. The previous version relied almost exclusively on backtest metrics. The new formula combines 3 pillars:

pylonWeightWhat measure
BACKTEST50%Historical performance: Win%, Sharpe, number of trades, Profit Factor, Expectancy
MOMENTUM35%Current Strength: CHG% (price change today), RVOL (relative volume), MarketRegime (Oracle)
QUALITY15%Intrinsic quality: liquidity (float), presence of catalyst, Oracle-price directional alignment

BACKTEST PILLAR (50%):

PILLAR MOMENTUM (35%):

QUALITY PILLAR (15%):

47.2 Quality Filters

Before being displayed in SMART PICKS, candidates must pass the filters:

FilterValueScope
bt_trades>= 5Sufficient statistical data
bt_sharpe> 0.0Positive Risk Adjusted Return
bt_win_rate> 20%Minimum viability
smart_score> 25Global quality (was > 20)
change_percent> -5%Excludes stocks in free fall
price>= $1.50Excludes extreme penny stocks

47.3 New Columns in the SMART PICKS Table

The SMART PICKS table now displays 3 new columns with color coding:

47.4 Catalyst Detection in All Modes

Previously, the catalyst check (has_catalyst) only applies when Warrior Pro mode was active. Now:


48. MARKET DISCOVERY โ€” Advanced Parameters and Auto-Scan

48.1 ScanParams โ€” Configurable Parameters

The market scanner now uses the ScanParams structure from scanner.rs, with all configurable fields in the UI:

ParameterDefaultDescription
price_min$1.00Minimum price per share
price_max$20.00Maximum price per share action
volume_min500,000Minimum daily volume
change_min5.0%Minimum percentage change
rvol_min2.0xMinimum relative volume (compared to average)
gap_min3.0%Minimum gap to previous close
require_catalystfalseMandatory catalytic filter (recent news)
max_candidates100Maximum number of candidates processed
scan_interval_minutes30Auto-scan interval (5-60 minutes)

48.2 Configuration from UI

In the Market Discovery section of sidebar:

All parameters are automatically saved in titan_settings.json through scan_params field from AppSettings.

48.3 Refactored Functions

48.4 Watchlist Management

48.5 Watchlist โ€” Chart interaction

When you click on a symbol from the watchlist, it is displayed on the chart (the main graph changes to the selected symbol).


49. MANUAL TRADE โ€” USD Manual Transaction

49.1 Manual Trade panel

The Manual Trade section in the sidebar (collapsible element <details>) allows direct manual trading:

ElementFunction
Symbol InputText field for the asset symbol (ex: AAPL, TSLA)
LONG / SHORTDirection selector: LONG (buy) or SHORT (short sell)
USD AmountThe amount in USD you want to trade
EXECUTEPlace the order
FROM WLInject the symbol selected from the Watchlist into the Symbol field

49.2 Backend โ€” submit_manual_order

Tauri command submit_manual_order processes the order:

  1. Receives: ManualOrder { symbol, side, usd_amount }
  2. Calculate qty: Fetch current price from cache (or fetch live from Alpaca), divide by usd_amount / price, round to whole
  3. Place order: Call send_order_internal() with type market
  4. Returns: Confirmation or error

49.3 Remarks


50. FORCE MANUAL OVERRIDE โ€” Total Control

50.1 What It Does

The FORCE MANUAL RES toggle in the sidebar activates total user control over ALL positions. When active:

50.2 Visual Indicator

When force_manual_tf is active, a pulsating red banner appears in the main UI area:

"MANUAL OVERRIDE ACTIVE" โ€” with animation pulse-border (semi-transparent red background with pulsating red border)

The banner is synchronized with the toggle state via refreshSidebarState().

50.3 Difference from Per-Asset Manual Mode

FeatureForce Manual OverridePer-Asset Manual (Chap. 51)
PurposeLock ALL the botLock the bot on ONE symbol
Positions affectedALLOnly the symbol set to "manual"
New entriesCompletely blockedAllowed on other symbols
When to useEmergency situations, temporary total controlIndividual management of specific positions

50.4 Interaction with Aggressive Fashion

force_manual_tf overrides Aggressive Mode โ€” even if Aggressive Mode is active, if Force Manual Override is ON, the bot does nothing. The force_manual_tf check comes BEFORE the aggressive parameters in autopilot_loop.


51. LIVE POSITIONS โ€” Auto/Manual mode per Asset

51.1 The MODE column in the Table of Positions

The live position table now contains a MODE column with a toggle button per symbol:

modellericonaColorEffect
CARRobotVerdantThe bot manages the normal position (SL, TP, trailing)
MANUALHandOrangeThe bot does NOT interact with the position in any way

51.2 Orders Bulls

51.3 Storage and Persistence

Mods are stored in position_trade_modes: HashMap<String, String> of AppSettings/AppState. It is automatically saved in titan_settings.json through state persistence.

51.4 Bot Behavior

In autopilot_loop, for each symbol processed:

  1. Check if the symbol has mode set in position_trade_modes
  2. If mode == "manual" โ†’ the position is completely skipped (skip)
  3. If mode == "auto" or has no mode set โ†’ the position is managed normally

51.5 Use Cases


52. DRAWING TOOLS V2 โ€” All Tools

52.1 General Presentation

52.2 The 11 Instruments

52.2 The 11 Instruments

#InstrumentDescription
1CrosshairDisables drawing mode, restores normal interaction with the chart (zoom, pan)
2TrendTrend line between 2 points (click-drag)
3RayInfinite radius โ€” from point 1 through point 2, continuing to the edge of the chart
4HLineHorizontal price line โ€” extends across the entire width of the chart at the selected price level
5VLineVertical timeline โ€” from top to bottom at the selected time
6FibFibonacci retracements โ€” automatic levels: 0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%
7TextText annotation โ€” click on the chart, enter text in the prompt, place it at the chosen coordinates
8MeasureDistance measurement โ€” displays the difference in price, percentage, and time between 2 points
9LongLong box position โ€” visual areas with entry, target, and stop
10ShortsShort box position โ€” visual areas with entry, target, and stop
11DeleteDelete ALL the drawings on the chart

52.3 Toolbar Execution

Under the chart there is an execution toolbar (exec-toolbar):

52.4 Persistence

Current drawings are serialized with serialize() and saved in localStorage with key drawings_{symbol}

  1. Current drawings are serialized with serialize() and saved in localStorage with key drawings_{symbol}
  2. The new symbol designs are restored with setDrawings() from localStorage

52.5 Solution Symbol

Drawing Engine V2 uses window.currentSymbol to identify the current symbol, instead of "BTC/USD" hardcoded (fixed from the previous version).

52.6 Interaction with the Chart


53. AGGRESSIVE MODE โ€” Full Audit

53.1 All Code Paths

Aggressive Mode modifies the behavior of the bot in 4 locations:

FileLocationNormalAggressive
trading_engine.rsL39-54SL: -2.5%, tight trailingSL: -8%, trailing wider
strategy.rsL173-198Standard entry thresholdsLower thresholds (more permissive inputs)
main.rs (autopilot)Stop-Loss1.0x0.52x (stop much further)
main.rs (autopilot)take profit1.0x1.68x (more ambitious target)
main.rs (autopilot)1.0x1.0x0.67x (tighter trailing)
main.rs (entry)stop_dist0.8x vol_factor53.2 Visual Indicator

53.2 Visual Indicator

When Aggressive Mode is active:

53.3 Override Sliders

Under the Aggressive Mode toggle there are 3 adjustment sliders:

53.4 Interaction with Force Manual

Force Manual Override overrides Aggressive Mode. If both are active, force_manual_tf completely blocks the autopilot โ€” aggressive parameters become irrelevant.

Check order in autopilot_loop:

  1. force_manual_tf โ†’ if true, continue (skip all)
  2. Per-asset manual mode โ†’ if manual, skip that symbol
  3. Aggressive parameters โ†’ apply modified multipliers

54. EXTENDED HOURS โ€” Full Audit

54.1 What It Does

When the Extended Hours toggle is active, orders sent to Alpaca include the extended_hours: true flag. This flag allows the execution of orders outside normal market hours:

54.2 Backend Implementation

In function send_order_internal() of main.rs:

  1. Check if enable_extended is ON in settings
  2. It is checked if the asset is NOT crypto (crypto trades 24/7, does not require a flag)
  3. If both conditions are met: "extended_hours": true is added to the JSON body of the order

54.3 Visual Badge

When Extended Hours is active, a purple "EXTENDED" badge appears in the application header, next to the market status information. The badge is synchronized with the toggle state via refreshSidebarState().

54.4 Observations


55. ELIMINATIONS FROM SESSION 7

55.1 Warrior 3rd Bot โ€” REMOVED

What it was: A third mode of strategy based on the Ross Cameron criteria (day trading of low-price stocks with momentum). It included a WARRIOR toggle in the sidebar, separate cash block, dedicated scoring strategy, scan_warrior(), and warrior_prefilter() functions.

What was removed:

What has been preserved: The function warrior_prefilter() has been renamed to momentum_prefilter() and is available as an advanced subfilter in the scanner. Ross Cameron's criteria (price $1-$20, RVOL >= 5x, change >= 10%, volume >= 1M) are kept in this function.

Why: Warrior functionality was redundant โ€” Ross Cameron criteria are now integrated into the configurable ScanParams, and momentum_prefilter() remains available as a strictly optional filter.

55.2 Kelly Criterion โ€” ELIMINATED

What it was: A KELLY toggle that enabled Kelly Criterion position sizing โ€” a mathematical formula for sizing positions based on the strategy's historical edge.

What was removed:

Why: Kelly Criterion position sizing was not fully integrated into the bot execution pipeline. Sizing position hardcaps (Chap. 44) offer more robust protection.

55.3 Sniper List โ€” REMOVED

What it was: A dedicated section in the sidebar (LISTA LUNETIST) with a table of monitored symbols, own budget controls, and performance statistics. It had dedicated CSS classes and separate management logic.

What was removed:

Why: The Sniper List functionality was partial and redundant with Watchlist + per-asset modes. The improved watchlist (Ch. 48) and per-asset modes (Ch. 51) cover all use cases.

55.4 Summary of Files Affected by Removals

FileWhat has changed
index.htmlDeleted: warrior checkbox, cash block, PRO toggle, footer, wallet wiring, sniper section, kelly checkbox
main.rsDeleted: warrior_mode, kelly_active from structs/settings/commands, warrior branching in scan/score
app_state.rsDeleted: warrior_mode, kelly_active from AppState and default
scanner.rsDeleted: scan_warrior(); renamed: warrior_prefilter โ†’ momentum_prefilter
sidebar_wiring.jsDeleted: chk-warrior wiring
main.jsDeleted: chk-warrior wiring
styles.cssDeleted: .lunetist-stats CSS block

Ch. 56 โ€” Central Panel: Watchlist (tab-9) and HFT Targets (tab-10)

56.1 Why they moved from the Sidebar

The left sidebar was too narrow (~250px) to display the tables with all the columns in the AI Scanner (SYMBOL, PRICE, CHG%, VOL, RVOL, GAP%, SCORE, BT W/R, BT PnL, DD, CAT). The columns were either truncated or did not fit at all.

Solution: Complete migration of Watchlist and HFT Engine from the sidebar to the central panel, where they have ~800-1200px width. Two new tabs have been created next to "REPLAY":

56.2 Tab-9: WATCHLIST

Displays all the assets in the list of favorites (watchlist) with full columns:

ColumnDescription
SYMBOLAsset ticker
PRICECurrent price (from Alpaca snapshot)
CHG%Daily change percentage, color-coded (green/red)
VOLDaily volume
RVOLRelative Volume (compared to the 20-day average)
GAPGap% compared to the previous close
SCORECalculated score (change% ร— 2 + RVOL ร— 15 + log(vol) ร— 3), color-coded
CATCatalyst badge โ€” see Chap. 59
TRADEButton "โ†’MT" โ€” inject into Manual Trade
HFTButton "โ†’HFT" โ€” inject into HFT Engine
AIAI backtest button per asset โ€” see Chap. 57

Buttons from header tab-9:

Backend:

56.3 Tab-10: HFT TARGETS

Displays assets from HFT Engine with all columns from AI Scanner:

ColumnDescription
SYMBOLAsset Ticker
PRICECurrent Price
CHG%Daily Change Percentage
VOLDaily Volume
RVOLRelative Volume
GAPGap%
SCOREComposite AI Score
BT W/RBacktest Win Rate %
BT PnLBacktest Profit & Loss
DDMax Drawdown โ€” see Ch. 58
CATCatalyst badge

Backend:

Auto-refresh: The table is automatically updated on every ai-scan-update event from the backend.

56.4 Inject All / Selective from Watchlist


Ch. 57 โ€” AI Backtest for Watchlist

57.1 Purpose

Allows the user to run the complete AI scoring pipeline (identical to AI Scanner) on Watchlist assets, without waiting for an automatic scan. The results appear in a secondary table with all columns from AI Scanner.

57.2 Cum se utilizeaza

  1. Navigheaza la tab-9 (WATCHLIST)
  2. Click "BACKTEST ALL" in header โ€” ruleaza scoring pe toate simbolurile
  1. Se afiseaza un progress bar: "SCORING 3/12..." during processing
  2. The results appear in table #wl-ai-results under the main table

57.3 AI Results table columns

Identical to AI Scanner: SYMBOL, PRICE, CHG%, VOL, RVOL, GAP%, SCORE, BT W/R, BT PnL, BT Trades, BT Best, BT Worst, DD, CAT.

57.4 Backend

Scoring uses exactly the same function score_candidate() from main.rs, which calls:


Chap. 58 โ€” Coloana DD (Max Drawdown)

58.1 Ce este Max Drawdown

Max Drawdown (DD) reprezinta cea mai mare scadere procentuala de la un varf local la un minim local pe durata unui backtest. Example: if the equity increases to $1000 and then decreases to $800, DD = -20%.

58.2 Why it is important

58.3 Where it is displayed

TableColumn
AI Scanner (tab-6)DD
Smart Picks (sidebar)DD
WL AI Results (tab-9)DD
HFT Targets (tab-10)DD

58.4 Color Coding

ValoareCuloareSemnificatie
< -20%Red (#f44)High risk
-20% ... -10%Yellow (#fa0)Moderate risk
โ‰ฅ -10%Grey (#999)Low risk

58.5 Camp Backend

bt_max_drawdown: f64 in AiScanCandidate โ€” calculated by the run_backtest_sync function based on the equity series.


In the CATALYST tab, every news headline is now clickable. When clicked, the source web page opens in the system's default browser via window.__TAURI__.shell.open(url).

Also, a "READ โ†—" button appears on each line for quick access to the source.

59.2 Catalyst Toast โ€” READ Button

When a catalyst toast notification appears, it includes a "READ" button that opens the news source.

59.3 News AI Tab (tab-1)

Headline-urile articolelor au acum un link "READ โ†—" clickabil langa data publicarii.

59.4 Catalyst Badges in Tables

In the tables in tab-9 (Watchlist) and tab-10 (HFT Targets), the CAT column displays:

BadgeSemnificatie
โ˜… (stea galbena)Catalyst recent (< 1h)
โ— (cerc portocaliu)Catalyst din ultimele 24h
โ€” (grey)No catalyst detected

Click on the badge: Opens the news source in the browser.

59.5 On-Demand News Check

59.6 Global Frontend Catalyst Cache

window._catalystCache โ€” JavaScript object populated from:

The cache allows instant display of badges without additional requests.

59.7 Backend Enhancements


Cap. 60 โ€” Manual Trade Panel: List of Assets, Controls, Inject

60.1 List of Manual Assets

Function renderManualAssetList() dynamically populates the section of the Manual Trade panel with all assets set to "manual" mode. Each row displays:

ElementDescription
SymbolAsset ticker (bold)
Status"OPEN +$12.50" or "NO POS" if there is no open position
CLOSEButton that sends a closing order (market sell/cover)
AUTOButton that switches the asset back to autotrading mode
โœ•Remove button โ€” removes the asset from the manual list

60.2 Auto-Mark Manual

When executing an order from the Manual Trade panel (submit_manual_order or submit_order), the symbol is automatically set to "manual" by calling set_position_mode(symbol, "manual"). This prevents the muzzle from interfering with the manually open position.

60.3 Inject from Watchlist

60.4 Auto-Refresh

renderManualAssetList() is called automatically from:


Chap. 61 โ€” Drawing Tools: Rendering Fixes and projectTime

61.1 Problem: Rectangle Sticking to the Right Edge

When an end of a drawing (ex: risk box) had a timestamp outside the visible viewport of the chart, timeToCoordinate() returns null. The original code used hardcoded fallbacks (x = 9999 or x = -9999), which made the rectangles extend to the edges of the screen.

61.2 Solution: projectTime(time)

A new method projectTime(time) was added to the DrawingManager class. This performs linear extrapolation of the x coordinate for off-screen timestamps, using the visible range of the chart (at least 2 reference points):

  1. Finds at least the minimum and maximum visible timestamp with their corresponding x coordinates
  2. Calculates pixelsPerMs = (xMax - xMin) / (tMax - tMin)
  3. Extrapolates: x = xMin + (time - tMin) * pixelsPerMs

If the chart does not have enough data, returns null instead of an erroneous value.

61.3 Rendering Audit โ€” 5 Fixes

  1. Null guards risk box: Explicit check if (y1 == null || y2 == null || yStop == null) return; at the beginning of the rendering risk box block โ€” prevents dimensions NaN
  2. Skip-draw on null projection: if (x1 == null || x2 == null) return; in render() and continue; in hitTest() โ€” if projectTime() cannot calculate, the drawing is omitted instead of being rendered at x=0
  3. Label overlap prevention: The TARGET and STOP labels are drawn only when the box is at least 16px high โ€” prevents overlap text
  4. Canvas state isolation: ctx.save() / ctx.restore() around each drawing in the render() loop โ€” prevents "leaking" of lineWidth, textAlign, shadowBlur, lineDash from one drawing to another
  5. Division by zero guard: Checking d.p1.price !== 0 in the calculation pPct (TARGET percentage) โ€” prevents values โ€‹โ€‹Infinity

Chap. 62 โ€” Long/Short Settings Tab (tab-11)

62.1 General Presentation

The LONG/SHORT tab (tab-11) is a centralized panel for configuring all the parameters related to the risk box (Long/Short) drawings on the chart. It is organized in 6 sections (A-F).

62.2 A. Default Risk Parameters

Set the default risk parameters applied when creating a new risk box drawing on the chart.

ParameterDescription
R:R Ratio (radio)R:R mode โ€” slider from 0.5 to 5.0, default 2.0. The stop is automatically calculated based on the selected Risk:Reward ratio
Fixed % (radio)Fixed percentage mode โ€” input fields SL% and TP% (ex: SL = 2%, TP = 4%)

Behavior: When creating a new drawing, onMouseUp() reads _lsSettings.riskMode:

62.3 B. Position Sizing

ParameterDescription
Fixed $ Amount (radio)Fixed amount in USD (ex: $500), entered in the input
% of Equity (radio)Percentage of the account equity, slider 0.5%-25%
Calculated fieldsAuto-calculated: Shares/Qty, Risk $, Max Loss $, Max Profit $

Calculated fields are updated automatically when a risk box is selected on the chart, based on entry price, stop price and bet amount.

62.4 C. Label Display Options

5 checkboxes that control what information is displayed on the risk boxes on the chart:

CheckboxEffect on the chart
Show % changeShows the percentage from entry to target/stop (ex: "+2.5%", "-1.2%")
Show $ P/LShow profit/loss in USD (ex: "+$125.00", "-$60.00")
Show R:R ratioShow the Risk:Reward ratio (ex: "R:R 2.1")
Show entry priceShow "ENTRY: 150.25" on the reference line (dashed)
Show target/stop pricesShow prices under labels (ex: "@ 153.50", "@ 148.00")

62.5 D. Execution

ParameterDescription
Auto-submit TP/SL bracketsCheckbox โ€” when active, EXEC/AI orders automatically include bracket orders (Take Profit + Stop Loss) calculated from the drawing
Order TypeSelector: Market (immediate execution) or Limit (specified price)

62.6 E. Visual

ParameterDescription
Profit colorColor picker for the profit area (default: #00e676 green)
Stop colorColor picker for the stop/loss area (default: #ff1744 red)
Box OpacitySlider 0-100% โ€” controls the transparency of the box fill. Default: 6% (subtly transparent)

62.7 F. Drawing Management

ButtonAction
CLEAR ALL DRAWINGSDeletes all drawings on the current chart (any type)
CLEAR LONG/SHORT ONLYDeletes only the risk box type drawings (long/short), keeps lines, text, etc.
CLEAR ALL SYMBOLSClear all drawings for all symbols from localStorage
Drawing infoShow number of drawings: "3 drawings (2 L/S)"

Drawing count badge: A red badge with the total number of drawings appears on the ๐Ÿ—‘๏ธ button in the left toolbar. It is updated automatically with each save/load.

62.8 Exec Toolbar โ€” EXEC and AI Buttons

When a risk box is selected on the chart, a contextual toolbar appears with:

ButtonAction
BET $Input for transaction amount, synchronized bidirectionally with tab-11
EXECSend manual order via submit_order with qty calculated from bet/price
AISend AI-assisted order (same flow, flag ai_mode: true)

Bracket support: If the checkbox "Auto-submit TP/SL" is active, the order includes take_profit and stop_loss calculated from the drawing prices.

62.9 Settings Persistence

All Long/Short settings are saved in localStorage under the titan_ls_settings key as JSON. When starting the application, _lsLoad() restores the settings and _lsApplyToUI() applies them to the controls in tab-11.

The global object window._lsSettings contains:

{
  riskMode: "rr" | "fixed",
  defaultRR: 2.0,
  fixedSL: 0.02,
  fixedTP: 0.04,
  sizingMode: "fixed" | "equity",
  betAmount: 500,
  equityPct: 0.05,
  showPct: true,
  showDollar: true,
  showRR: true,
  showEntry: true,
  showTargetStop: true,
  autoBracket: false,
  orderType: "market",
  colorProfit: "#00e676",
  colorStop: "#ff1744",
  opacity: 0.06
}

63. AI SCANNER PARALLEL SCORING (RAYON)

AI Scanner has been optimized for maximum speed using parallel processing.

64. DEEP AUDIT REASONING โ€” MODAL WINDOW

Every score generated by AI Scanner can now be audited in detail.

65. MANUAL TRADE USD VS SHARES TOGGLE

Total control over how to place stakes in the manual trading panel.


66. SIGNAL STRATEGY โ€” TRADING BASED ON ARROWS

Signal Strategy is a way of trading that is based exclusively on the BUY/SELL/TRAIL arrows on the chart, ignoring all other parameters of the strategy.

66.1 Principle

66.2 Activation

Click on the SIGNAL STRATEGY button in the mode bar (next to Oracle / GPU / Fusion).

66.3 Signal Source Selector

After activating the Signal Strategy, a sub-selector appears: FUSION | ORACLES | GPU. Select from which strategy the arrows are visible on the chart:

66.4 Dedicated Assets List

Signal Strategy has its own list of assets (separate from HFT Targets):

66.5 Assets Table with Enriched Information

Each asset displays: PRICE, CHG%, RVOL, VOL, ORACLE score, NEXUS %, FUSION score, SIGNAL (BUY/SELL/NEUTRAL), BEST TF, and action buttons.


67. SIGNAL STRATEGY โ€” PARAMETERS CONFIGURATION TAB (SIGNAL CFG)

67.1 Structure

The Signal CFG tab contains 3 safety sections with parameters independent of the main strategy:

A. ENTRY SAFETY:

B. SAFETY POSITION:

C. EXIT SAFETY:

67.2 Bypass per Parameter

Each parameter (except Max Open Positions) has a checkbox BYP (Bypass). When active, that parameter is completely ignored by Signal Strategy. It allows granular control โ€” for example, you can bypass the cooldown but keep the stop loss active.

67.3 Smart Default

The SMART DEFAULT button sets all parameters to optimized values for active trading:

67.4 Visual Dimming

Parameters with active bypass are visually dimmed (opacity 40%) to clearly indicate that they are inactive.


68. SIGNAL STRATEGY โ€” ARROW BACKTEST

68.1 Principle

The Signal Strategy backtest simulates trading exclusively based on the BUY/SELL/TRAIL arrows (of the selected strategy: Oracle, GPU, or Fusion) on all 9 Alpaca timeframes.

68.2 Parameters

68.3 Asset selection for Backtest

In the "#" column in the table, each asset has a SEL (yellow) button. Click on SEL:

After the backtest, the following is displayed:

After the backtest, the following is displayed:

68.5 Auto-Trade on TF Optim

When the Signal Strategy is active, the bot automatically uses the optimal timeframe (from the last backtest) to draw signals from the chart.


69. EXTENDED HOURS โ€” AUTOMATIC CONVERSION OF LIMIT ORDERS

69.1 The problem

Alpaca rejects "market" type orders; in extended hours with error 422: "extended hours order must be DAY or GTC limit orders".

69.2 Automatic Solution

When the conditions are met:

...the order is automatically converted:

69.3 Cooldown of Failed Orders

After any failed command, the symbol receives a 60 second cooldown. During this period, the bot no longer tries to trade that symbol. Prevents retry spam.

Cooldown clears automatically at:


70. NON-FRACTIONAL ASSETS โ€” QUANTITY MANAGEMENT

Some shares (eg: PLU) do not support fractional amounts. Alpaca rejects with 403: "asset is not fractionable".

70.2 Solution

70.2 Solution

When placing the order:

  1. Checking property fractionable from the Alpaca API
  2. If the asset is not fractionable, the amount is rounded down to a whole number (floor)
  3. If the rounded quantity < 1, the order is rejected early with clear message

70.3 Example


71. CLICK-TO-CHART FROM LIVE POSITIONS

71.1 Functionality

Click on any row in the Live Positions table, load that asset on the chart and automatically switch to the Complex Chart tab.

71.2 Conduct


72. CLICK-TO-CHART FROM SIGNAL STRATEGY ASSETS

72.1 Functionality

Click on any row in the Signal Strategy Assets table to load the asset on the chart in its best timeframe.

72.2 Conduct


73. CRASH-SAFE PERSISTENCE & STATE CHART

73.1 Settings Persistence (Disk)

All application settings are saved in titan_settings.json:

Persistent settings include: all toggles, sliders, scalping modes, Signal Strategy bypasses, signal source, signal assets list, scan params, position modes, etc.

73.2 State Snapshot (Disk)

The runtime state is saved separately in titan_state_snapshot.json:

73.3 Chart State Preservation

When switching between tabs and returning to the Complex Chart:

Implementation: resizeCharts() instead of chart.timeScale().fitContent() when returning to tab 0.

74. CATALYST CROSS-TAB INTEGRATION (Deep Audit)

The Catalyst system doesn't work in isolation in Tab 7 โ€” it's integrated into 5 tabs via global helpers.

74.1 _catalystBadgeHtml(sym, candidate) โ€” Global Badge

Global JS function that generates the CAT badge on any table:

74.2 _updateCatalystCacheFromResults(results) โ€” DRY Helper

Centralized update cache function, used in 3 places:

Complete removal of the 3 blocks of duplicate code.

74.3 Integration per Tab

TabFeature Catalyst
Tab 1 (News AI)Button ๐Ÿ”ฅ TEST BULLISH (gradient), article cards with severity badge (EXPLOSIVE/STRONG)
Tab 6 (AI Scanner)CAT badge in scan results tables + SMART PICKS, auto-update cache at ai-scan-update
Tab 9 (Watchlist)CAT badge per symbol + CHECK NEWS button on all symbols (with error feedback)
Tab 10 (HFT Targets)CAT badge per target + CHECK NEWS button (with error feedback)
CFG signalToggle REQUIRE CATALYST (scan filter)

74.4 Error Feedback on CHECK NEWS

On failure, the CHECK NEWS (Watchlist + HFT) buttons display:


75. ARCHITECTURE MODERNIZATION โ€” data.rs SPLIT (Phase 9)

Problem

The file commands/data.rs had ~3,800 lines with mixed concerns: market data, order execution, various operations, scoring/backtest. Difficult to navigate, difficult to revise during code review, increased risk of merge conflicts.

Solution โ€” 4 Domain Modules

ModuleResponsibilityLines
commands/market_data.rsCandles, snapshots, quotes, price queries~300
commands/order_exec.rsOrder execution, bracket orders, order management~250
commands/ops.rsHealth check, state queries, miscellaneous operations~200
commands/scoring.rsBacktest scoring, GPU scores, signal markers, AI scan scoring~2,415

data.rs has been reduced to a re-export shim (~50 lines) that makes pub use out of sub-modules. All existing Tauri commands work identically โ€” zero breaking changes.

TitanError is the application's central error enum, defined in src-tauri/src/error.rs:

commands/
โ”œโ”€โ”€ mod.rs              โ† Module declarations
โ”œโ”€โ”€ data.rs             โ† Re-export shim
โ”œโ”€โ”€ market_data.rs      โ† Market data queries
โ”œโ”€โ”€ order_exec.rs       โ† Order execution
โ”œโ”€โ”€ ops.rs              โ† Operations & state
โ”œโ”€โ”€ scoring.rs          โ† Scoring & backtest (cel mai mare modul)
โ”œโ”€โ”€ backtest.rs         โ† Backtest sweep
โ”œโ”€โ”€ account.rs          โ† Account management
โ”œโ”€โ”€ trading.rs          โ† Trading commands
โ”œโ”€โ”€ settings.rs         โ† Settings CRUD
โ”œโ”€โ”€ favorites.rs        โ† Watchlist favorites
โ”œโ”€โ”€ hft_targets.rs      โ† HFT targets
โ”œโ”€โ”€ journal_cmd.rs      โ† Trade journal
โ”œโ”€โ”€ signal.rs           โ† Signal strategy
โ”œโ”€โ”€ scanner_cmd.rs      โ† Scanner commands
โ”œโ”€โ”€ monitoring.rs       โ† Telemetry & heartbeat
โ”œโ”€โ”€ strategy_cmd.rs     โ† Strategy scoring
โ””โ”€โ”€ misc.rs             โ† Replay, heatmap, alerts

76. TITAN ERROR SYSTEM (Phase 8)

The TitanError structure

TitanError is the application's central error enum, defined in src-tauri/src/error.rs:

#[derive(Debug, thiserror::Error, Serialize)]
pub enum TitanError {
    Network(String),     // Erori retea (API calls, WebSocket)
    Broker(String),      // Erori broker (Alpaca rejects, 403/422)
    Validation(String),  // Input invalid (parametri gresiti)
    Internal(String),    // Erori interne (logica, state)
    Io(String),          // Erori I/O (fisiere, disk)
    Gpu(String),         // Erori GPU (WGPU, compute shaders)
    Timeout(String),     // Timeout-uri (API, WebSocket)
    RateLimit(String),   // Rate limiting (API throttle)
}

Automatic Conversions (From impls)

Macro titan_bail!

titan_bail!(Network, "API call failed: {}", url);
// Expands to: return Err(TitanError::Network(format!("API call failed: {}", url)))

Impact


77. DECIMAL MIGRATION โ€” Tier 1 (Phase 7C)

Fields Migrated to rust_decimal::Decimal

AppState / AppSettings:

TradeAction:

EntryContext:

StateSnapshot (6 fields):

Serde Adapters

For compatibility with existing JSON files (which store numbers as floats), custom adapters are used:

#[serde(serialize_with = "serialize_decimal_as_f64")]
#[serde(deserialize_with = "deserialize_decimal_from_f64")]
pub equity: Decimal,

What remains f64

  1. FRONTEND MODULARIZATION (Phase 7E)

78. FRONTEND MODULARIZATION (Phase 7E)

From Monolith to 30 Modules

index.html was reduced from 15,454 lines to 2,595 lines by:

  1. External CSS โ€” block <style> of 2,877 lines extracted in src/styles.css
  2. 30 JavaScript modules โ€” all IIFEs and inline scripts extracted into separate files
  3. switchTab fix โ€” chain of 6 overrides on window.switchTab replaced with a single definition in titan_tabs.js

Loading Order

The scripts are loaded in <head> (before the DOM) and at the end of <body> (after the DOM):

Head (utilities and core):

<script src="lightweight-charts.js"></script>
<script src="titan_core.js"></script>
<script src="titan_bus.js"></script>
<!-- ... 16 module infrastructure ... -->
<script src="titan_bootstrap.js"></script>

End of body (feature modules, after DOM):

<script src="titan_globals.js"></script>
<script src="titan_journal.js"></script>
<!-- ... 8 module feature ... -->
<script src="titan_ls_settings.js"></script>

Shared Utilities (titan_core.js)

All modules have access to utilities from titan_core.js:


79. XSS HARDENING & escapeHtml (Phase 10)

The escapeHtml function

function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/&/g,'&amp;')
        .replace(/</g,'&lt;').replace(/>/g,'&gt;')
        .replace(/"/g,'&quot;').replace(/'/g,'&#039;');
}

Systematic Audit

All innerHTML assignments that include dynamic values โ€‹โ€‹were audited in 15 JS files. String values โ€‹โ€‹(symbols, headlines, timestamps, labels, IDs) are now wrapped with escapeHtml():

// Inainte (vulnerabil la XSS):
row.innerHTML = `<td>${t.symbol}</td><td>${t.reason}</td>`;

// Dupa (hardened):
row.innerHTML = `<td>${escapeHtml(t.symbol)}</td><td>${escapeHtml(t.reason)}</td>`;

Intentional Exceptions

Calculated numeric values โ€‹โ€‹(formatted with .toFixed(), formatVolume(), etc.) are NOT escaped โ€” they are safe by construction because they produce only digits and characters ., %, $, -.

Unified Helper formatVolume

fmtVol and fmtK (two duplicate functions) have been replaced with a single function:

function formatVolume(val, decimals = 1) {
    const n = Number(val);
    if (!Number.isFinite(n)) return "--";
    const abs = Math.abs(n);
    if (abs >= 1e9) return (n / 1e9).toFixed(decimals) + "B";
    if (abs >= 1e6) return (n / 1e6).toFixed(decimals) + "M";
    if (abs >= 1e3) return (n / 1e3).toFixed(decimals) + "K";
    return n.toFixed(0);
}

80. CENTRALIZED ERROR HANDLING (Phase 11)

TitanError.report (Frontend)

Defined in titan_core.js, replaces console.error in catch blocks:

const TitanError = {
    _log: [],
    report(context, error) {
        const entry = { ts: Date.now(), context, error: String(error) };
        this._log.push(entry);
        if (this._log.length > 200) this._log.shift();
        console.error(`[TITAN:${context}]`, error);
    },
    getLog() { return this._log; }
};

TitanDebug.log

Logging with timestamp, partial replace for console.log:

const TitanDebug = {
    log(tag, ...args) {
        console.log(`[${new Date().toISOString()}][${tag}]`, ...args);
    }
};

TitanTimers

Centralized registry for setInterval / clearInterval:

const TitanTimers = {
    _timers: {},
    set(name, fn, ms) {
        if (this._timers[name]) clearInterval(this._timers[name]);
        this._timers[name] = setInterval(fn, ms);
    },
    clear(name) {
        if (this._timers[name]) { clearInterval(this._timers[name]); delete this._timers[name]; }
    },
    clearAll() { Object.keys(this._timers).forEach(k => this.clear(k)); }
};

Global Error Handlers

window.onerror = (msg, src, line, col, err) => {
    TitanError.report('window:onerror', `${msg} at ${src}:${line}:${col}`);
};
window.addEventListener('unhandledrejection', (e) => {
    TitanError.report('unhandledrejection', e.reason);
});

Console.warn Preserved Intentionally

~20 non-critical console.warn are preserved (localStorage fallback, CRUD operations, capability detection) โ€” they are not errors but operational information.


81. DOM CACHE SYSTEM โ€” $el Helper with WeakRef (Phase 3 + RF-D Part 1)

Implementation (titan_core.js)

const _domWeakCache = typeof WeakRef !== 'undefined' ? Object.create(null) : null;

function $el(id) {
    if (_domWeakCache) {
        const ref = _domWeakCache[id];
        if (ref) {
            const el = ref.deref();
            if (el && el.isConnected) return el;   // cache hit
            // stale โ€” re-resolve
        }
        const el = document.getElementById(id);
        if (el) _domWeakCache[id] = new WeakRef(el);
        return el;
    }
    return document.getElementById(id);             // fallback fara WeakRef
}

How It Works

Debug API

window.TitanDomCacheDebug.snapshot() returns live counters:

CounterWhat it measures
lookupsTotal calls $el()
cacheHitsReturned from WeakRef without DOM query
staleInvalidationsRe-resolve after deref() null or !isConnected
domQueriesEffective searches document.getElementById()
domQueryMissesSearches that returned null
fallbackDirectCallsDirect calls (WeakRef unavailable)
weakRefEnabledtrue if WeakRef is active

window.TitanDomCacheDebug.reset() โ€” reset all counters to 0.

Migrated Files (RF-D Part 1)

All document.getElementById calls in these files have been replaced with $el():

Plus hot-paths converted to original Phase 3:

Anti-Regression Guard

guard_no_direct_getelementbyid.sh โ€” script that fails if document.getElementById( reappears in the migrated files. Automatically run by build.sh at step 2 (DOM regression guard). As new files are migrated, they are added to the list in the script.

Extension Scope

There are ~400+ document.getElementById calls left in the rest of the modules (titan_hft_panel, titan_bootstrap, titan_sidebar, etc.), planned for incremental conversion in the next sessions (RF-D Part 2+).


82. PRODUCTION HARDENING (Phase 7H)

Cargo Profile Release

[profile.release]
lto = true           # Link-Time Optimization (binar mai mic, mai rapid)
codegen-units = 1    # Optimizare maxima (un singur codegen unit)
panic = "abort"      # Fara stack unwinding in productie
strip = true         # Strip debug symbols
opt-level = 3        # Optimizare maxima pentru viteza

Result: binary ~14.7MB (from ~17MB without LTO/strip).

Feature Flags

[features]
default = ["gpu", "telegram", "web-dashboard", "options"]
custom-protocol = ["tauri/custom-protocol"]
gpu = []
telegram = []
web-dashboard = []
options = []

Optional modules gate-watched with #[cfg(feature = "...")]:

CI Compliance

Build Script โ€” 13-Step Pipeline with Validation-First

build.sh runs 13 sequential steps. All checks (steps 1-6) are executed BEFORE build/deploy โ€” any failure stops the pipeline without affecting the current installation.

Stepwhat is he doingControl lime env
1node --check on 33 first-party JS files (excludes lightweight-charts.js, node_modules, dist, target)โ€”
2DOM regression guard (guard_no_direct_getelementbyid.sh) โ€” check that migrated files do not reintroduce document.getElementByIdโ€”
3Static UI smoke โ€” serves local src/, launches Chrome headless + CDP, tests Manual Trade, quick buy/sell, KILL ALL confirm, cyberConfirm. Requires requests + websockets Python modules.TITAN_SKIP_STATIC_UI_SMOKE=1 (skip)
4cargo test --workspace (259 tests, fail-fast)โ€”
5cargo clippy --workspace -- -D warnings (blocks at any warning)โ€”
6Benchmarks (optional): focused bench_check_entry or full cargo benchTITAN_RUN_BENCH=1 (focused), TITAN_RUN_FULL_BENCH=1 (full)
7rsync -a --delete src/ โ†’ dist/โ€”
8cargo build --release --features custom-protocolโ€”
9Clear Webview cache (~/.local/share/com.titan.hft.v7reloaded, ~/.cache/titan-hft-v7-reloaded)โ€”
10Stop the instance runningโ€”
11Deploy binary to ~/.local/bin/titan-hft-v7-reloaded + desktop entries + icons (32, 128, 512)โ€”
12Launch with logging in ~/titan_hft_rust/logs/titan_YYYYMMDD_HHMMSS.logโ€”
13Summary: duration, binary size, timestampโ€”

Wrapper with benchmark: build_bench.sh โ€” executable that runs TITAN_RUN_BENCH=1 ./build.sh (shortcut for full validation with focused benchmark).


83. SIGNAL SCALPING KIT (Session 17) โ€” Realtime Alerts + Exact Journal

This chapter documents the updates for manual scalping in SIGNAL_STRATEGY, delivered in session 17.

83.1 What's new in UI

83.2 Realtime alerts (audio + visual)

83.3 Persistence of alert preferences

Preferences are stored locally in browser storage:

Upon restart, the application automatically restores the last configuration.

83.4 Journal exactly on source/timeframe (backend)

TradeRecord explicitly includes:

Benefits:

Set MODE = SIGNAL, then choose SRC (FUSION, ORACLE, GPU).

  1. Activate SIGNALS on the chart and check the live markers.
  2. Activate SIGNALS on the chart and check the live markers.
  3. In SIGNAL HEALTH, leave ALERTS ON and set VOL comfortably.
  4. After the session, analyze the KPI Journal on source and timeframe.

83.6 Operational note

For the next session, the priority backlog remains:


84. ALL CONFIGURABLE TRADING PARAMETERS (Session 18)

In session 18, absolutely all parameters that the bot uses in the trading process were exposed. Previously, these values โ€‹โ€‹were hardcoded in the Rust code. Now each is:

84.1 AUTOPILOT CORE (10 parameters)

Controls the fundamental behavior of the autopilot:

ParameterDefaultfieldDescription
min_hold_secs1800-3600Minimum holding time before forced exit
nexus_consensus_threshold7030-100Nexus consensus threshold for stop/take adjustment
autopilot_loop_ms1500500-10000ofi_stale_ms
ofi_stale_ms100001000-60000The time after which the OFI is considered expired
min_bars_for_entry205-200No. minimum number of candles required for entry
ofi_entry_threshold5.00-50OFI threshold for entry confirmation
max_qty_cap10001-100000Maximum quantity per order
min_qty_threshold0.001Minimum quantity acceptedMinimum quantity accepted
default_equity_fallback100001000-1000000Equity default when the data is missing
max_bypass_risk_pct25Maximum risk in bypass modeMaximum risk in bypass mode

84.2 EXIT SCALING (17 parameters)

Controls how stop-loss, take-profit and trailing stop are calculated:

ParameterDefaultDescription
vol_factor_min/max0.6 / 2.5Volatility factor domain
fallback_sl/tp/trail_pct2.5 / 2.5 / 1.5SL/TP/trail fallback percentages
scalping_stop/take/trail_mult0.70 / 0.60 / 0.50Scalping multipliers
partial_first_target_frac0.5TP fraction for the first partial output
partial_min_qty0.001Minimum quantity for partial output
atr_period14ATR period
0.5 / 8.00.5 / 8.0ATR stop clamping range
atr_take_clamp_min/max1.0 / 15.0ATR take clamping range
atr_trail_clamp_min/max0.3 / 5.0ATR trail clamping area

84.3 ORACLE EXIT (6 parameters)

Thresholds for Oracle-based outputs:

ParameterDefaultDescription
Minimum confidence for exit on opposite signal0.40Minimum confidence for exit on opposite signal
oracle_exit_min_score30.0The minimum score for exit on the opposite signal
oracle_flip_score_threshold10.0Score Threshold for Oracle Flip Exit
oracle_flip_confidence0.20Minimum confidence for Flip Exit
chaos_exit_max_loss_pct-0.5Maximum loss in Chaotic mode
chaos_exit_min_confidence0.25Minimum confidence for Chaos Exit

84.4 CIRCUIT BREAKER (5 parameters)

Daily loss protection thresholds:

ParameterDefaultDescription
breaker_caution_pct-3.0%Warning threshold
breaker_halt_pct-5.0%Threshold for stopping new entries
breaker_panic_pct-8.0%Panic threshold (kill switch)
max_notional_equity_frac0.25The maximum fraction of equity per position
min_stop_distance_frac0.0001Minimum stop distance as a fraction of the price

84.5 STRATEGY SCORING (9 parameters)

Parameters of the strategy scoring engine:

ParameterDefaultDescription
strategy_base_score50Base Score (Neutral)
vpin_gate_scalping0.85VPIN threshold for scalping
vpin_gate_normal0.75VPIN threshold for normal trading
min_rvol_threshold0.5The relative minimum volume for entry
rvol_window20RVOL calculation window
rvol_relax_threshold3.0RVOL threshold for relaxation
rvol_relax_value5.0Threshold adjustment at high volume
chaos_confidence_kill0.10The confidence threshold below which the score is cancelled
chaos_regime_mult0.55Regime multiplier for Oracle contribution

84.6 ENGINE STOPS (6 parameters)

Stops and trails from the trading engine (manage_positions):

ParameterDefaultDescription
long_stop_normal-2.5%Normal stop loss for long
long_stop_aggressive-8.0%Aggressive stop loss for long
short_stop_pct-5.0%Stop loss for short
long_trail_min_profit1.5%Minimum profit for trailing long activation
short_trail_gap1.5%The trailing gap for short
short_trail_min_profit1.0%Minimum profit for trailing short

84.7 ORACLE FUSION (8 parameters)

Oracle fusion weights and thresholds (7 layers):

ParameterDefaultDescription
oracle_kalman_weight0.30Kalman weighting in fusion
oracle_entropy_weight0.25Wavelet Weight/Entropy
oracle_hurst_weight0.20Hurst weight
oracle_vpin_weight0.15Share of VPIN
oracle_wavelet_weight0.10Entropy direction weight
oracle_confidence_floor0.25The minimum confidence threshold
entropy_chaos_threshold0.85Entropy threshold for chaotic regime
vpin_toxicity_alert0.6VPIN threshold for toxicity alert

84.8 PERIOD INDICATOR (12 parameters)

Periods of all classic technical indicators:

ParameterDefaultDescription
ema_fast_period9Fast EMA
ema_mid_period20Average EMA
ema_slow_period50Slow EMA
ema_trend_period200EMA trend
rsi_period14RSI period
macd_fast12MACD fast line
macd_slow26MACD slow line
macd_signal9MACD signal
bb_period20Bollinger Bands period
bb_std_dev2.0Bollinger Bands standard deviation
adx_period14ADX period
1414Stochastic RSI period

84.9 How it works technically

  1. UI: Each parameter has a slider in the HFT Engine tab, organized in 8 color-coded sections
  2. Save: When you click SAVE, all values โ€‹โ€‹are sent as a batch to the backend (batch_update_settings)
  3. Backend: apply_setting_field parses, clamps and writes to AppState + titan_settings.json
  4. Bot: Autopilot, strategy, trading_engine, risk, oracle and indicators read from settings.* instead of hardcoded values
  5. Load: On the first visit to the tab after the restart, loadHftSettings hydrates the sliders from the backend snapshot

84.10 Recommendations for use


FINAL NOTE

TITAN HFT (Shark V7 Reloaded) is a complete automatic trading system with 87 chapters of documentation.

Sessions 15-16 (March 25-26, 2026) executed Phase 7 completely (Architecture, Modernization & Production Readiness):

Session 17 (March 27, 2026) added the SIGNAL toolkit for manual scalping:

Session 18 (March 27, 2026) exposed absolutely all trading parameters (~80+) in the HFT Engine tab:

Session 19 (March 27-28, 2026) โ€” Deep Audit + 12 Smart Features + Complete Styling:

Session 20 (March 28-29, 2026) โ€” Cyber-HUD + Ross Cameron Columns + FMP Enrichment:

Session 21 (March 29, 2026) โ€” Phase 9 Final Upgrades:

Backend: 59+ Rust files, 122 tests, 0 clippy warnings, 4 workspace crates (titan-types, titan-risk, titan-genetic, titan-indicators). Frontend: 30 JS modules (at the time of session 21; now 33 modules), DOM cache $el with WeakRef, centralized TitanError.report, TitanTimers registry. Live WebSocket dashboard.

Left for the next session: 7D (Strategy TA Filters), DOM Cache Expansion, Decimal Tier 2, Profile persistence on disk, Latency Metrics UI, Position FSM Status Column.


85. DEEP AUDIT + 12 SMART FEATURES + STYLING (Session 19)

In session 19, a deep audit of the entire HFT Engine tab was performed, 12 new functionalities ("Smart Features") were added, the styling was completely refactored, and the SAFE/SCALP presets were extended to all sliders (~90+).

85.1 Emergency Kill Dashboard

Sticky panel at the top of the HFT Engine tab with:

The panel is updated automatically every 3 seconds.

85.2 DRY RUN / LIVE Badge

Badge displayed next to the title "HFT ENGINE CONFIG":

The badge reads the real status from the backend and is synchronized through the dryRunChanged event on TitanBus.

85.3 SAFE DEFAULT / SCALP DEFAULT presets

Two buttons that automatically set ALL the sliders (~90+) in the tab to pre-calculated values:

SAFE DEFAULT โ€” conservative parameters:

SCALP DEFAULT โ€” aggressive parameters:

Each preset has a toggle lock (switch on/off):

85.4 Search Filter

Search field "Search parameters..." which filters all the sliders in the tab in real time:

85.5 Undo (Persistent on Disk)

The UNDO button restores all settings to the state before the last change:

Rust commands: save_undo_snapshot, load_undo_snapshot

85.6 Settings Diff View

The SHOW CHANGES button displays a table with all unsaved changes:

85.7 Per-Symbol Overrides

Collapsible section that allows setting custom parameters per symbol:

Overrides are persisted in titan_settings.json and respected by the autopilot during trading.

Rust commands: set_symbol_override, remove_symbol_override, get_symbol_overrides

85.8 Live Impact Preview (Effective Exit Values)

Panel showing the EFFECTIVE values of stop/take/trail AFTER applying the adaptive multipliers:

It is automatically updated when the sliders are changed (debounced).

Rust command: preview_effective_exits

85.9 Regime Heatmap

Three colored boxes showing the multipliers for each market regime:

Each box shows: S (stop much), T (take much), Tr (trail much). The active mode is highlighted. It is updated every 5 seconds.

85.10 Parameter Profiles (RF-C: Disk Persistence)

Named profile system for saving/loading complete configurations. Profiles are stored on disk in titan_profiles.json (not in localStorage) -- they survive rebuilds, crashes, and can be exported/imported.

Available actions:

Storage: titan_profiles.json in the data folder of the application, with atomic writing (temp+rename) and auto-backup .bak. Versioning scheme (schema_v: 1) for compatibility with future updates.

Automatic migration: If there are old profiles in localStorage (from previous versions), they are automatically imported to disk at the first run and the old key is deleted.

85.11 Risk Calculator Live

Panel with 4 risk metrics calculated in real time:

It is updated automatically when the sliders are changed.

85.12 Parameter Health

Diagnostic system with 15 conflict/risk rules:

85.13 Auto-Suggest

The ANALYZE TRADES button analyzes the last 50 trades in the log and generates suggestions:

85.14 Adaptive Exit Multipliers

Advanced section (collapsible) with 18 sliders + toggle + floor that control the adaptive multipliers of the outputs:

Toggle: DISABLE ADAPTIVE EXITS โ€” when ON, all multipliers are ignored and only the raw values from the main sliders are used.

Min Exit Floor % โ€” the minimum value to which stop/take/trail can be compressed after cascading.

Regime Multipliers (9 sliders) โ€” separate multipliers for Stop/Take/Trail in each regime (Chaotic, Range, Trend).

Signal Alignment Multipliers (5 sliders) โ€” multipliers for when the signals are aligned or opposite to the position.

Timeframe Multipliers (3 sliders) โ€” multipliers for short timeframes (1m/3m).

85.15 Multi-Asset Control

85.16 Chart Persistence on Disk

Chart settings (timeframe, indicators, configurations) are now saved to disk:

Rust commands: save_chart_settings, load_chart_settings

85.17 Completely Refactored Styling

85.18 HFT Engine dedicated manual

A separate user manual was created, exclusively dedicated HFT Engine tab:


86. CYBER-HUD + ROSS CAMERON COLUMNS + FMP ENRICHMENT (Session 20)

86.1 Cyber-HUD Styling

All 3 tables in the center panel (HFT Targets, Signal CFG, Watchlist) have received the Cyber-HUD theme:

86.2 Ross Cameron Columns Complete

The full set of columns is now available on all 3 tables:

ColumnSourceDescription
GAP%Alpaca snapshotsGap from open vs prev close
FLOATEstimated from volumeLOW (<3M vol), MED (3-10M), HIGH (>10M)
CAPFMP /stable/profileMarket cap in millions (ex: 22M, 1.2B)
INSFMP /stable/insider-tradingLast insider activity: BUY, SELL, or โ€”
SCOREAI scoring pipelineSmart score or composite AI score

86.3 FMP Enrichment Universal

Before this session, FMP data (market cap, insider signal) was populated only by scanning Market Discovery.

Now, FMP enrichment is integrated into all data pipelines:

FMP data is cache-forgotten โ€” it is not re-fetched at each refresh if it is already in the cache.

If the FMP API key is not set (in Settings โ†’ API Keys), the CAP and INS columns will show โ€” (fallback graceful).

86.4 Cross-Module Refresh

When injecting symbols from Market Discovery:

86.5 Modified Rust files


87. PHASE 9 FINAL UPGRADES โ€” POSITION FSM + LATENCY METRICS + WEBSOCKET DASHBOARD + SESSION ANALYTICS (Session 21)

87.1 Position State Machine (FSM)

87.1 Position State Machine (FSM)

The positions had an implicit lifecycle โ€” their state was deduced from the context (presence/absence in the HashMap). Information such as the time of opening, hold duration, partial fills and reason for entry were dispersed in separate HashMaps on TitanState.

condition

conditionMeaning
PendingEntryOrder sent, waiting for fill
OpenActive position (default)
PartialExitPartially executed
PendingCloseClosing order sent
ClosedCompletely closed position

New fields on Position struct:

FieldTypeDefaultDescription
statePositionStateOpenCurrent status of the FSM
opened_atOption<u64>NoneEpoch seconds on opening
closed_atOption<u64>NoneEpoch seconds at closing
partial_takenboolfalseIf the take was partially executed
entry_tagOption<String>NoneReason for entry (ex: "momentum_entry")

All fields have #[serde(default)] โ€” the previously saved state (without these fields) is deserialized correctly.

FSM transitions:

87.2 Micro-Latency Metrics

API latency (order round-trip, GPU dispatch, streamer tick processing) was only logged with tracing::info!. There is no aggregation or percentiles.

Structure LatencyMetrics:

Methods:

Structure LatencySnapshot:

pub struct LatencySnapshot {
    pub order: LatencyBucket,
    pub gpu: LatencyBucket,
    pub streamer: LatencyBucket,
}
pub struct LatencyBucket {
    pub p50: u64,
    pub p95: u64,
    pub p99: u64,
    pub min: u64,
    pub max: u64,
    pub count: usize,
}

Tauri command: get_latency_metrics โ€” returns LatencySnapshot as JSON for the frontend.

Registration points:

87.3 WebSockets Dashboard

The web dashboard (axum, port 7777) was using <meta http-equiv="refresh" content="5"> for updating โ€” not suitable for real-time monitoring.

Implementation (updated S02 โ€” Session 45):

WebSocket Message Types (JSON):

typeWhenFields
statusIn 2 secondsequity, cash, positions[], breaker, latency
tradeAt entry/exit/partialaction, symbol, side, pnl, duration_secs
alertAt watchdog recoverymessages

87.4 Session Analytics Improvements

The journal records the duration of the trades as duration_secs: 0. Partial exits were not journalized at all. There were no streak counters.

New fields on SessionAnalytics (crate titan-risk):

FieldTypeDescription
longest_win_streaku32Longest streak of consecutive wins
longest_lose_streaku32The longest streak of consecutive losses
current_streaki32Current Streak (+ = wins, - = losses)
avg_duration_secsf64Average duration of trades (rolling)
best_trade_pnlDecimalThe highest profit from a trade
worst_trade_pnlDecimalThe biggest loss in a trade

Method record_trade_with_duration(pnl, duration_secs):

Partial exit journaling:

Exposed in API:

87.5 Post-Implementation Clippy Fixes

3 clippy errors detected by build.sh (running cargo clippy -- -D warnings):

  1. derivable_impls in app_state.rs โ€” impl Default for PositionState manual replaced by #[derive(Default)] + #[default] on the Open version
  2. dead_code in app_state.rs โ€” Position::new_open() marked with #[allow(dead_code)] (public API, will be used in the future)
  3. bind_instead_of_map in state.rs โ€” .and_then(|x| Some(y)) replaced by .map(|x| y) on the genetic_champion calculation

87.6 Amended Files โ€” Full Summary

Backend Rust (12 files):

87.7 Validations


Head. 88 โ€” Session 23: FSM Status Column, Latency Panel, Rate Limiting, Watchdog Fix

Date: 29 March 2026 (Session 23)

This session added visibility in the UI for position status and latency, secured the web dashboard with CORS and rate limiting, and fixed a critical gap in the watchdog.

88.1 Position FSM Status Column (RF-A1)

The table of positions in the "CURRENT PORTFOLIO" section; now has a STATUS column between TYPE and MODE that shows the FSM (Finite State Machine) status of each position.

5 possible states with colored badges:

conditionBadgeColorWhen it appears
PendingEntryPENDINGYellow with pulse animationEntry order sent, waiting for fill
OpenOPENCyanThe position is active and open
PartialExitPARTIALMagentaA partial take profit was executed
PendingCloseCLOSINGRed with pulse animationClosing order sent
ClosedCLOSEDGrayPosition closed (rarely visible, transient)

How โ€‹โ€‹the status reaches the frontend:

Why it's useful: Before, you didn't have visibility if an order was being executed or if a partial exit had already been made. Now you can instantly see the real status.

88.2 Latency Metrics Panel (RF-A2)

In the rightbar of the chart (the section on the right, under "Time"), a new section "Latency (us)" has appeared that shows the real-time performance of the 3 critical channels.

4x4 grid with 3 channels x 3 percentiles:

ChannelWhat measureWhere is it registered?
OrderRound-trip time of Alpaca API orderscommands/order_exec.rs
GPUNexus GPU dispatch durationloops/nexus_loop.rs
StreamWebSocket streamer message processingstreamer.rs

Percentiles: p50 (median), p95 (95th percentile), p99 (99th percentile)

Automatic color coding:

Smart format: Values โ€‹โ€‹are displayed as us (microseconds), ms (milliseconds), or s (seconds) depending on the magnitude.

Polling: The data is automatically updated every 5 seconds via invoke('get_latency_metrics').

The backend was already implemented (session 21 โ€” LatencyMetrics with ring buffer of 100 entries per channel). This session only added the frontend.

88.3 Rate Limiting + CORS (Phase 1 Security)

Web dashboard and Telegram have received security protections.

Web Dashboard โ€” CORS (updated S02 โ€” Session 45):

Web Dashboard โ€” Rate Limiting (updated S02 โ€” Session 45):

Telegram โ€” Rate Limiting:

88.4 Watchdog Streamer Spawn Fix (Phase 2)

Problem: The streamer was registered in watchdog (heartbeat("streamer", 0)) but does NOT exist in spawn_loop_by_name. If the streamer task panicked or stopped, the watchdog detected it as dead but couldn't restart it.

Fix: Added branch "streamer" in spawn_loop_by_name:

Why it's important: The streamer is the most critical component โ€” without it, you have no real-time price data. If it fell and was not restarted, the whole bot became "blind".

88.5 N1 Cleanup โ€” println! Residuals

The last 2 println! of the production code (from commands/settings.rs) have been migrated to tracing::info!:

Zero println! remain in production code. All logs go through tracing (structured logging with components, level filtering).

88.6 Modified Files โ€” Full Summary

Backend Rust (5 files):

Frontend (4 files):

88.7 Validations


Chap. 89 โ€” Session 24: Ring Buffer + ArcSwap Lock-Free + Flash Crash Detector

Session 24 implemented 3 major components from BLOCK 2 of the audit plan, focused on hot-path performance and capital protection in extreme events.

89.1 S1: CandleRingBuffer โ€” Market Data In-Memory

Problem: The autopilot calls fetch_bars_internal (REST HTTP to Alpaca) at each iteration, for each candidate symbol. This means 50-500ms latency per call, multiplied by the number of symbols.

Solution: CandleRingBuffer โ€” circular buffer in memory per symbol, fed directly from WebSocket.

New file: src-tauri/src/candle_buffer.rs

Architecture:

pub struct CandleRingBuffer {
    candles: VecDeque<Candle>,   // max 200 candles finalizate
    current: Option<Candle>,     // candle in constructie (nu inca inchisa)
    tf_secs: i64,                // durata timeframe-ului in secunde
}

Data flow:

  1. Streamer receives trade tick from WebSocket (price, size, timestamp)
  2. Call ring_buffer.update_trade(price, size, ts):
  1. When candles.len() > 200 โ†’ evicts the oldest (front pop)

Autopilot integration โ€” get_candles() helper:

async fn get_candles(state: &Arc<TitanState>, symbol: &str, timeframe: &str, min_candles: usize)
    -> Result<Vec<Candle>, TitanError>

All 7 calls fetch_bars_internal from the autopilot were redirected through get_candles().

Utility timeframe_to_secs(): Converts strings ("1m", "1Min", "5m", "5Min", "15m", "1h", "1Hour", "1d", "1Day") to seconds.

Unit tests (7 new):

Performance impact: Hot path from 50-500ms (REST) โ€‹โ€‹to <1ms (memory read).

89.2 S3: ArcSwap Lock-Free on OfiState

Problem: ofi_state was protected by Arc<Mutex<OfiState>>. The streamer (write at each tick) and the autopilot (read at each iteration) were fighting on the same lock, creating contention on the most latency-sensitive path.

Solution: arc_swap::ArcSwap<OfiState> โ€” atomic swap lock-free.

Before:

pub ofi_state: Arc<Mutex<OfiState>>,
// Write: state.ofi_state.lock().unwrap().current_ofi = val;
// Read:  let ofi = state.ofi_state.lock().unwrap().clone();

After:

pub ofi_state: arc_swap::ArcSwap<OfiState>,
// Write: let prev = state.ofi_state.load();
//        let mut st = (*prev).clone();
//        st.current_ofi = val;
//        state.ofi_state.store(Arc::new(st));
// Read:  let ofi = state.ofi_state.load();  // Guard<Arc<OfiState>>, no lock

Updated write paths (streamer.rs):

  1. Book-path OFI โ€” when receiving L2 deltas from WebSocket, recalculates OFI and makes atomic store
  2. Quote-path OFI โ€” when it receives NBBO quotes, it updates best_bid/ask/spread and makes atomic store

Read paths updated (3 locations):

  1. autopilot.rs โ€” spread guard + OFI stale check
  2. commands/order_exec.rs โ€” smart limit pricing (midpoint calculation)
  3. commands/strategy_cmd.rs โ€” get_ofi_status command for frontend

Conservative approach: ONLY migrated ofi_state because it has a clear single-writer pattern (the streamer). last_prices, trail_* and others remain Mutex (multi-writer patterns).

Impact: Zero contention on read path; write is O(1) atomic pointer swap.

89.3 S7: Flash Crash Detector with Auto-Protection

Problem: The existing circuit breaker only measures your PnL (losses from positions). It does not detect abnormal market movements (flash crashes) that have not yet hit the stop.

Solution: FlashCrashDetector โ€” rolling window price monitoring per symbol.

pub struct FlashCrashDetector {
    windows: HashMap<String, VecDeque<(Instant, f64)>>,  // preturi recente per simbol
    blocked_until: HashMap<String, Instant>,               // cooldown per simbol
    window_duration: Duration,   // fereastra de monitorizare (default 30s)
    threshold_pct: f64,          // prag de declansare (default 3.0%)
    cooldown: Duration,          // blocare post-trigger (default 5min)
}

Detection logic:

  1. At each trade tick, the price is added to the symbol window
  2. Clearing prices older than window_duration
  3. min and max are calculated from the window
  4. If (max - min) / min * 100 > threshold_pct โ†’ FLASH CRASH DETECTED

5 automatic actions when triggered:

  1. tracing::warn!(component = "flash_crash", symbol, drop_pct, ...) โ€” structured log
  2. app.emit_all("flash-crash", { symbol, drop_pct, action }) โ€” event to the frontend
  3. Auto-close the position on the affected symbol โ€” spawn close_position(state, symbol, qty, side, app)
  4. send_telegram_alert(...) โ€” Telegram notification (if enabled)
  5. Block new entries on the symbol for cooldown_mins minutes

3 configurable parameters from the UI (AppState + AppSettings):

ParameterDefaultRangeWhat it does
flash_crash_window_secs305-120Monitoring window in seconds
flash_crash_threshold_pct3.00.5-20.0Trigger percentage threshold
flash_crash_cooldown_mins51-60How many minutes does the post-trigger symbol block

All 3 have #[serde(default)] for backward compatibility with previously saved settings.

Autopilot integration: At the beginning of the evaluation of each candidate symbol, the autopilot checks state.flash_crash.lock().is_blocked(candidate) and does continue if the symbol is blocked.

Unit tests (6 new):

89.4 Modified files โ€” Full Summary

New file (1):

Backend Rust (8 files changed):

89.5 Validations


Ch. 90 โ€” Session 25: Drawdown Velocity Detection + Keyboard Command Palette

90.1 S8: Intraday Drawdown Velocity Detection

Problem solved: The circuit breaker measures the magnitude of the loss (daily PnL < threshold). The Flash Crash Detector measures the movement of the market. But none reacts to the speed of the loss. The dangerous scenario: you have -0.8% daily PnL (under the halt threshold of -1%), but in the last 3 minutes you lost 0.6% โ€” cascading losses in progress. The circuit breaker does not trip yet, but the speed shows that something is fundamentally wrong.

Solution: Ring buffer of drawdown snapshots with velocity detection.

How it works:

  1. At each autopilot cycle (~1.5s), a snapshot (epoch_secs, drawdown_pct) is recorded in the ring buffer on SessionAnalytics
  2. The ring buffer retains a maximum of 120 entries (the last ~3 minutes at normal refresh)
  3. Calculate dd_velocity = drawdown change in %/min on the window configured
  4. If the speed exceeds the threshold (default -1.0 %/min), new entries are blocked โ€” independent of the circuit breaker
  5. Log message periodically in UI: "DD VELOCITY HALT โ€” Drawdown speed X.XX%/min exceeds threshold"

Configurable settings (HFT Engine tab):

ParameterDefaultRangeDescription
dd_velocity_threshold-1.0-10.0 ... -0.1Maximum drawdown speed in %/min before halt
dd_velocity_window_secs30030 ... 600Lookback window in seconds

Difference to Circuit Breaker:

AppearanceCircuit BreakerDD Velocity
MeasureMagnitude (daily PnL %)Rate of loss (%/min)
TriggerPnL below absolute thresholdRate of loss over the threshold
When it helpsLarge accumulated lossesRapid losses in the cascade
RecoveryManual resetAutomatic when the speed decreases

Concrete example: Equity $100,000. In 3 minutes you lose 5 consecutive trades, equity drops to $97,000. Drawdown = 3%. Speed โ€‹โ€‹= -1.0%/min. The default threshold (-1.0) is reached โ†’ blocked inputs BEFORE the circuit breaker activates at -5%.

Exposed in API: get_risk_status returns the field dd_velocity (f64, negative when drawdown deepens).

Tests: 7 unit tests โ€” no_data, stable_equity, cascading_loss, safe_threshold, ring_eviction, window_secs, positive_threshold.

90.2 S11: Keyboard Shortcut Command Palette

Problem solved: In active scalping, every second counts. Navigating with the mouse through the tabs, changing the timeframe or quickly placing orders consumes precious time.

Solution: Global keyboard shortcuts module with integrated command palette (Ctrl+K).

Direct shortcuts (works anytime):

ShortcutAction
Ctrl+KOpen Command Palette
Ctrl+EnterQuick Buy (market order on the current symbol)
Ctrl+Shift+EnterQuick Sell (market order on the symbol current)
Ctrl+Shift+XFlatten All โ€” liquidate all positions (emergency)
Ctrl+PToggle Autopilot on/off
Ctrl+[Smaller timeframe (ex: 5m โ†’ 3m โ†’ 1m)
Ctrl+]Larger timeframe (ex: 5m โ†’ 10m โ†’ 15m)

Command Palette (Ctrl+K):

Commands available in the palette:

CategoryOrderShortcut
TradeQuick Buy (market)Ctrl+Enter
TradeQuick Sell (market)Ctrl+Shift+Enter
TradeFlatten All PositionsCtrl+Shift+X
ControlToggle AutopilotCtrl+P
NavigateGo to Chart1
NavigateGo to News AI2
NavigateGo to Journal3
NavigateGo to HFT Engine4
NavigateGo to Performance5
NavigateGo to AI Scanner6
NavigateGo to Watchlist9
NavigateGo to HFT Targets0
ChartTimeframe HigherCtrl+]
ChartTimeframe LowerCtrl+[
ChartTimeframe โ†’ 1m/5m/15m/1h/1dโ€”

Compatibility: Ctrl+* shortcuts do not interfere with the chart hotkeys (L=line, R=ray, H=hline, etc.) that work only without Ctrl. Navigating through tables with numbers (1-9, 0) is available ONLY through the command palette, not directly as hotkeys (avoids conflict with 0 = chart reset).

Input guard: All shortcuts (except Ctrl+K) are disabled when the focus is on a <input>, <textarea> or contentEditable element. Ctrl+K always works โ€” opens the palette and moves the focus to the palette input.

90.3 Changed Files โ€” Full Summary

New file (1):

Backend Rust (6 modified files):

Frontend (2 modified files):

90.4 Validations


Ch. 91 โ€” Session 26: TA Entry Gates with Soft/Hard Mode (RF-B)

91.1 What are TA Entry Gates

TA Entry Gates are 6 technical pre-entry filters that are applied AFTER the Oracle decides Buy/Short, but BEFORE returning the final trading decision. Their purpose is to filter the suboptimal inputs that Oracle alone misses.

Each gate has 3 modes of operation:

ModeEffect
OffThe Gate is completely ignored (as if it does not exist)
SoftEntry is allowed, but the score is penalized with N points (default 15). If the score falls below the threshold, the entry is still not executed
HardThe entry is completely blocked โ€” check_entry() returns None, regardless of the Oracle score

91.2 The 6 Gates

GateWhat it checksWhen block/penalize
RSIRSI vs thresholds overbought/oversoldLong: RSI > rsi_overbought (default 70). Short: RSI < rsi_oversold (default 30)
EMA AlignmentOrder EMA9/20/50Long: need EMA9 > EMA20 > EMA50. Short: EMA9 < EMA20 < EMA50. If they are not aligned, the gate is activated
ADXTrend strengthADX < adx_trend_threshold (default 25) โ€” trend too weak
BB SqueezeWidth of Bollinger bandsIf (BB_upper - BB_lower) / BB_mid < 2% โ€” market consolidating, avoid entries
MACDMACD histogram directionLong: the histogram must > 0. Short: the histogram must be < 0. If it is not aligned with the direction of the trade, the gate is activated
Stoch RSIExtreme StochRSILong: StochRSI > 80 (already overbought). Short: StochRSI < 20 (already oversold). Avoid entries when the indicator is in the extreme opposite direction

91.3 Presets (Predefined Profiles)

PresetRSIEMAADXBBMACDStochRSIWhen to use it
StrictHardHardHardHardHardHardMaximum quality, few inputs. Good for volatile markets
BalancedSoftOffSoftOffOffOffCompromise: RSI and ADX filter but not block
Oracle OnlyOffOffOffOffOffOffDefault. The Oracle decides by itself, without additional filters

91.4 Soft Penalty (Adjustable Penalty)

When a gate in Soft mode is violated, the score of the trade decreases by ta_gate_soft_penalty points (default 15, configurable 1-50 from the UI).

Penalties are cumulative: if 3 Soft gates are violated simultaneously, the score decreases by 45 points (3 x 15). A low enough score can make the trade not pass the entry threshold, even if it is not explicitly blocked.

91.5 Fail-Open Design

If an indicator is None (not enough data โ€” for example, RSI is None on the first 14 candles), that gate is completely skipped. It does not block or penalize.

The reason: at the beginning of the trading session or after a restart, the candle buffer is small. If the gates would block in the absence of data, you would lose the first minutes of the market open โ€” the most volatile and profitable.

91.6 Place in the Pipeline

The complete pipeline check_entry():

Candle-uri โ†’ FVG Detection โ†’ Oracle Score โ†’ VPIN Gate โ†’ RVOL Gate
  โ†’ Regime Thresholds โ†’ Long/Short Decision
  โ†’ TA Gates (NOU) โ†’ Classical Bonus โ†’ Return TradeDecision

91.7 Configuration from UI

In the HFT Engine tab, the "TA ENTRY GATES" section (with orange background) contains:

The changes are applied live (when changing each select) and automatically saves to disk.

91.8 Validations


Chap. 92 โ€” Session 27: StreamingIndicators โ€” O(1) Incremental Calculation (S2+S4 Part 1)

92.1 What is StreamingIndicators

StreamingIndicators is an internal module in the titan-indicators crate that maintains the state of each technical indicator and can produce a complete snapshot of indicators by processing a single candle (O(1)), instead of recalculates all indicators from zero for 200 candles (O(n)) at each cycle.

This is an internal optimization. Does not change any visible behavior โ€” same indicators, same values, same trading decision. It's just that it's calculated more efficiently.

92.2 Why it is necessary

The autopilot calls calculate_all_with_periods() every cycle (500-1500ms), for each candidate symbol. This function recalculates from scratch:

From all these calculations, only the LAST value matters (the current snapshot). The first 199 candles are recalculated unnecessarily. In addition, in 95%+ of the cycles the candles are identical to the previous cycle (a 1-minute candle changes once a minute, but the autopilot checks 60-120 times).

92.3 How it works

StreamingIndicators maintains persistent states per pointer:

IndicatorInternal stateUpdate complexity
EMA (x4)Previous EMA value + precomputed alphaO(1)
RSIavg_gain, avg_loss (Wilder smoothing)O(1)
MACD3 internal EMAs (fast, slow, signal)O(1)
BBSliding window VecDeque (20 values)O(period) ~20 ops
ADX4 sliding window SMA (TR, +DM, -DM, DX)O(period) ~14 ops
VWAPCumulative amounts (volume, volume*price)O(1)
StochRSIRing buffer RSI + 2 SMA(3)O(period) ~14 ops

Important design decision: BB and ADX use sliding window (VecDeque) instead of online algorithms (Welford). The reason: the existing batch uses sample variance (N-1) and rolling SMA. Sliding window guarantees identical output at the bit level, without the risk of cumulative floating point errors.

92.4 API Public

MethodWhat it does
StreamingIndicators::new(periods)Creates the empty instance, ready for update()
StreamingIndicators::cold_start(candles, periods)Processes an initial batch of candles, initializes state
streaming.update(candle)Process a new candle, return Indicators snapshot
streaming.candle_count()Total number of candles processed

92.5 Numeric validation

The output StreamingIndicators has been validated against batch calculate_all_with_periods() with proptest on random sequences of 50-200 candles. All values โ€‹โ€‹are identical to epsilon 1e-10 (0.0000000001).

92.6 Oracle

The Oracle (7-layer predictive super-indicator) was NOT incrementalized in session 26. update() returns oracle_score = None. Oracle is called batch only for new candle (once per minute at TF 1m), not every cycle. Note: Online Oracle Weight Adaptation (S15) was implemented in Session 38 โ€” see Chap. 103. This adjusts the weights, not the incremental calculation.

92.7 What's next (Part 2)

In the next session, IndicatorCache is implemented โ€” a cache per symbol+timeframe that:

Estimated reduction: ~95-99% of the indicator calculation overhead.

92.8 Modified files

One file: src-tauri/crates/titan-indicators/src/indicators.rs

Zero changes in the main code (src-tauri/src/). Completely isolated implementation in crates.

92.9 Validations


Chap. 93 โ€” Session 28: IndicatorCache โ€” Hybrid Cache per Symbol+TF (S2+S4 Part 2)

93.1 What is

IndicatorCache is the module that integrates StreamingIndicators (Chap. 92) into the trading engine. Without it, StreamingIndicators exists isolated in crates with no real effect. With IndicatorCache, the autopilot no longer recalculates all indicators from scratch at each cycle.

93.2 Hybrid strategy

The cache uses a hybrid strategy with two components:

93.3 The three execution paths

PathWhen it is activatedwhat is he doingCost
Cache hitSame candle timestamp (~95% of cycles)Returns the instant stored snapshotZero
Cache missNew candle (different timestamp)streaming.update() O(1) + oracle::calculate() batchO(1) + O(n) oracles
Cold startFirst call per symbolStreamingIndicators::cold_start() + calculate_all_with_periods() batchA(n) full

At the cache hit, NO computation is done. The result is returned directly from memory.

93.4 Structure

IndicatorCache
  โ””โ”€ entries: HashMap<"SIMBOL|TF", CacheEntry>

CacheEntry
  โ”œโ”€ streaming: StreamingIndicators  (state incremental persistent)
  โ”œโ”€ last_candle_ts: i64             (timestamp ultimul candle procesat)
  โ”œโ”€ snapshot: Indicators            (rezultat complet: streaming + oracle)
  โ””โ”€ last_access: Instant            (pentru eviction)

93.5 API

Methodwhat is he doing
IndicatorCache::new()Create empty cache
cache.get_or_compute(symbol, tf, candles, periods, oracle_weights)Returns Indicators: cache hit, incremental update, or cold start
cache.evict_stale(max_age)Delete entries not accessed more than max_age

In autopilot.rs, the call:

In autopilot.rs, the call:

let indicators = calculate_all_with_periods(&candles, &periods, &oracle_w);

was replaced by:

let indicators = {
    let mut cache = state.indicator_cache.lock().unwrap_or_else(|e| e.into_inner());
    cache.get_or_compute(candidate_symbol, &cand_tf, &candles, &periods, &oracle_w)
};

The eviction is done periodically (~1% of cycles, check order) with a maximum duration of 1 hour.

93.7 Design decision: cold start uses batch

At the first call per symbol, calculate_all_with_periods() is run completely (batch). StreamingIndicators::cold_start() only initializes the internal state. The reason: it guarantees BIT-IDENTICAL output with the non-cached path. After cold start, all subsequent calls use incremental streaming.

93.8 What NOT to do

93.9 Performance impact

MetraBeforeAfter
Calculation indicator per cycleO(200) candles * 14 indicators + Oracle 7 layersZero (cache hit 95%+)
At the new candleO(200) full recalculatedO(1) streaming + O(n) Oracle (once)
On first callO(200) fullO(200) full (identical, cold start)

93.10 Files

93.11 Validations


94.1 What it is

94.1 What it is

Module TitanAudio adds procedural audio alerts, screen-edge glow and flash title on critical trading events. The goal: the user does not have to keep his eyes on the screen non-stop โ€” sounds and visual effects alert him instantly when something important happens.

94.2 Problem solved

Before S12:

After S12, all these events have sound distinctive + visual feedback (flash title and/or screen glow).

94.3 Procedural sounds (7 types)

All sounds are generated procedurally with the Web Audio API (no .wav/.mp3 files):

SoundWave typeFrequenciesDurationWhen played
fill-entrysine520โ†’780โ†’1040 Hz (up)200msAt each trade fill
fill-exit-profitsine+triangle880โ†’1320โ†’1760 Hz (cha-ching)300msAvailable programmatically
fill-exit-losssawtooth220โ†’180 Hz (buzz)350msProgrammatically available
breakersquare600+750 Hz, 3x pulse1sBreaker CAUTION/HALT/PANIC
flash-crashsawtooth+square440โ†’330โ†’220 Hz (descending)1sFlash crash detected
signalself1000+1200 Hz (ping)200msProgrammatically available
watchdogtriangle400โ†’500โ†’400 Hz (triple)550msWatchdog dead loops

94.4 Visual feedback

Flash Title: Alternate document.title at 500ms with descriptive message (ex: "FILL: BUY AAPL", "BREAKER PANIC"). Variable duration (2-6 seconds depending on severity). Useful when the Titan window is not in focus.

Screen Glow: Fullscreen overlay with animated inset box-shadow (3 pulses). Colors:

94.5 Toggle AUDIO ON/OFF

Button in the TITAN SAFETY panel header (next to the breaker badge). Persistent state in localStorage (key titan_audio_enabled). Default: ON.

Toggle synchronizes visually: cyan when ON, gray when OFF. A click on the button changes the status instantly.

94.6 Wire-up on Tauri events

Event TauriSoundFlash TitleScreen Glow
trade-fillfill-entry"FILL: SIDE SYMBOL" (2.5s)โ€”
breaker-triggered (non-NORMAL)breaker"BREAKER LEVEL" (5s)Red/Yellow
flash-crashflash-crash"FLASH CRASH: SYMBOL" (6s)Magenta
watchdog-alert (dead>0)watchdog"WATCHDOG: N DEAD" (4s)โ€”

Breaker with level=NORMAL (reset) does not emit sound โ€” it is a reset, not an alarm.

94.7 Technical Details

94.8 Files

94.9 Public API

Methodwhat is he doing
TitanAudio.play(eventType)Play the specified sound
TitanAudio.flashTitle(msg, ms)Toggle document.title
TitanAudio.showScreenGlow(color, ms)Overlay fullscreen glow
TitanAudio.toggle()ONโ†”OFF
TitanAudio.setEnabled(bool)Direct setting
TitanAudio.isEnabled()Query status
TitanAudio.setVolume(v)Volume (0.05-1.0)
TitanAudio.wireEvents()Login to Tauri events

94.10 Validations

Head. 95 โ€” Session 30: TitanToasts โ€” Unified Notification System (Phase 4)

95.1 What is it?

TitanToasts is a unified non-blocking notification system that completely replaces the browser's native alert() and confirm(). Instead of blocking the UI with native modal dialogs (which prevent any interaction until closed), notifications appear as slide-in toasts in the upper-right corner and disappear automatically.

95.2 Why was it necessary?

65 alert() calls completely blocked the application UI. In active scalping, a dialog blocker that appears after an order fill or an error can prevent the operator from reacting to another critical event. Also, 16 confirm() calls had the same blocker effect. Plus there were 4 different toast systems (each with inconsistent CSS and behavior).

95.3 showCyberToast(message, type, durationMs)

Displays a non-blocking notification in the upper-right corner of the screen.

Available types:

TypeColorDefault durationiconaWhen it is used
successGreen (#00FF88)3 secondsโœ”Order executed, config saved, successful action
errorRed (#FF3344)6 secondsโœ–Order error, API error, critical failure
warningAmber (#FFD700)5 secondsโš Empty list, invalid input, attention
infoCyan (#00BFFF)3 secondsโ„นInformation, results, status

Behavior:

95.4 cyberConfirm(message, opts)

Replaces the native confirm() with a stylized modal. Returns Promise<boolean>.

Features:

Usage example:

if (!(await cyberConfirm('Delete all drawings?'))) return;
// utilizatorul a confirmat, continua actiunea

95.5 What was replaced

65 alert() replaced in 11 JS files:

16 confirm() replaced in 11 JS files:

95.6 Consolidation of existing toasts

Old toastWhat happenedReason
hftToast() (30 uses)Redirected to showCyberToast (thin wrapper with color map)Same type of simple notification
showNewMoverToast()Simplified to a single showCyberToast callIt was a simple notification with custom CSS
_showSignalAlertToast()KEPT as suchDomain-specific: buy/sell/trail/chaos types, bottom-right positioning
showCatalystToast()KEPT as suchComplex multi-field layout: symbol, headline, score, action buttons

95.7 Files

95.8 Public API

Functionwhat is he doing
showCyberToast(msg, type, ms)Display non-blocking toast
cyberConfirm(msg, opts)Async modal, returns Promise
TitanToasts.show(msg, type, ms)showCyberToast equivalent (internal API)
TitanToasts.confirm(msg, opts)CyberConfirm equivalent (internal API)

95.9 Validations


96. PERSISTENCY PROFILES ON DISK (RF-C) โ€” Session 31

96.1 What was done

The trading profiles were moved from localStorage (ephemeral, lost on rebuild) on disk to titan_profiles.json. Loading the profile restores ALL parameters including nested objects (TA Gates, Scan Params, Symbol Overrides) โ€” the fix for an existing bug that filters objects on load.

96.2 New bulls orders (backend)

Commandwhat is he doing
save_profile(name)Complete AppSettings snapshot with metadata (schema_v, saved_at)
load_profile(name)Apply full profile to AppState via apply_settings()
delete_profile(name)Delete profile (graceful if it doesn't exist)
list_profiles()Returns the sorted list with metadata (name, saved_at, schema_v)
export_profile(name)Returns the complete JSON of the profile
import_profile(name, data)Import profile from JSON

96.3 Disk storage

96.4 Automatic migration from localStorage

On the first run after the update, if the titan_hft_profiles key exists in localStorage:

  1. Each old profile is imported to disk via import_profile
  2. The old key is deleted from localStorage
  3. The migration is done only once (one-shot)

96.5 New buttons in the UI

96.6 Bonus: N5 โ€” max_manual_order_usd Enforcement

The setting max_manual_order_usd (default $50,000) existed but was not checked server-side. Now submit_manual_order in trading.rs blocks orders that exceed the limit with a clear error: "Order $X exceeds max_manual_order_usd limit ($Y)".

96.7 Bonus: Fixed async DELETE handler

Profile delete handler had await cyberConfirm() in a non-async function โ€” real JS bug. Fixed with async () => { ... }.

96.8 Modified files

96.9 Validations


97. CONCURRENT PRE-FETCH + EXIT PROCESSING (S5+S6) โ€” Session 32

97.1 What was done

The autopilot evaluates positions and candidates sequentially โ€” with 5 open positions and 10 candidate symbols, the latency was O(n * per_simbol_latency). Now evaluations run concurrent via futures::future::join_all, and decisions (API calls, state mutations) are applied sequentially.

97.2 Architecture: Gather in Parallel, Apply Sequentially

The principle: reading is done in parallel, writing remains sequential. No lock is held in the parallel code for more than microseconds.

Tick Autopilot:
  1. [PARALEL] join_all(evaluate_position_exit per pozitie)
     โ†’ Vec<ExitEvaluation> (candles, ATR, signals, stops, force_exit)
  2. [SECVENTIAL] Aplica decizii: close_position, trail updates, analytics, journal
  3. [SECVENTIAL] Pre-filtreaza candidati (flash crash, holding, pending, cooldown, correlation)
  4a. [SECVENTIAL] SignalStrategy path (neschimbat)
  4b. [PARALEL] join_all(evaluate_candidate_entry per candidat)
     โ†’ Vec<EntryEvaluation> (candles, indicators, check_entry)
  5. [SECVENTIAL] Selecteaza best entry (scor maxim), aplica OFI/Nexus, send_order

97.3 New structures

ExitEvaluation โ€” encapsulates the exit decision per position without side effects:

EntryEvaluation โ€” encapsulates the entry decision per candidate:

97.4 Behavior Change: Best-Score Selection

Previously, the autopilot took the first candidate that passed the filters. Now, all the candidates are evaluated in parallel, and the one with the maximum score is selected (best-match instead of first-match). Result: the autopilot chooses optimally.

97.5 What has NOT changed

97.6 Performance impact

With ring buffer (S1) + cache indicator (S2+S4) already implemented, most get_candles are cache hits (<1us). Parallelization helps the most when:

97.7 Validations


98. PORTFOLIO VaR ENGINE + HHI CONCENTRATION GATE (S9) โ€” Session 33

98.1 What is it?

Two complementary risk gates at portfolio level that PREVENT entries when the total risk is too high. Unlike CircuitBreaker / FlashCrash / DD Velocity (which are reactive โ€” act AFTER the loss), VaR and HHI are preventive โ€” block entry BEFORE the risk occurs.

98.2 Why was it necessary?

The existing risk management protects against INDIVIDUAL losses:

But there is NOTHING that says:

VaR and HHI cover these two gaps.

98.3 VaR โ€” Parametric Value at Risk

Method: Parametric (variance-covariance) at 99% confidence:

VaR = z_score(0.99) * sqrt(w' * Sigma * w)

where:

CVaR (Expected Shortfall) โ€” average losses BEYOND VaR:

CVaR = VaR * pdf(z) / (z * (1 - confidence))

CVaR is always higher than VaR and captures tail risk.

How the gate works:

  1. Close prices are extracted from the CandleRingBuffer for each symbol in the portfolio
  2. Log returns and the covariance matrix are calculated
  3. VaR is calculated with the ACTUAL portfolio
  4. VaR is calculated with the PROPOSED portfolio (adding the new position)
  5. If the proposed VaR > max_portfolio_var_pct โ†’ entry BLOCKED

98.4 HHI โ€” Concentration Risk Gate

Formula:

HHI = sum(w_i^2)     unde w_i = |notional_i| / total_notional

Range:

How the gate works:

  1. The notionals of the current positions are extracted
  2. The estimated notional of the proposed position is added
  3. The proposed HHI is calculated
  4. If the proposed HHI > max_concentration_hhi โ†’ entry BLOCKED

98.5 Settings (HFT Engine tab)

In the PORTFOLIO RISK GATES card (purple, after TA ENTRY GATES):

SettingDefaultRangeDescription
VaR Gate ON/OFFOFFtoggleEnable/disable VaR gate
Max Portfolio VaR %2.0%0.1-10.0Maximum threshold VaR 99%
Lookback Periods205-100How many return periods for covariance
Concentration Gate ON/OFFOFFtoggleActivate/deactivate HHI gate
Max HHI0.400.10-1.00Maximum concentration threshold

Both gates are OFF by default โ€” zero change in behavior until the user activates them explicitly.

For HFT scalping with minute positions, 95% VaR is too permissive โ€” it allows too many entries in high volatility conditions. 99% offers a higher safety margin, especially in combination with Circuit Breaker which already acts on absolute losses.

check_entry() โ†’ decide Buy/Short + scor
   โ†“
TA Gates (Soft/Hard) โ†’ penalizeaza sau blocheaza
   โ†“
OFI Filter โ†’ verifica flow direction
   โ†“
Nexus Consensus โ†’ verifica acord multi-agent
   โ†“
HHI Gate โ†’ verifica concentrare portofoliu โ† NOU
   โ†“
VaR Gate โ†’ verifica risc statistic portofoliu โ† NOU
   โ†“
Position Sizing โ†’ calculeaza qty
   โ†“
send_order_internal() โ†’ executa

98.7 Why VaR at 99% and not 95%?

For HFT scalping with minute positions, 95% VaR is too permissive โ€” it allows too many entries in high volatility conditions. 99% offers a higher safety margin, especially in combination with Circuit Breaker which already acts on absolute losses.

98.8 Known limitations

98.9 Tests

16 new tests in titan-risk crate (total 60):

98.10 Validations


99. FEATURE STORE โ€” ENTRY CONTEXT SNAPSHOT (S13) โ€” Session 34

99.1 What is

Feature Store is a system for capturing the complete context of indicators and strategy at the exact moment of entering a trade. Each trade in the journal now contains a snapshot with 20 fields that describe the state of the market and the trading decision at the time of entry.

99.2 Problem solved

Before the Feature Store, TradeRecord in the log only contained execution data: symbol, direction, quantity, prices, PnL, duration, strategy, timeframe. The notes field was empty. The information "why the trade was entered" and "what was the state of the indicators" he was constantly losing on every trade.

Consequences:

99.3 What TradeFeatures captures (20 fields)

CategoryFieldDescription
Oracleoracle_scoreOracle composite score (-100 to +100)
Oracleoracle_confidenceOracle Trust Level (0.0 to 1.0)
Oracleoracle_regimeMarket regime (Trending, MeanReverting, Chaotic, Unknown)
IndicatorsrsiRelative Strength Index
IndicatorsadxAverage Directional Index (trend strength)
Indicatorsatr_pctATR as a percentage of price (volatility)
Indicatorsema99 period EMA
Indicatorsema5050-period EMA
FlowvpinVolume-sync Probability of Informed Trading
FlowhurstHurst Exponent (persistence/mean-reversion)
FlowrvolRelative Volume (current vs average volume)
MicrostructureofiOrder Flow Imbalance (bid/ask pressure)
Microstructurespread_bpsSpread in basis points
Microstructureimbalance_ratioBid/ask imbalance ratio
Strategystrategy_scorecheck_entry()
Strategysignal_sourceSignal Source (ORACLE, GPU, FUSION, SIGNAL_STRATEGY)
Strategyfvg_typeFVG Type (Bullish, Bearish, None)
Strategyentry_typeEntry type (ex: Trending_LONG, SCALP_MeanRev_SHORT)
TA Gatesta_gates_passedNumber of TA gates passed
TA Gatesta_gates_totalTotal number of evaluated TA gates

99.4 How it works

ENTRY (send_order reusit)           EXIT (close_position)
    โ”‚                                    โ”‚
    โ–ผ                                    โ–ผ
snapshot_entry_features()          journal.record_trade()
    โ”‚                                    โ”‚
    โ–ผ                                    โ–ผ
state.entry_features               entry_features.remove(sym)
    .insert(symbol, features)           โ”‚
                                        โ–ผ
                                   TradeRecord {
                                     ...,
                                     entry_features: Some(features)
                                   }
                                        โ”‚
                                        โ–ผ
                                   journal.json pe disk

At entry: After send_order_internal succeeded, snapshot_entry_features() reads:

At full exit: entry_features.remove(&symbol) -- extract and delete from map.

At partial exit: entry_features.get(&symbol).cloned() -- read without deleting (the position is still open).

99.5 Backward compatibility

Field entry_features on TradeRecord has #[serde(default)]. Old logs (without this field) are deserialized with entry_features: None. Zero impact on existing UI or functionality.

99.6 Future Use

Data in the Feature Store will be used by:

99.7 Changed files

99.8 Tests (8 new, 221 total)

99.9 Validations


100. MICROSTRUCTURE ALPHA SIGNALS โ€” STREAM VPIN, SPREAD REGIME, DUAL VPIN DIVERGENCE (S10-lite) โ€” Session 35

100.1 What is

Complete system of microstructure alpha signals that transforms existing streamer data (trade classification, spread, imbalance) from binary filters (yes/no) into soft score modifiers (bonus/penalty on the entry score). It adds three new components: Stream VPIN (real VPIN from trade flow), Spread Regime (narrowing detection), and an original signal -- Dual VPIN Divergence (stream vs candle VPIN comparison).

100.2 Why it matters

Prior to this implementation, microstructure data existed in the system but was only used in binary:

Now, the microstructure influences the score of each entry candidate. A candidate with narrowing spread, aligned imbalance and healthy VPIN receives up to +14 points bonus. A candidate with hidden toxicity receives a -18 point penalty. The difference between entering or not entering a trade.

100.3 Stream VPIN -- Real VPIN from trade flow

What it does: Calculates VPIN (Volume-Weighted Probability of Informed Trading) directly from trade-by-trade flow, using the existing Lee-Ready classification (classify_trade).

Difference compared to VPIN candle (oracle):

LayoutCandle VPIN (oracle)Stream VPIN (S10-lite)
ClassificationBVC (close position in range) -- proxyLee-Ready quote rule -- exact
GranularityPer candle (1m/5m)Per trade (~ms)
BinningTime-synced (n candles)Volume-synced (n shares)
UpdateAt candle boundaryAt each classified trade
Accuracy on short TFsModerateHigh

How it works:

  1. Each classified trade (buy/sell) adds volume to the current bucket
  2. When buy_vol + sell_vol >= bucket_vol_threshold (5000 default), the bucket closes
  3. VPIN raw = sum(|buy - sell|) / sum(buy + sell) over the last 20 buckets
  4. EMA smoothing on VPIN raw (alpha = 0.15) to filter noise

Interpretation:

100.4 Spread Regime -- Narrowing detection

What it does: Two EMAs on spread_bps (bid-ask spread in basis points) with different speeds. When the fast EMA falls below 80% of the slow EMA, the spread_narrowing flag is activated.

Parameters:

Why it matters:

Market makers tighten the spread when they anticipate imminent directional movement. Spread narrowing after a period of wide spread is a pre-directional signal. The autopilot uses this flag as a +5 bonus on the entry score.

100.5 Dual VPIN Divergence (original concept)

What it does: Compares Stream VPIN (from tap, precise) with Candle VPIN (from oracle, roughly). When they diverge significantly, it is informative:

SituationDivergenceInterpretationEffect
Stream VPIN high + Candle VPIN low> +0.15Hidden toxicity -- toxic flow detected in tape but not yet visible in candlesPenalty -8
Stream VPIN low + Candle VPIN high< -0.15False alarm -- VPIN candle is noise from range compressionBoth similar
Both similar[-0.15, +0.15]Concordant, without divergence0

Academic reference: Inspired by Easley, Lopez de Prado, O'Hara (2012) "Flow Toxicity and Liquidity in a High-Frequency World". Dual-source divergence is not implemented in retail HFT -- original concept.

100.6 Microstructure Score Modifier -- Full Table

Function apply_microstructure_modifier() is applied in evaluate_candidate_entry(), AFTER check_entry() calculates the base score, BEFORE the ranking of the candidates:

ConditionBonus/PenaltyCumulativeNote
Spread narrowing+5YesMarket makers anticipate direction
NBBO imbalance aligned (buy + imb > 0.3 or sell + imb < -0.3)+4YesOrder flow confirms direction
Dual VPIN: false alarm filtered (divergence < -0.15)+5YesCandle VPIN was noise
Dual VPIN: hidden toxicity (divergence > +0.15)-8YesDanger hidden in the tape
Extreme VPIN Stream (> 0.85)-10YesVery high toxicity

Maximum possible: +14 (narrowing + imbalance + false alarm) to -18 (hidden toxicity + extreme toxicity)

Important: All modifications are soft (adjusts the score, does not block). A candidate with a high penalty can still be selected if he has a sufficiently high base score. Consistent with the "best candidate by score" philosophy from concurrent entry evaluation (S5+S6).

100.7 Integration in the pipeline

Trade message --> classify_trade() --> StreamVpin.update()
                                            |
Quote/L2 message --> spread_bps --> SpreadRegime.update()
                                            |
                               OfiState ArcSwap (lock-free)
                              /                            \
                    Autopilot:                          Frontend:
                evaluate_candidate_entry()          ofi-update event
                        |                      (stream_vpin, spread_narrowing)
                check_entry() -> score
                        |
        apply_microstructure_modifier()
                        |
              score +/- modifier
                        |
                best candidate selected
                        |
            snapshot_entry_features()
            (vpin=stream_vpin, vpin_divergence, spread_narrowing)

100.8 TradeFeatures -- New fields

Two fields added to TradeFeatures (journal.rs), both with #[serde(default)] for backward compatibility:

FieldTypeDefaultDescription
vpin_divergencef640.0stream_vpin - candle_vpin at the time of entry
spread_narrowingboolfalseFlag spread regime at the time of entry

The existing vpin field now contains stream_vpin (more precisely) instead of VPIN candle.

100.9 Validations


101. CONFIGURABLE STRATEGY THRESHOLDS โ€” SCORE MODIFIERS, CLASSICAL BONUSES, ENTRY THRESHOLD MATRIX (N4) โ€” Session 36

101.1 What it is

The extraction system of ~50 hardcoded magic numbers from strategy.rs in configurable structures from the UI. Before, the critical parameters that controlled how easy/hard Titan enters a trade were fixed in the source code -- now they are editable in real time from the HFT Engine tab, without recompilation.

101.2 Why it matters

Before N4:

After N4:

101.3 The 3 groups of parameters

Group 1: Score Modifiers (21 parameters)

Fine controls on the score calculated by calculate_score():

ParameterDefaultWhat it does
Chaos Kill Penalty-50Penalty when confidence is below chaos threshold
Chaos Kill Fallback50Score returned when oracle is not available
Chaos Conf x MeanRev1.5Chaos threshold multiplier per MeanRev regime
Chaos Conf x Chaotic2.5Multiplier per Chaotic regime
Chaos Conf x Unknown1.5Multiplier per regime Unknown
Regime x MeanRev0.82Multiplier oracle contribution per MeanRev
Regime x Chaotic0.55Multiplier per Chaotic
Regime x Unknown0.73Multiplier on Unknown
VPIN Penalty High-20Penalty when VPIN > scalping gate
VPIN Penalty Medium-10Penalty when VPIN > normal gate
FVG Bull Bonus+15Bonus on Fair Value Gap bullish detected
FVG Bear Penalty-15Penalty on bearish FVG
RVOL Tier1 Thr.2.0Tier 1 RVOL Threshold
RVOL Tier1 Bonus+8Bonus if RVOL > tier 1
RVOL Tier2 Thr.4.0RVOL tier 2 threshold (institutional)
RVOL Tier2 Bonus+12Bonus if RVOL > tier 2
StochRSI OB80Overbought threshold for TA gate StochRSI
StochRSI OS20Oversold threshold for TA gate StochRSI
BB Squeeze Width0.02Bollinger squeeze threshold (width < this threshold)
Strong Label80Oracle score > this threshold = "STRONG" entry
Mild Label60Oracle score > this threshold = normal entry

Group 2: Classical Bonuses (6 parameters)

Controls on bonuses in compute_classical_confirmation() (active only when use_classical_filters is ON):

ParameterDefaultWhat it does
RSI Bonus10.0Bonus when RSI confirms direction
EMA Align Bonus15.0Bonus when EMA20 > EMA50 (long) or vice versa
ADX Bonus10.0Bonus when ADX > trend threshold
BB Squeeze Bonus5.0Bonus when Bollinger bands are tight
VWAP Bonus10.0Bonus when price is above/below VWAP
Cap50.0Upper limit of the amount of bonuses

Group 3: Entry Threshold Matrix (7 regimes x 3 values x 2 modes = ~42 cells)

The grid that determines the entry thresholds per market regime:

RegimModeLongShortConfidence
TrendingScalp22-220.18
Trending AggroScalp15-150.12
MeanRevScalp32-320.28
MeanRev AggroScalp25-250.22
ChaoticScalp50-500.38
UnknownScalp32-320.25
Unknown AggroScalp22-220.18
TrendingNormal35-350.25
Trending AggroNormal25-250.20
MeanRevNormal50-500.35
MeanRev AggroNormal40-400.30
ChaoticNormal70-700.55
UnknownNormal50-500.30
Unknown AggroNormal35-350.25

Meaning of the columns:

101.4 UI in HFT Engine tab

Three new cards appear between STRATEGY SCORING and ENGINE STOPS:

  1. SCORE MODIFIERS (orange header) -- 21 sliders in a 3-column grid
  2. CLASSICAL BONUSES (green header) -- 6 sliders, the card appears semi-transparent when Classical Filters is OFF
  3. ENTRY THRESHOLD MATRIX (header cyan) -- grid 7 rows x 3 columns with numeric inputs, Scalping/Normal dropdown, VALIDATE and RESET DEFAULTS buttons

101.5 VALIDATE button

Call the command validate_thresholds and check:

  1. All long_threshold > 0 (a negative threshold has no meaning)
  2. All short_threshold < 0
  3. All conf_threshold in range [0.05, 0.95]
  4. Scalping thresholds <= Normal thresholds (scalping is more permissive)
  5. Trending thresholds <= Chaotic thresholds (natural gradient)
  6. StochRSI overbought > oversold
  7. RVOL tier1 < tier2

The results appear as toasts (warnings, not blocking errors).

101.6 RESET DEFAULTS button

Restores the values โ€‹โ€‹from the table above for the currently selected mode (Scalping or Normal). Useful after experiments.

101.7 Technical implementation

Three new structs in app_state.rs:

Fields on AppState with #[serde(default)] for backward compatibility. Entry thresholds are HashMap<String, EntryThreshold> with keys like trending, trending_aggro, mean_rev, etc.

The function lookup_entry_threshold() โ€‹โ€‹in strategy.rs does lookup with fallback safe if a key is missing from the HashMap.

33+ new match arms in settings.rs + apply_entry_threshold_field() dynamic parser for entry thresholds.

101.8 Validations


102. CI HARDENING + CRITERION BENCHMARKS (S19) โ€” Session 37

102.1 What was added

The CI pipeline has been expanded with two new audit tools and a complete system of performance benchmarks.

Configuration in src-tauri/deny.toml

cargo-audit โ€” scan the dependency tree for known CVEs (RustSec Advisory DB):

Criterion Benchmarks โ€” 6 benchmarks on 3 critical paths:

102.2 Available Benchmarks

BenchmarkWhat measureCandlesBaseline resultTarget
oracle_calculate_200Oracle 7-layer + fusion200873 us<5ms
oracle_calculate_100Oracle 7-layer + fusion100208 doors-
oracle_calculate_50Oracle 7-layer + fusion5051 doors-
indicators_all_200EMA + RSI + MACD + BB + ADX + VWAP + StochRSI + Oracle200895 USD<2ms
indicators_all_100The same complete set100218 doors-
full_pipeline_200Indicators + Oracle end-to-end (as check_entry)200906 us<10ms

All under 1ms for 200 candles. The complete pipeline is ~11x below target.

102.3 How to use benchmarks

Benchmarks are on-demand (not automatic). It is run when you want to check the performance after a change:

cargo bench                            # toate 6 benchmarks
cargo bench -p titan-indicators        # doar oracle + indicators (5 benches)
cargo bench --bench bench_check_entry  # doar full pipeline (3 benches)

Criterion generates HTML reports in target/criterion/report/index.html. On successive runs, it automatically compares with the previous baseline and shows the regression/improvement.

102.4 Full CI Pipeline (Post-Session 37)

Files: .github/workflows/ci.yml (push/PR) + .github/workflows/release.yml (v* tags)

Steps in order:

  1. cargo fmt --check โ€” formatting
  2. cargo clippy -- -D warnings โ€” lint
  3. cargo build --release โ€” compilation
  4. cargo test โ€” 248 tests
  5. cargo deny check โ€” license + advisory audit
  6. cargo audit โ€” CVE vulnerability scan

102.5 deny.toml โ€” Advisory Ignores

19 ignored advisories, all from transitive dependencies that we did not control:

102.6 Validations


103. ONLINE ORACLE WEIGHT ADAPTATION (S15) โ€” Session 38

103.1 What it is

Before S15, the Oracle weights were static (Kalman 0.30, Wavelet 0.25, Hurst 0.20, VPIN 0.15, Entropy 0.10), identical regardless of the market regime or the real performance of each layer. A layer that predicts incorrectly for months keeps the same weight as one that predicts correctly. There is no feedback loop between the trade results and the Oracle configuration.

103.2 Problem solved

Before S15, the Oracle weights were static (Kalman 0.30, Wavelet 0.25, Hurst 0.20, VPIN 0.15, Entropy 0.10), identical regardless of the market regime or the real performance of each layer. A layer that predicts incorrectly for months keeps the same weight as one that predicts correctly. There is no feedback loop between the trade results and the Oracle configuration.

103.3 How it works

When entering the trade:

  1. Oracle calculates the complete snapshot (7 layers)
  2. The 5 directional signals [-1, +1] are extracted (kalman_signal, wavelet_signal, etc.)
  3. It is stored together with the regime and confidence at the time of entry

When exiting the trade:

  1. The signals from the entry are recovered
  2. The PnL direction is calculated (+1 profit, -1 loss)
  3. The per-layer EMA correlation is updated: corr = corr * (1 - alpha) + (signal * direction) * alpha
  4. Every 50 trades, the adapted weights are recalculated

On the next entry:

  1. We are looking for adapted weights for the CURRENT regime of the market
  2. Oracle uses adaptive weights instead of static ones

103.4 The 3 smart upgrades

Per-Regime Adaptation: 4 independent sets of weights, one per MarketRegime (Trending, MeanReverting, Chaotic, Unknown). Kalman can dominate in trend but Hurst in mean-reversion. Each regime optimizes its weights independently.

Confidence-Weighted Learning: alpha_efectiv = alpha_baza * confidence_la_entry. Trades with high confidence (Oracle was sure) contribute more to learning than those with low confidence. It filters the noise from uncertain decisions.

Continuous Decay: corr *= 0.997 applied to every trade on all regimes. Half-life of ~230 trades. Adaptation "forget" gradually the old information, protecting against overfitting on market conditions that are no longer relevant.

103.5 Safety mechanisms

MechanismEffect
Weight cap 0.5x - 2.0xA weight cannot increase/decrease more than 2x compared to the base
Sum normalization = 1.0The summed adjusted weights always make 1.0
Toggle default OFFenable_oracle_adaptation must be activated manually
Continuous decayPrevents overfitting on historical sequences
layer_signals_at_entry volatileOn restart, only entry snapshots in-flight are lost (not the correlations)

103.6 How to activate

In the HFT Engine tab, the Oracle Fusion section:

The adaptation starts accumulating data from the first trade after activation. After the first 50 trades, the weights are recalculated automatically.

103.7 Persistence

OracleAdaptation (per-regime correlations, adjusted weights, trade_count) is saved in titan_state_snapshot.json through StateSnapshot. Upon restart, the accumulated data is automatically restored (if the snapshot is less than 12 hours old).

layer_signals_at_entry (signals at entry) are NOT persisted โ€” they are volatile per-session data. If a trade is open at the restart, that trade will not contribute to the adaptation.

103.8 Interaction with manual weights

The weights in the Oracle Fusion slider (Kalman W, Entropy W, etc.) become the base weights when the adaptation is active. Adaptation changes them relative to these values โ€‹โ€‹(0.5x - 2.0x). If you change the Kalman W slider from 0.30 to 0.40, the adaptation will oscillate between 0.20 and 0.80 (not 0.15 - 0.60).

When the adaptation is OFF, the weights in the slider are used directly (identical behavior as before S15).

103.9 Changed files (8)

103.10 Tests (11 new, 259 total)

103.11 Validations


104. EXIT INFLIGHT GUARD โ€” Anti-Loop Protection at Exits (Sessions 39-40)

104.1 Problem

The autopilot decides to close a position based on the positions reported by the broker (fetch_positions via API Alpaca). After close_position sends a sell order, the autopilot loop restarts in ~500ms. The broker may need 1-5+ seconds to reflect the closed position in the API response, so the next fetch_positions still returns the position โ€” and the autopilot sends another SELL order.

Symptoms observed in production:

19:28:07 AUTOPILOT EXIT: SELL LAR โ€” PnL: $-21.20
19:28:07 ORDER ACCEPTED: SELL LAR x212.0000 LAR
19:27:52 AUTOPILOT EXIT: SELL LAR โ€” PnL: $-21.20
19:27:52 ORDER ACCEPTED: SELL LAR x212.0000 LAR
19:27:42 AUTOPILOT EXIT: SELL LAR โ€” PnL: $-21.20
... (12+ ordine identice in 42 secunde)
19:27:48 RECONCILIATION: 2 open positions synced from Alpaca

Each duplicate order is either executed (accidentally opening a short position) or generates 429 errors (rate limit).

What was missing (S39):

Race conditions discovered after S39 (resolved in S40):

104.2 Solution (V2 โ€” Session 40)

Two layers of protection:

  1. Guard inflight strict โ€” Field on TitanState:
pub exit_inflight: Mutex<HashMap<String, u64>>

Maps simbol -> timestamp_ms. If a symbol exists in the map, the autopilot does not send another exit โ€” no timeout. The guard remains active until the broker confirms that the position is flat (through reconciliation) or a permanent error removes the entry.

  1. Guard broker open-order โ€” Before close_position, the autopilot queries has_pending_orders_for_symbol() (REST GET /v2/orders?status=open&symbols=X). If the broker already has an open order for the symbol, the new exit is skipped.

104.3 Complete flow

evaluate_position_exit() (tick autopilot)
    |
    +-- exit_inflight.contains_key(symbol)?
    |       DA -> return None (exit deja in zbor)
    |
    v
should_close = true (decizia de exit)
    |
    +-- has_pending_orders_for_symbol(symbol)?
    |       DA -> skip (broker are deja ordin deschis)
    |
    v
close_position() apelat
    |
    +-- cancel_open_orders_for_symbol (curata ordine vechi)
    +-- seteaza exit_inflight[symbol] = now_ms
    +-- trimite ordinul la broker (send_order_internal)
    |
    v
Autopilot success path:
    +-- marcheaza pozitia PendingClose (nu o sterge)
    +-- seteaza recon_grace (30s)
    +-- journal, analytics, trail cleanup
    |
    v
Fill ajunge pe WebSocket (trade_updates):
    +-- reduce qty pe pozitia existenta
    +-- daca qty ~= 0: sterge pozitia, state = Closed
    +-- exit_inflight NU se sterge (lasat pentru recon)
    +-- daca pozitia nu exista + exit_inflight activ: NU creeaza sintetica
    |
    v
Position reconciliation (la 15s):
    +-- fetch_positions de la broker (sursa de adevar)
    +-- exit_inflight.retain: pastreaza doar simboluri inca prezente la broker
    +-- cand broker-ul nu mai raporteaza simbolul -> exit_inflight se curata

104.4 Where to set / where to delete

LocationActionFile
close_position()SET โ€” before sending the ordercommands/market_data.rs
Position reconciliationCLEAR โ€” when the symbol disappears from the broker's raw positionsloops/position_recon.rs
Autopilot permanent failureCLEAR โ€” for errors 422/invalid/not foundloops/autopilot.rs

Does not clear in:

104.5 Why strict guard without TTL

104.6 Modified files

S39 (basic structure โ€” 5 files):

S40 (hardening โ€” 4 files, 6 changes):

104.7 Validations

104.8 PendingClose Lifecycle

Prior to S40, the autopilot would delete the position from settings.positions immediately after close_position returned Ok(). This causes two problems:

  1. When the fill arrived on the WebSocket, trade_updates did not find the position and created a new synthetic Sell type (false short position)
  2. Reconciliation re-inserts the position as Open after the expiration of the grace if the broker still reports it

Solution: The autopilot marks the position PendingClose (with closed_at set) instead of deleting it. This allows:

104.9 ORDER ACCEPTED โ€” Log Correct

Previously, send_order_internal emitted the message ORDER FILLED: SELL LAR x212.0000 LAR on the HTTP 200 response. This was misleading โ€” HTTP 200 means that the broker accepted the command, not that it was executed (the actual fill comes on the WebSocket as a separate event of type fill or partial_fill).

After S40: The message is ORDER ACCEPTED: SELL LAR x212.0000 LAR. Actual fills appear as FILL: SELL LAR x212.0000 @ $X.XX [fill] (issued by trade_updates).


105. CONFIGURATION COHERENCE โ€” apply_runtime_config (Session 44)

The first session of the Audit Roadmap. Solves the problem of desynchronization between the saved settings (AppSettings / AppState) and the runtime fields in TitanState.

105.1 Problem solved

Before S44, there were 4 different ways through which the settings reached the runtime (update_settings, batch_update, load_profile, main.rs startup), each with its own synchronization logic. Result: some runtime fields (strategy_mode, dry_run, circuit breaker thresholds, flash crash params, nexus_fusion_alpha) could remain out of sync after certain operations.

Additionally, batch_update_settings calls save_settings_to_disk before error checking โ€” if an individual field fails, the partially corrupted config was already persisted to disk.

105.2 Solution: apply_runtime_config()

A single function in state.rs that synchronizes all runtime fields from AppSettings in TitanState:

105.3 Transactional batch_update_settings

batch_update_settings now uses a snapshot + rollback mechanism:

  1. Snapshot โ€” full clone of AppState before changes
  2. Apply โ€” apply each field individually; if either fails, restore the snapshot
  3. Persist โ€” save on disk and Redis side effects only on success path
  4. Runtime sync โ€” apply_runtime_config called only once at the end

105.4 New command: apply_full_settings

Tauri command apply_full_settings accepts a AppSettings directly as JSON typed. Used by:

Include validate_settings_coherence() โ€” cross-field validation:

105.5 FlashCrashDetector::reconfigure()

The new method on FlashCrashDetector (in candle_buffer.rs) that updates the parameters (window duration, threshold %, cooldown) without deleting the price history from the sliding windows. Before, the only option was clear() which lost all history.

105.6 Import hardened profiles

import_profile check now:

105.7 Regression tests (4)

TestWhat is he checking?
settings_round_trip_coherenceAppSettings ->> JSON --> AppSettings keeps all fields
strategy_mode_from_name_covers_all_variantsAll variants of StrategyMode are covered by from_name
flash_crash_reconfigure_preserves_windowsreconfigure() does not lose sliding window history
validate_coherence_catches_bad_breakersWrong breaker ordering is detected

105.8 Modified Files

FileChange
state.rsapply_runtime_config(), StrategyMode::from_name(), 4 tests
candle_buffer.rsFlashCrashDetector::reconfigure()
commands/settings.rsbatch transactional, apply_full_settings, validate_coherence, import hardened
commands/strategy_cmd.rsfrom_name() replaces duplicate match
main.rsfrom_name() at startup + register apply_full_settings
titan_perf_stats.jsImport/undo use apply_full_settings (no String coercion)
.cursor/rules/titan-cyber-hud.mdcDesign system rule (NEW)

105.9 Cyber-HUD Design System Rule

Bonus: created .cursor/rules/titan-cyber-hud.mdc โ€” encodes the existing design system from styles.css (37 CSS custom properties, component patterns, animations). Any future frontend changes automatically respect this visual contract. Includes: color tokens, typography, component patterns (.cyber-panel, .titan-btn-*, .titan-toast-*), strict rules (zero inline styles, max 6 glow effects on screen, mandatory fonts).


106. SMARTTREND AI v3 โ€” FSM + ENGINE + LIVE PANEL (S07b) โ€” Session 55

106.1 What is

SmartTrend AI v3 is a trend intelligence system with 3 pillars (Macro, Micro, Momentum) orchestrated by a finite state machine (FSM). In S07a we built the pillars and the BayesianTracker. In S07b I added the complete FSM, the SmartTrendEngine engine, the wiring in settings, the Tauri command, and the UI panel.

106.2 State Machine (FSM)

SmartTrend operates through 5 states that shape the cycle of a trade:

StatusDescriptionBadge color
FlatNo position, no active signalDim (gray)
StalkingSignal detected, waiting for confirmationGold
EntryConfirmed, marker issued, position being openedCyan (flicker)
InTradeOpen position, monitoring activeGreen
TrailSignal weakening, trailing stop activeMagenta (breathe)

Transitions:

106.3 SmartTrendEngine

SmartTrendEngine::evaluate() is the central point. Receives a SmartTrendInput and returns SmartTrendResult:

Input: macro_input, micro_input, momentum_input, current_price, changepoint_prob, dominant_cycle, tf_minutes

Output: score (0-100), state, prev_state, direction, markers (vec), pillar_scores, bars_in_state, confirmation_progress

Internal flow:

  1. Evaluate the 3 pillars via evaluate_pillars()
  2. Check changepoint reset (force Flat + Exit marker if it was InTrade/Trail)
  3. Run FSM transitions based on directional_strength
  4. Emit markers at each transition
  5. Update BayesianTracker at exits (success/failure)

106.4 Dynamic Confirmation Window

The confirmation window (how many bars the score must remain above the entry threshold in Stalking) adapts dynamically:

confirmation_needed = max(2, dominant_cycle / tf_minutes)

106.5 Changepoint-Aware Reset

When the changepoint probability exceeds 0.7 (configurable st_changepoint_reset_threshold):

106.6 Bonuses implemented

BonusDescriptionConfig
Trail ATR Auto-Tighten (B1)In Trail, stop tightens by 5% per barst_trail_tighten_pct (0.05)
Pillar Agreement Gate (B2)Entry requires 2/3 aligned pillars (without cross-divergence)cross_divergence from PillarDiagnostics
FSM Stats Tracking (B3)Transitions per type, bars per state, hit rates, resetsSmartTrendStats in diagnostics
Hysteresis Anti-Chatter (B4)Stalking->Flat requires drop below threshold - marginst_hysteresis_margin (5.0)

106.7 SmartTrend Live Panel (UI)

Cyber-HUD panel in sidebar (under MICROSTRUCTURE), visible only when st_enabled = true:

+--[ SMARTTREND LIVE ]-------------------+
|  STATE: [FLT] [STK] [ENT] [TRD] [TRL] |
|  DIR: LONG    SCORE: 67.2  STR: Mod    |
|  BARS: 4/8 [========>           ]      |
|  M:62  m:71  P:58   AGREE             |
+----------------------------------------+

106.8 Configuration SmartTrend

All SmartTrend settings are persisted in AppSettings and editable via batch update. New fields added in S07b:

FieldDefaultDescription
st_changepoint_reset_threshold0.7Changepoint threshold for force reset to Flat
st_trail_tighten_pct0.05Tighten trailing stop per bar in Trail
st_hysteresis_margin5.0Anti-chatter edge Stalking->Flat

Existing camps from S07a: st_macro_weight, st_micro_weight, st_momentum_weight, st_entry_threshold, st_stalking_threshold, st_entry_thresholds[4], st_stabilization_window, st_bayesian_decay, st_bayesian_halflife, st_dominant_cycle_filter, st_ofi_norm_range, st_mp_bps_range, st_cvd_scale, st_enabled, st_killed.

106.9 Modified files

FileChange
smarttrend.rsFSM, Engine, markers, stats, 17 tests, 3 config fields
app_state.rssmarttrend: SmartTrendConfig + default
state.rsAppSettings, settings_from_state, apply_settings, apply_runtime_config
commands/settings.rsapply_smarttrend_field() with 21 fields
commands/market_data.rsget_smarttrend_diagnostics command
main.rsregister command, SmartTrendEngine init
index.htmlSmartTrend Live panel HTML
styles.cssSmartTrend panel CSS cyber-HUD
titan_bootstrap.jsinitSmartTrendPanel() polling + rendering

107. SMARTTREND SCORING + KILL SWITCH (S08) โ€” Session 56

107.1 StrategyMode::SmartTrend

New variant added to enum StrategyMode in state.rs:

VariantDisplayParse
SmartTrendSMARTTREND"SMARTTREND", "SMART_TREND", "ST"

Toggle cycle: MathOracle -> GpuNexus -> Fusion -> SignalStrategy -> SmartTrend -> MathOracle

107.2 SmartTrend Pipeline Scoring

In get_signal_markers_internal(), when mode == SmartTrend:

  1. evaluate() is run on each history bar (warmup 50 bars)
  2. evaluate() is run on each history bar (warmup 50 bars)
  3. Macro/Micro/Momentum inputs are built from oracle history, GPU scores, and candle data
  4. FSM markers are converted to SignalMarker format:
SmartTrend MarkerChart ShapedyeText
Entry (Bullish)arrowUp#00E5FFST BUY
Entry (Bearish)arrowUp#00E5FFST SELL
exitarrowDown#FFD700ST EXIT
ferryabout#BF00FFST TRAIL
Stalkingabout#FFD700ST STALK
ChangePointResetabout#FF8800ST BREAK

SmartTrend mode skips the default exit signal generation (FSM handles exits).

107.3 Regime-Adaptive Entry Colors (B4)

Entry markers change their color intensity proportionally to the market regime:

dietdye
Trending#00E5FF (full)
MeanRevertingrgba(0,229,255,0.6)
Chaoticrgba(0,229,255,0.5)
Unknownrgba(0,229,255,0.4)

107.4 Kill Switch

Backend:

Tauri Commands (smarttrend_cmd.rs):

Commandparametersreturns
smarttrend_kill_switchenable: bool, confirm_token: Option<String>String
get_smarttrend_config--SmartTrendConfig
update_smarttrend_configfield: String, value: StringString
get_smarttrend_session_stats--SmartTrendStats
get_smarttrend_state--SmartTrendDiagnostics

107.5 UI Kill Switch + Mode Button

Kill Switch button in SmartTrend Live panel:

Strategy mode selector โ€” button "ST" added to nexus-mode-toggle:

107.6 Score Overlay (B1)

SmartTrend scores (0-100) are included in SignalMarkersResponse.st_scores:

107.7 Quick-Stats Banner (B2)

Persistent banner under SmartTrend Live panel:

+--[ Quick Stats ]------------------------+
|  WIN: 65%  BARS: 12  TRAIL: 45%  RST: 3 |
+-----------------------------------------+

107.8 Mode Transition Toast (B3)

When user changes StrategyMode to/from SmartTrend:

107.9 New tests S08

19 new tests (395 total):


108. SMARTTREND SENTINEL LOOP + ALERTS (S09) โ€” Session 57

108.1 Sentinel Loop Backend

New file: src-tauri/src/loops/smarttrend_sentinel.rs

The sentinel loop continuously scans all active assets (positions + HFT targets + signal assets), calls SmartTrendEngine::evaluate() on each one with real live data, detects FSM transitions and issues alerts.

Adaptive cadence per symbol:

FSM statusDefault rangeConfig field
Flat30sst_sentinel_idle_secs
Stalking5sst_sentinel_stalking_secs
Entry/InTrade/Trail2sst_sentinel_hot_secs

The loop sleeps after the shortest cadence of all monitored symbols.

Assembly live data:

InputSourceLock type
Oracle score/confidence/regimeindicator_cache.last_oracle_snapshot()Mutex
OFI, microprice, spread, imbalancemarket.ofi_stateArcSwap (lock-free)
CVDmarket.cvdMutex
GPU consensusnexus_consensusMutex
Current pricemarket.last_pricesMutex

Registered in watchdog.register("smarttrend_sentinel") at startup

108.2 Symbol Priority Queue (B2)

Instead of linear iteration, symbols are evaluated by BinaryHeap<SymbolPriority>:

memberRankaPriority
InTrade4The tallest
Entry/Trail3
Stalking2
Flat1The lowest

Within the same rank, symbols with a higher score are evaluated first. Reduces reaction latency on critical symbols.

108.3 Micro-Latency Tracking (B1)

Each evaluate() is timed with Instant::now() / elapsed():

UI indicator in Alert Log header:

108.4 Alert Severity Classification (B4)

AlertSeverity::Info     โ€” Flat->Stalking, Stalking->Flat
AlertSeverity::Warning  โ€” Entry, Trail, Stalking timeout
AlertSeverity::Critical โ€” Exit, ChangePoint Reset, Kill

Backend issues severity in payload smarttrend-alert. Differentiated cooldown: INFO respects per-symbol cooldown (default 30s), WARNING/CRITICAL always emits.

108.5 Audio Alerts (6 new sounds)

SoundEventosCharacter
st_stalkingFlat->StalkingShort rising tone
st_entryEntry confirmedDouble beep fast
st_exitExit signalDescending tone
st_trailTrail enabledShort metallic tone
st_changepointBreak regimeGlitch/static burst
Kill switchKill switchShort alarm

All generated via Web Audio API (oscillator + gain envelope), without external files. Cooldown 30s per symbol + event-type in frontend.

108.6 Alert Log UI

Container #st-alert-log under SmartTrend Live panel:

+--[ ALERT LOG ]--[ 245ยตs ]--[I][W][C]--[ร—]--+
| TIME     SYM   EVENT  SCORE  DIR            |
| 14:23:05 AAPL  ENTRY  72.3   LONG           |
| 14:22:51 TSLA  STALK  56.8   SHORT          |
| 14:20:12 NVDA  EXIT   45.1   --             |
+--------------------------------------------- +

108.7 Dashboard Badge (B3)

Persistent badge in the header-right area:

[ 5 | 2 ACT | TSLA InTrade ]

108.8 Visual Alerts

108.9 Config Fields New

FieldDefaultClampDescription
st_sentinel_idle_secs305-300Cadence Flat
st_sentinel_stalking_secs51-60Stalking cadence
st_sentinel_hot_secs21-30Entry/InTrade/Trail cadence
st_sentinel_alert_cooldown_secs305-600Cooldown per-symbol INFO alerts

Backward compatible โ€” old settings files without these fields use the default values โ€‹โ€‹via #[serde(default)].

108.10 Tauri Commands New

CommandReturnDescription
get_sentinel_statusSentinelStatusSentinel status: running, symbols, badge

108.11 Files

FileCHANGE
loops/smarttrend_sentinel.rsNEW: sentinel loop + 10 tests
loops/mod.rsRegistration modules
loops/watchdog_loop.rsspawn_loop_by_name branch
smarttrend.rs4 config fields + serde defaults
indicator_cache.rslast_oracle_snapshot() + OracleSnapshot
commands/smarttrend_cmd.rsget_sentinel_status command
commands/settings.rs4 fields in apply_smarttrend_field
main.rswatchdog register + spawn loop + command
titan_audio.js6 new synthetic sounds
titan_bootstrap.jsAlert listener, log rendering, badge, severity
index.htmlAlert log container, dashboard badge, severity toggles
styles.cssAlert log CSS, badge, severity, toast SmartTrend

108.12 New tests S09

10 new tests (405 total):


109. SMARTTREND BOT MARKER-DRIVEN (S10) โ€” Session 58

109.1 SmartTrendAccount โ€” Virtual Sub-Account

Structure SmartTrendAccount in smarttrend.rs โ€” separate capital tracking for SmartTrend trades:

FieldTypeDescription
allocated_capitalf64Current capital (increase/decrease with PnL + topup/withdraw)
f64f64realized_pnl_today
PnL realized in the current sessionf64PnL realized in the current session
total_realized_pnlf64Cumulative Total PnL
high_water_markf64The highest capital achieved
max_drawdown_pctf64Maximum drawdown as a percentage
trade_count_todayu32Number of trades today
win_count_todayu32Number of wins today
loss_count_todayu32Number of losses today
total_tradesu64Total trades all-time
u64u64All-time win totals
avg_winf64Earnings average (running)
avg_lossf64Running average
pausedboolBot paused flag
breaker_triggeredboolCircuit breaker fired

Key methods: record_fill(pnl), drawdown_pct(), hit_rate(), kelly_fraction(), compute_size_usd(), daily_reset().

Persistence: data/titan_st_account.json with .bak automatic backup.

109.2 Config Fields S10

7 new fields in SmartTrendConfig (all with #[serde(default)] backward-compatible):

FieldDefaultDescription
st_risk_per_trade0.01Fraction of capital per trade (1%)
st_max_dd_pct5.0Maximum drawdown before the circuit breaker
st_bot_loop_ms2000Bot loop cadence in ms
st_bot_pausedfalseBot starts paused
st_kelly_enabledfalseActivate Kelly sizing
st_kelly_min_trades20Minimum trades before Kelly
st_max_kelly_fraction0.25Cap Kelly fraction

109.3 SmartTrend Bot Loop

NEW File: src-tauri/src/loops/smarttrend_bot.rs

Architecture: Dedicated loop (NOT autopilot) that reads the state of the SmartTrend engine from the sentinel and executes orders based on the FSM markers.

Main Stream:

  1. Guard: skip if mode != SmartTrend, killed, paused
  2. ST Circuit Breaker: if drawdown > st_max_dd_pct โ†’ force exit ALL + pause + emit alert
  3. Read engine snapshot (state, direction, score, transition)
  4. Entry: on SmartTrendStateKind::Entry with no existing position โ†’ compute_size_usd โ†’ send_order_internal with tag ST|AUTO|{symbol}|{ts}
  5. Exit: on Flat transition from Trail/InTrade โ†’ close_position
  6. Persist account periodically + dedup actions
  7. Adaptive cadence: fast (1s) with positions, slow (3s) without

Safety mechanisms:

109.4 Trade Updates โ€” ST Fill Detection

In trade_updates.rs:

109.5 Tauri Commands S10

5 new orders registered in invoke_handler:

CommandparametersGuardEffect
smarttrend_topupamount: f64amount <= buying_powerIncrease allocated_capital
smarttrend_withdrawamount: f64amount <= available - notional_openDecrease allocated_capital
smarttrend_pausepaused: bool-Toggle st_bot_paused + persist
smarttrend_account_stats--Return SmartTrendAccount JSON
smarttrend_force_exit_allconfirm_token: String"CONFIRM_ST_LIQUIDATE"Force close ALL ST AUTO positions

109.6 UI โ€” SmartTrend Account Panel

Panel #st-account-panel (.cyber-panel) with:

109.7 S10 Bonuses

B1: Live Micro Inputs โ€” Sentinel assemble_macro_input() now uses real data from oracle snapshot (kalman_gain, price_surprise, changepoint_prob, run_length) instead of fixed placeholders. 4 new fields added in Indicators struct and propagated through merge_streaming_oracle.

B2: Daily Reset โ€” daily_reset.rs calls SmartTrendAccount::daily_reset() at 09:30 ET. Zero pnl_today, trade_count_today, win_count_today, loss_count_today. Adjust initial_capital to current allocated_capital. Issue smarttrend-daily-reset event.

B3: Sentinel-to-Bot Bridge โ€” When sentinel detects Entry marker, call bot_wake().notify_one(). Bot loop uses sleep_or_wake() with tokio::select! on sleep + Notify. Reduces entry latency from ~2s (normal cadence) to ~0s.

B4: ST Positions Badge in Header โ€” Badge #st-positions-badge shows "ST: 3 +$45.20" (green) or "ST: 0 -$12.00" (red). It is updated on every smarttrend-fill event + polling 5s.

109.8 S10 Tests

20 new tests (274 total):


110. S11: AUTO/MAN Per Asset + Trade Panels

110.1 Per-Asset AUTO/MAN Mode

SmartTrend supports per-symbol execution mode: each asset can be individually configured as AUTO (automatic execution by bot) or MAN (manual execution by trade panel).

Backend:

Tauri Commands S11:

CommandParamsGuardDescription
smarttrend_get_asset_modes--Returns complete HashMap
smarttrend_set_asset_modesymbol: String, mode: StringAUTO->MAN blocked if AUTO position liveSet mode per asset
smarttrend_set_all_modesmode: String, confirm_token: Option<String>ALL AUTO requires CONFIRM_ST_ALL_AUTOSet ALL assets to one mode
smarttrend_get_trade_panel_datasymbol: String-Assemble complete data (price, score, sizing, Kelly, pillars, mode)

110.2 Bot Loop โ€” Filtering on Asset Mode

110.3 Sentinel Events S11

110.4 UI โ€” Trade Panel SMARTTREND TRADE

Panel #st-trade-panel (.cyber-panel):

110.5 UI โ€” Exit Signal Panel

Panel #st-exit-panel (.cyber-panel):

110.6 UI โ€” ST Assets Table

Panel #st-assets-panel (.cyber-hud-table):

110.7 Keyboard Shortcuts S11

ShortcutTrade PanelExit Panel
EnterEXECUTECLOSE 100%
EscapeSKIPHOLD
VVIEW CHARTVIEW CHART
1/2/3/4Quick sizing presets-

Guard: shortcuts active only when the ST panel is visible (does not interfere with the rest).

110.8 Position Markers

SmartTrend positions display distinctive tag:

110.9 Bonuses S11

B1: Countdown Timer + Urgency Indicator

B2: Smart Sizing Suggestion

B3: Trade History per Asset Tooltip

B4: Mode Change Audit Trail

110.10 Tests S11

16 new tests (441 total):


111. S12a: SMARTTREND CONFIG TAB (Tab 13)

Tab 13 SMARTTREND CFG is the complete configuration interface for the SmartTrend engine. Displays and allows modification of all ST parameters, with live readout and FSM state visualization.

111.1 Access

111.2 Section 1: PILLAR WEIGHTS (cyan border)

Configure the weights of the 3 SmartTrend pillars:

SliderCamp BackendrankDefault
Macrost_macro_weight0-100 (%)40
Microst_micro_weight0-100 (%)35
Momentumst_momentum_weight0-100 (%)25

111.3 Section 2: ENTRY THRESHOLDS (orange border)

SliderCamp BackendrankDefault
Global Entryst_entry_threshold10-10065
Stalkingst_stalking_threshold5-10055
HYSTEREZEst_hysteresis_margin0-205.0

Per-Regime Grid: overrides per market regime:

RegimeFieldDefault
TRENDINGst_entry_thresholds_060
MEAN REVst_entry_thresholds_170
CHAOTICst_entry_thresholds_275
UNKNOWNst_entry_thresholds_365

Validation: the stalking threshold must be lower than the entry threshold.

111.4 Section 3: MICROSTRUCTURE (green border)

ControlCamp BackendTypeDefault
Dominant Cycle Filterst_dominant_cycle_filterToggleMR
OFI Norm Rangest_ofi_norm_rangeSlider 1-20050
Microprice BPS Rangest_mp_bps_rangeSlider 1-5010.0
CVD Scalest_cvd_scaleSlider 1-1000100

Info box gold: "Micro pillar active only for streamer symbol with live L2 data"

111.5 Section 4: EXIT & TRAIL (orange border)

SliderCamp BackendrankDefault
Trail Tighten % / barst_trail_tighten_pct0-50%5%
Changepoint Resetst_changepoint_reset_threshold0.10-1.000.70
Stabilization Windowst_stabilization_window2-50 bars8

111.6 Section 5: SELF-CORRECTION (purple border)

SliderCamp BackendrankDefault
Bayesian Decayst_bayesian_decay0.990-1.0000.997
Halflife (trades)10-100010-1000200

Live Readout (update to 5s via get_smarttrend_state):

111.7 Section 6: STATE MACHINE LIVE (cyan border)

5 FSM boxes with the active status highlighted:

memberActive ColorAnimation
FLATGrey--
STALKINGGoldieneon-pulse
ENTRYCyan--
IN TRADEGREENEneon-pulse
ferryMagenta--

Under the boxes: Direction (LONG/SHORT/--), Bars in State, Entry Price, Best Price, Combined Score, Agreement (AGREE/MIXED/DIVERGE).

Confirmation progress bar visible in Stalking status.

Refresh at 3s via get_smarttrend_state.

111.8 Action Bar

ButtonActionFeedback
SAVE CONFIGApply only fields modified in batchToast success + audio click
SMART DEFAULTPreset BALANCED (34/33/33)Toast info
RESET DEFAULTSRestore all defaultsConfirmation + toast + audio confirmation
COMPARE (B3)Current vs saved side-by-side overlayGold highlight diffs table

111.9 Bonuses S12a

B1: Config Diff Indicator

B2: Pillar Weights Radar Chart

B3: Config Comparison Mode

111.10 Files Involved

FileRole
src/index.htmlTab button + tab-13 complete container
src/styles.cssCSS S12a (~350 lines)
src/titan_bootstrap.jsinitSmartTrendCfg() (~380 lines)
src/titan_keyboard.jsEscape dismiss compare overlay
src/titan_tabs.jsUnsaved changes warning on tab switch

111.11 Orders Used Bulls

CommandScope
get_smarttrend_configInitial load config
update_smarttrend_configSave per field to SAVE
get_smarttrend_stateLive readout + FSM state

111.12 Tests S12a

12 new tests (453 total):


112. S12b: SMARTTREND UI ACTIONS + CHART OVERLAY

Extension of tab 13 with sections 7-10 (state changes), SmartTrend overlay chart, and EXPORT/IMPORT config.

112.1 Section 7: SMARTTREND ACCOUNT (cyan border)

SmartTrend virtual account management panel.

Information Grid:

FieldSourceRefresh
ALLOCATEDallocated_capital5s
INITIAL5s5s
DAILY PnLrealized_pnl_today5s (green/red)
TOTAL PnLtotal_realized_pnl5s (green/red)
HWMhigh_water_mark5s
MAX DD%max_drawdown_pct5s (red)
BETRAYEDtotal_trades5s
W/Ltotal_wins / losses5s

Actions:

ButtonOrder TaurusConfirmation
TOP-UPsmarttrend_topupNo (validate amount > 0)
WITHDRAWsmarttrend_withdrawNo (validate amount > 0)
BREAKS / SUMMARYsmarttrend_pauseNo (toggle)
Liquidsmarttrend_force_exit_allYes (TitanToast.confirm)
KILL SWITCHsmarttrend_kill_switchYes (double confirmation)

B1 Equity Micro-Chart: Canvas 200x80px with equity curve cyan, gradient fill, HWM dashed gold, drawdown zones red. Fallback text if < 3 trades.

112.2 Section 8: SMARTTREND ASSETS (green border)

Interactive table with all SmartTrend symbols.

ColumnDescription
SYMBOLThe name of the asset
modellerBadge AUTO (cyan) / MAN (gold), click to toggle
MemberFSM colored badge (Flat gray, Stalking cyan, Entry cyan pulse, InTrade green, Trail gold)
slagSmartTrend Combined Score
DIRDirection (Bullish/Bearish/Neutral)
BarseBars in the current state
In PlayGreen dot if there is a position `STopen

Toolbar: Input ADD symbol (add with MAN mode), ALL AUTO (with confirmation CONFIRM_ST_ALL_AUTO), ALL MAN.

B2 Asset Heatmap: Subtle background on each row based on score โ€” red (<30), neutru (30-60), cyan (60-80), green (>80).

112.3 Section 9: SMARTTREND BACKTEST (orange border)

Quick backtest on the active symbol.

B3 Backtest Sparkline: Canvas 300x60px with equity curve green, HWM dashed gold, drawdown zones red, hover tooltip with value.

112.4 Section 10: SENTINEL ALERTS (purple border)

Sentinel alert configuration and monitoring.

ControlCamp BackendDefault
Idle cadencest_sentinel_idle_secs30s
Stalking cadencest_sentinel_stalking_secs5s
Hot cadencest_sentinel_hot_secs2s

Toggles: Audio ON/OFF, Visual ON/OFF, Severity filter (Info/Warning/Critical).

Alert Log: The last 20 alerts, scrollable, with severity badges (Info cyan, Warning orange, Critical red).

Status Badge: RUNNING (green) / STOPPED (red) via get_sentinel_status.

B4 Sentinel Heatmap Badge: Horizontal strip with 3 proportional segments (Info/Warning/Critical), pulse animation on the dominant segment, tooltip with exact counts.

112.5 Chart Overlay SmartTrend

ElementsDescription
States StripFSM Markers
Arrow up cyan (Entry), arrow down red (Exit), circle gold (Trail) on the candlestick at transitionsArrow up cyan (Entry), arrow down red (Exit), circle gold (Trail) on the candlestick at transitions
CVD ToggleCheckbox in strip for magenta CVD overlay

The strip is automatically hidden if SmartTrend is not enabled. Refresh at 3s.

112.6 EXPORT / IMPORT Config

ButtonAction
EXPORTDownload full JSON SmartTrendConfig with schema_version: 1
IMPORTJSON upload, client + server validation (serde + range checks), confirmation, reload

Format: Full JSON with all SmartTrendConfig fields. Unknown fields are ignored during deserialization (backward compatible with #[serde(default)]).

112.7 Orders New Bulls S12b

CommandScope
smarttrend_export_configReturns complete JSON config with schema_version
smarttrend_import_configReceives JSON string, validates, applies and saves

112.8 Tests S12b

8 new tests (461 total):


113. S14: EXECUTION RESILIENCE (Session 63)

Complete hardening of the order execution cycle, health observability, and data-stream robustness.

113.1 Order Lifecycle Tracking

Each order generates a unique client_order_id (UUID v4). The broker's response is parsed for broker_id and status. Automatic retry 1-2x for transient network/server errors (5xx, timeout). Event order-lifecycle is emitted on each attempt.

FieldTypeSource
UUID v4UUID v4Locally generated
broker_idStringParsed from Alpaca's answer
retry_count0-20-2
statusStringnew, accepted, filled etc.

113.2 Pending Order Watchdog

Orders sent are tracked locally in TradingState::pending_orders. The watchdog runs in an autopilot loop and automatically cancels orders:

Cancellation is made via Alpaca DELETE /v2/orders/{broker_id}. Orders are removed from the pending list at fill, partial_fill, rejected, or canceled.

113.3 Equity Sync Health Emitter

EventConditionPayload
equity-sync-degradedModerate consecutive errors{ consecutive_failures, msg }
equity-sync-criticalConsecutive errors >= threshold{ consecutive_failures, msg }

Frontend: Badge EQUITY STALE (gold with pulse) in the cockpit strip when a degraded/critical event is received.

113.4 Trade Updates Resilience

MetraDescription
reconnect_countNumber of WS reconnections since the start
trade-updates-healthEvent issued with connected: bool, reconnect_count, last_disconnect_reason

Front end: Badge WS DISCONN (red with pulses) in cockpit strip when connected = false.

Fills received on WS correlate order.id with pending_orders to remove them from tracking.

113.5 Exit Features

TradeRecord was extended with exit_features: Option<TradeFeatures> โ€” snapshot of the market conditions at the time of closing the position (price, volatility, volume, spread, RSI, VWAP). Complements entry_features for post-trade analysis (entry vs exit delta).

113.6 Bounded Streamer Channel

The Herfindahl-Hirschman Index calculation now uses qty * live_price (from state.market.last_prices) instead of qty * entry_price. Structured logging with hhi_pre, hhi_post, blocked.

113.7 HHI Notional Fixed

The Herfindahl-Hirschman Index calculation now uses qty * live_price (from state.market.last_prices) instead of qty * entry_price. Structured logging with hhi_pre, hhi_post, blocked.

113.8 Cockpit Strip (B1)

The persistent bar under the header with aggregated metrics and health badges:

ElementsSourceRefresh
EQUITYget_settings โ†’ equity5s poll
P&Lget_settings โ†’ Calculated P&L5s poll
POSget_settings โ†’ positions.len5s poll
modellerget_settings โ†’ auto/manual5s poll
BREAKERbreaker-triggered eventEventos
GENDERget_settings โ†’ generation5s poll
EQUITY STABLESequity-sync-degraded/criticalEventos
WS DISCONNtrade-updates-healthEventos

Styling: .cockpit-strip with border-bottom: 1px solid var(--border-subtle), mono font, responsive collapse on mobile.

Triangulation of fills on the chart via LightweightCharts markers:

Triangulation of fills on the chart via LightweightCharts markers:

TypedyedyeText
BUYarrowUplime(--neon-green)B ${qty}
SELL / sellarrowDownlime(--neon-red)S ${qty}

Markers are persistent in window._titanFillMarkers[]. Refresh at 3s via setInterval. The timestamp is converted from ISO 8601 to epoch seconds UTC.

113.10 Journal Min P&L Filter (B3)

Input j-filter-minpnl added to the filter bar of the journal. The value is passed to get_journal_trades as parameter min_pnl. Reset also clears this field.

113.11 Time-in-Trade Column (B4)

TIME column added in the positions table (cyber-hud-table):

termColorCSS class
0-5 mindimpos-time-dim
5-30 mincyanpos-time-cyan
30 minutes - 2 hoursGoldiepos-time-gold
> 2horange + flickerpos-time-orange

Calculation: Date.now()/1000 - position.opened_at. Format: Xh Ym / Xm Ys / Xs.

113.12 Involved Files S14

Filemodifications
src-tauri/Cargo.toml+uuid dependency
src-tauri/src/app_state.rs+broker_order_id on Position, +pending_order_timeout_secs
src-tauri/src/state.rsBounded Sender, +pending_order_timeout_secs settings
src-tauri/src/trading_state.rssrc-tauri/src/commands/order_exec.rs
src-tauri/src/commands/order_exec.rs+OrderResult, UUID gen, retry loop, broker_id parse
src-tauri/src/commands/trading.rsAdapted to OrderResult
src-tauri/src/commands/misc.rs+exit_features/broker_order_id on manual record
src-tauri/src/commands/account.rstry_send bounded channel
src-tauri/src/commands/settings.rstry_send bounded channel
src-tauri/src/loops/autopilot.rsPending watchdog, exit features snapshot, HHI fixed
src-tauri/src/loops/trade_updates.rsHealth emitter, fill correlation, pending removal
src-tauri/src/loops/equity_sync.rsHealth emitter events
src-tauri/src/loops/watchdog_loop.rsBounded channel
src-tauri/src/loops/position_recon.rssrc-tauri/src/trading_engine.rs
src-tauri/src/trading_engine.rs+broker_order_id
src-tauri/src/streamer.rsBounded Receiver
src-tauri/src/main.rsBounded channel(256)
src-tauri/src/journal.rs+exit_features, +broker_order_id
src/index.htmlCockpit strip, positions cyber-hud-table + TIME col
src/styles.cssCockpit strip CSS, time-in-trade CSS
src/titan_bootstrap.jsCockpit strip init, health listeners, fill markers
src/titan_chart_layout.jsapplyFillMarkers()
src/titan_journal.jsminPnl filter wire
src/titan_positions.jsTIME column rendering + color coding

114. S15: TRADING EDGE UPGRADES (Session 64)

Four trading logic improvements + four UI/UX bonuses, all with consistent cyber-HUD style.

114.1 Max-Hold Decay Exit (T1)

Progressive exit mechanism that tightens the trail as the position approaches max_hold_secs. It prevents dead-weight positions that consume capital without action.

How โ€‹โ€‹it works:

  1. When elapsed > max_hold_secs * max_hold_decay_start_pct (default 50% of max hold): the trail starts to tighten proportionally with progress (0..1)
  2. Formula: effective_trail = base_trail * (1.0 - progress * decay_trail_tighten * 100)
  3. When elapsed >= max_hold_secs: force exit with log [MAX_HOLD_DECAY] Force exit

Settings:

114.2 MTF Confirmation Gate (T2)

Confirmation gate on higher timeframe before entry. Check if the proposed direction (BUY/SELL) is aligned with the trend on HTF.

Soft Mode (default): Penalizes the score with mtf_gate_penalty points if HTF does not confirm.

Hard Mode: Completely blocks the entry if HTF does not confirm.

Shared helper: is_htf_aligned(candles, oracle_weights, is_buy) -> (aligned, htf_score) in strategy.rs. Automatic LTF->HTF mapping: 1m->5m, 5m->15m, 15m->1h, 1h->4h, 4h->1d.

Settings:

114.3 Tiered Scanner Top-K (T3)

Pre-ranking pipeline in the scanner that reduces expensive scoring (oracle + GPU) on illegal tickers.

Pipelines:

  1. Pre-rank by dollar volume (close * volume) DESC
  2. Tier 1 (top tier1_count): fully scored โ€” always
  3. Tier 2 (following tier2_count): scored only if RVOL >= gate OR change% >= 3%
  4. Merge results, re-sort by prefilter score, truncate at max_candidates

Settings on ScanParams:

114.4 Risk Parity Manual Orders (T4)

HHI gates on manual orders in send_order_internal. Similar to the existing gate on autopilot, but with a more relaxed limit.

Calculation: HHI post-trade = ฮฃ(notional_i / total_notional)ยฒ. If it exceeds the limit, the order is rejected with a descriptive error.

Settings:

114.5 Regime Band on Chart (B1)

Visual strip under the chart showing the current market regime, updated at 5s.

RegimeColorLabelle
Trending UpNeon Green glowTRENDING UP
Trending DownNeon Red glowTRENDING DOWN
ChaoticNeon Orange glowCHAOTIC
Quiet/RangeDim borderQUIET/RANGE

The oracle score is displayed to the right of the strip.

114.6 Journal Hour-of-Day PnL Heatmap (B2)

Grid canvas 5 days (Mon-Fri) x 13 30-minute intervals (9:30am-4:00pm ET).

Each cell shows the total PnL on that bucket, with gradient color proportional to the magnitude (green=profit, red=loss). Tooltip on hover: day, interval, PnL, number of trades, win rate.

Positioned in Journal tab as .cyber-panel under existing KPIs.

Mini-panel in Nexus with 3 strategy indicators and agreement meter.

Mini-panel in Nexus with 3 strategy indicators and agreement meter.

Indicators: Oracle, GPU, SmartTrend โ€” each with colored badge LONG/SHORT/NEUTRAL.

Agreement Meter: Bar 0-100%: 3/3 agree = 100% green, 2/3 = 66% cyan, 1/3 = 33% gold, 0 = red.

Stale Detection: If an indicator has not updated > 60s, the badge shows "STALE" with animation data-flicker.

Powered by Taurus events nexus-update and smarttrend-state.

114.8 Latency Panel V2 (B4)

Upgrade of the existing latency panel with graphic views.

Sparklines: Canvas 120x28 per metric (Order, GPU, Stream), ring buffer of 60 samples. Cyan line with colored dot at the last value (green < 50%, gold 50-80%, red > 80% of max).

Histogram: Canvas 160x40 with 5 distribution buckets: <1ms (green), 1-5ms (cyan), 5-20ms (gold), 20-100ms (orange), >100ms (red). Accumulate global counter as new data appears.

114.9 Involved Files S15

Filemodifications
src-tauri/src/state.rs+12 settings S15, +10 default functions, +settings_from_state sync, +apply_settings sync, +2 tests
src-tauri/src/app_state.rs+12 fields S15 on AppState, +defaults
src-tauri/src/commands/settings.rs+12 batch update handlers S15
src-tauri/src/loops/autopilot.rsMax-Hold Decay exit logic, MTF gate in evaluate_candidate_entry
src-tauri/src/strategy.rs+is_htf_aligned, +ltf_to_htf, +6 tests
src-tauri/src/commands/order_exec.rsHHI gate manual orders
src-tauri/src/scanner.rsTiered scan pipeline, +3 ScanParams fields, +3 tests
src-tauri/src/trading_engine.rs+fixed broker_order_id on tests
src/index.htmlRegime strip, journal heatmap canvas, strategy agreement panel, latency sparklines+histogram
src/styles.css+120 CSS lines: regime strip, heatmap tooltip, strategy agreement, latency sparklines
src/titan_bootstrap.jsRegime band init, Strategy agreement init
src/titan_journal.jsHour-of-day PnL heatmap (canvas bucketing + rendering + tooltips)
src/titan_rightbar.jsLatency V2 sparklines + histogram (ring buffer + canvas drawing)

ยง115 โ€” S16: UX Polish + Cleanup (Session 65 โ€” Final roadmap session)

115.1 Cockpit Strip V2

115.2 Unified Chart Markers Engine

window._titanMarkerEngine โ€” unique manager of fills + signals + SmartTrend. Debounce 100ms, FIFO head 50, pruning >24h.

115.3 Latency Histogram Rolling Window

Ring buffer 300 samples (5 min). The distribution no longer increases indefinitely.

115.4 Fill Quality Columns HFT Targets

3 columns: SLIP (avg slippage bps), T2F (avg duration), TRADES (count). Backend get_fill_quality_stats. Polling 30s.

115.5 PiP Mini Dashboard (B1)

Floating HUD 260px, draggable, shortcut P, โ€‹โ€‹opacity slider, minimize. Reuse cockpit data.

115.6 LLM Sentiment Batch + Decay (B2)

Batch scoring N headlines, exp decay halflife on confidence. Settings: llm_batch_size (5), sentiment_halflife_secs (3600).

115.7 Mode Audit Trail (B3)

Vec<ModeTransition> chapter 100, timeline panel in Nexus, color coding per mode. Command get_mode_audit_trail.

115.8 Health Score Badge (B4)

HP:XX% in the cockpit. 6 sub-scores: equity sync, WS, breaker, latency, loops, fill rate. Polling 10s.

115.9 Module Entrypoint + $el() Rollout + CSS Cleanup

titan_init.js, registerTabInit(), 464 getElementById โ†’ $el(), CSS var() tokens.


106. Wave 1 MUST-FIX โ€” 9 Critical Fixes + 4 Bonuses (Session 67)

106.1 Fill Deduplication (CRIT-11)

Alpaca reports filled_qty and filled_avg_price cumulative per order. The previous code treats them as incremental, leading to inflated positions ~50% on partial fill -> fill sequences.

Solution: HashMap fill_cumulative per order ID on TradingState. At each fill event, delta_qty = cum_filled_qty - prev_qty is calculated and ONLY the delta is applied. Fills with delta <= 0 are automatically suppressed and counted in fills_deduplicated.

Cockpit badge: DEDUP:N (cyan, visible only when N > 0) shows in real time how many duplicate fills have been prevented.

106.2 Bot Exit Operator Precedence (CRIT-12)

The exit condition in SmartTrend bot had state == Flat && transition.contains("Trail->Flat") || transition.contains("InTrade->Flat") -- without brackets, && binds more tightly than ||, so InTrade->Flat triggers exit even if the state was NOT Flat.

Fix: state == Flat && (transition.contains("Trail->Flat") || transition.contains("InTrade->Flat"))

106.3 Circuit Breaker Latch (CRIT-1)

The breaker sets account.paused = true and account.breaker_triggered = true, but the gate at the beginning of the loop ONLY checks st_config.st_bot_paused from the settings. After the first iteration, the bot could continue trading.

Fix: Check account.paused || account.breaker_triggered at the beginning of the loop + persist settings.smarttrend.st_bot_paused = true after the breaker wire.

106.4 Position Recon Trail-Stops (CRIT-15)

Reconciliation lost the trail high when the price rose above the old high (copy existing.highest_price only if it was higher than current_price, but not if current_price was the highest).

Fixed: highest_price = existing.highest_price.max(current_price), lowest_price = existing.lowest_price.min(current_price). It also preserves broker_order_id.

106.5 Exit Inflight TTL (CRIT-16)

close_position inserts in exit_inflight but the remove was incomplete โ€” it was missing on the error path and canceled/rejected events. Symbols could be stuck permanently.

Fix: TTL 120s cleanup in trade_updates loop + explicit remove on: complete fill, send_order error, rejected/cancelled events.

106.6 Lock Order (CRIT-21)

smarttrend_kill_switch take engine -> settings, smarttrend_pause take settings -> engine = ABBA deadlock potential.

Fix: Standardized order in ALL commands: settings(1) -> smarttrend_engine(2) -> st_account(3). NEVER vice versa.

106.7 API Rate Limit (CRIT-13)

cancel_open_orders_for_symbol was doing DELETE to Alpaca WITHOUT acquire_api_permit, generating 429 rate limit rejections.

Fix: Added permit + tracking record_api_call(). Cockpit badge API:N/200 with color coding.

106.8 AssetCheck JSON (CRIT-5)

If HTTP answered 200 but JSON parse failed, if let Ok(json) was skipped and is_fractionable remained true. The order could go on ticker delisted.

Fix: match explicitly on JSON parse. On Err: reject in hard mode, is_fractionable = false in soft mode.

106.9 Generation ID (HIGH-24)

generation_id was read AFTER HTTP POST, so a bump_generation() during the request attached the wrong generation to PendingOrder.

Fix: Moved state.current_generation() to the beginning of the send_order_internal function, before any await.

106.10 Trail-Stop Integrity Indicator (B4)

New column TRAIL in positions table with badge TRAIL OK (green) / TRAIL WARN (red pulse). Checked at every cockpit poll (5s) by _titanTrailHealth. Visually confirm that trail extremes are correct after reconciliation.


107. Wave 2A SmartTrend Safety โ€” 8 Fixes + 4 Bonuses (Session 68)

Session 68 fixed 8 critical safety bugs in the SmartTrend engine and added 4 cyber-HUD bonuses. Total: 516 tests (+10 new), clippy clean.

107.1 Sentinel Generation Check (CRIT-3)

The Sentinel compares current_generation() < boot_gen, but the generation is monotonically increasing (increases with each respawn). After a watchdog respawn, the old sentinel did NOT stop โ€” it ran like a zombie alongside the new one.

Fix: Replaced < with !=, identical to smarttrend_bot.rs. When the generation changes (in any direction), the sentinel exits with a log warning and gives way to the new instance.

107.2 Multi-Symbol ST Exit (CRIT-6)

The bot exit checks pos.symbol == settings.active_symbol. SmartTrend positions on other symbols are orphaned โ€” they never got auto-exit when the FSM went Flat.

Fix: Deleted the active_symbol guard from the exit block. ALL positions with strategy_mode == "ST|..." receive exit when the engine is Flat. Entries remain gated on active_symbol (correct โ€” only the current symbol in the chart is entered). The guard recently_acted per symbol and freshness_window_ms remain as an anti-spam safety net.

107.3 Kelly Bayesian Loss Floor (CRIT-14)

With zero losses (100% win rate), avg_loss <= 0 => b = 0 => kelly_fraction = 0. Paradoxically, the bot does not measure positions when performing at its maximum.

Fix: Bayesian floor on avg_loss: if avg_loss <= 0, use max(avg_win * 0.1, 1e-9) as conservative prior. Kelly returns a positive fraction (capped at max_fraction), allowing proportional sizing even with a perfect track record.

107.4 Kill Switch Import Guard (CRIT-20)

import_config replaced all of SmartTrendConfig in JSON, including st_killed. A JSON file with st_killed: false disarms the silent kill switch.

Fix: After parsing the import, the safety fields are forced from the current runtime: imported.st_killed = settings.st_killed and imported.st_bot_paused = settings.st_bot_paused. These fields can be modified ONLY through the dedicated commands (smarttrend_kill_switch, smarttrend_pause).

107.5 Entry State Persist Bars (HIGH-11)

The FSM was doing Entry -> InTrade immediately at the next evaluate(). The bot had only one eval window to see the Entry status. If the loop was desynchronized (async timing), the complete entry was missed.

Fix: New config field st_entry_persist_bars (default 3). Entry persists until:

107.6 entries_total Double Count (HIGH-13)

record_transition increments entries_total and Stalking->Entry AND on Entry->InTrade. A single trade = 2 entries in statistics, corrupting trail_hit_rate.

Fix: Counts only transition IN Entry (not InTrade). One transition per trade.

107.7 NaN Weight Firewall (HIGH-15)

If a weight or score was NaN, sum <= 0.0 si adj_sum > 0.0 did not detect NaN (NaN > 0 = false in IEEE 754). NaN propagates in combined score, affecting entry/exit decisions.

Fix: Guards NaN at 3 levels:

  1. normalize_weights: !sum.is_finite() => fallback to defaults (0.40, 0.35, 0.25)
  2. Individual pillar scores: !score.is_finite() => sanitized at 50.0 (neutral) + confidence 0
  3. Combined final score: !combined.is_finite() => 50.0 (neutral)

Counter nan_sanitized_count on engine incremented at each sanitization, exposed in get_risk_status.

107.8 Zombie Loops AbortHandle (HIGH-20)

main.rs spawns loops with tauri::async_runtime::spawn() without abort_and_replace. At the first respawn via watchdog, there are no old handles to abort โ€” the original task continues alongside the new one.

Fix: Macro spawn_with_handle! records AbortHandle for ALL loops at startup through watchdog.abort_and_replace(). On respawn, the old handle is correctly aborted.

107.9 ST SHIELD Safety Dashboard (B1)

Cyber-HUD panel in the sidebar with 8 safety metrics:

MetricsValuesSource
KILLOFF (green) / ON (red pulse)engine.config.st_killed
BREAKERNORMAL / PAUSED / TRIPPEDst_account
DEDUPcounter (gold if > 0)fills_deduplicated
ZOMBIEcounter (red if > 0)watchdog.dead_loops()
NaNcounter (red if > 0)nan_sanitized_count
KELLYfraction 0.00-0.25kelly_fraction()
GEN#Nsession_generation
ORPHANScounter (red if > 0)orphan detection

Shield score composite 0-100%: penalize kill (-50), breaker tripped (-30), zombies (-20), orphans (-15), NaN (-10).

107.10 Generation Timeline Strip (B2)

Visual strip in the cockpit showing the history of generations. Each generation displays the ID and duration. The last generation pulses with neon-pulse. Ring buffer of max 10 entries.

107.11 NaN Firewall Monitor Badge (B3)

Badge NaN:0 (green) / NaN:N (red pulse) in cockpit strip. It shows in real time how many NaN values โ€‹โ€‹were intercepted and sanitized by the firewall in FIX-7.

107.12 Orphan Position Detector (B4)

New column ORPHAN in positions table, visible only for SmartTrend positions. Badge OK (green) confirms that the position has a valid exit path after FIX-2 (multi-symbol exit). Badge ORPHAN (red pulse) indicates positions without an exit path.


108. Wave 2B SmartTrend Correctness โ€” 9 Fixes + 5 Bonuses (Session 69)

Session 69 fixed 9 correctness bugs in the SmartTrend engine and added 5 cyber-HUD bonuses. Total: 526 tests (+10 new), clippy clean.

108.1 Hysteresis Validation (HIGH-12)

st_hysteresis_margin could be configured high enough for the FSM to remain stuck in Stalking (hysteresis >= stalking_strength/2, drop_strength became 0, exit condition was impossible). Fix: semantic validation in validate_smarttrend_config + runtime clamp in max_safe_margin. drop_strength minimum 0.1.

108.2 Sentinel Per-Symbol Oracle Inputs (HIGH-14)

The Sentinel used last_oracle_snapshot() which returned the last accessed entry from the (global) cache. With multi-symbol evaluation, all symbols received the oracle data of the last symbol evaluated. Fixed: new oracle_snapshot_for(symbol) with per-symbol lookup on prefix symbol: in cache keys. Fallback to global when there is no per-symbol data. nexus_consensus remains global (documented architectural limitation).

108.3 Circuit Breaker Reset Race (HIGH-16)

reset_circuit_breaker only resets risk.circuit_breaker but NOT st_account.breaker_triggered, st_account.paused, settings.st_bot_paused. daily_reset resets breaker_triggered but not paused. Fixed: both functions now fully reset the ST state. daily_reset sets paused = false only when breaker_triggered was active (preserves intentional manual pauses).

108.4 Exit Floor Dead Code (HIGH-21)

Line local_stop = local_stop.min(-floor).max(local_stop) was mathematically a no-op (min(x, -floor) followed by max(result, x) = x). Fixed: deleted the no-op, kept only the functional checks if abs < floor. Adaugat guard exit_floor_pct > 0.0.

108.5 Max-Hold Decay 100x (HIGH-22)

The tighten_factor = 1.0 - progress * trail_tighten * 100.0 formula made the 0.003 parameter act like 0.3 per progress unit (100x more aggressive than configured). Fixed: deleted * 100.0, default changed from 0.003 to 0.3, clamp range adjusted [0.05, 0.8]. The actual behavior is identical, but the parameter now correctly reflects its scale.

108.6 Lyapunov Live vs History (HIGH-25)

Live calculate() calculates Lyapunov on the entire series of closes (global). History calculate_history() used window rolling of 200 bars. Divergence: live could see "chaos" on 500 bars, history see "predictable" on the last 200. Fixed: live now uses closes[len-200..] trailing slice, identical to history.

108.7 Kalman price_vs_predicted Mismatch (CRIT-4)

Three issues fixed: (a) indicator_cache applies .abs() to price_surprise, deleting the sign used by macro pillar for velocity alignment; (b) history price_vs_predicted era raw delta (close - pred), live era ratio ((close - state.x[0]) / close); (c) surprise_series per-bar in kalman_filter used .abs(). Fixed: deleted .abs() from the cache and surprise_series, normalized history to ratio (close - pred) / close.

108.8 Duplicate Changepoint Markers (MED-5)

Chart markers were duplicated at each eval cycle because _merge() concatenates without dedup. Fix: dedup by composite key time|position|shape|text via Set in _titanMarkerEngine._merge().

108.9 stalking_timeouts Incremented Wrong (MED-8)

stalking_timeouts is incremented both on hysteresis drop (Stalking->Flat from low score) and on actual timeout. Fixed: the increment now exists only on the path stalking_timeout (when bars_in_state >= 2 * confirmation_needed).

108.10 ST CORRECTNESS Dashboard (B1)

Cyber-HUD panel with 4 correctness metrics, displayed in the sidebar under ST SHIELD:

MetricValuesMeaning
HYSOK (green) / STUCK:N (red pulse)Detect FSM stuck in Stalking > 50 consecutive evaluations
DECAYCurrent score (gold)Last value last_score from engine
LYAP-- (placeholder)Current Lyapunov exponent
KAL+0.3% (green) / -2.1% (red)Kalman price surprise signed ratio

108.11 FSM Transition Heatmap Badge (B2)

Badge compact FSM:S12/E3/T8 in cockpit strip. Ring buffer of 100 evaluations on SmartTrendEngine. Counter per-state (Stalking/Entry/InTrade+Trail). Dominant color: cyan (Stalking), green (Entry), gold (InTrade).

108.12 Breaker Sync Indicator (B3)

Badge BRK:SYNC (green) / BRK:DESYNC (red pulse) in ST SHIELD panel. Compare risk.circuit_breaker.level() != Normal with st_account.breaker_triggered. Visually confirm that the FIX-3 is working correctly.

108.13 Kalman Alignment Sparkline (B4)

Mini CSS bar chart (8 bars) in cockpit strip. Last 8 values โ€‹โ€‹price_surprise from cache pointer. Cyan bars for positive surprise, magenta for negative. Height proportional to maximum. Flat = Kalman aligned with the price, spike = divergence.

108.14 Max-Hold Timer HUD (B5)

New column HOLD in positions table. Progress bar 15/60m with gradient stops: cyan (normal), gold + glow-breathe (>70% of max_hold), red + pulse-red-ring (>90%). Visually shows how close the forced exit position is from max-hold decay.


109. Wave 2C โ€” SmartTrend UI+Chart (Session 71)

109.1 Visible Chart Markers (CRIT-8)

window.candleSeries is now exposed as a global property after creating the series in titan_bootstrap.js. The marker engine _titanMarkerEngine._merge() can set markers on the chart. All 3 sources (signals, fills, SmartTrend) are visible.

109.2 ST CFG Flicker Eliminated (CRIT-9)

All SmartTrend timers in titan_bootstrap.js use TitanTimers.register with { tab: 13 }:

Timers with tab guard automatically stop when another tab is visible, eliminating unnecessary polls and DOM flicker.

109.3 Duplicate HTML IDs Resolved (HIGH-6)

Tab-13 (S12b sections) used the same IDs as the SmartTrend sidebar: st-acct-capital, st-acct-dd, st-acct-trades, st-acct-amount, st-assets-tbody. Now tab-13 uses prefix s12b- (ex: s12b-acct-capital, s12b-assets-tbody). Both sections are updated independently.

109.4 titan_init.js Loaded (HIGH-4)

<script src="titan_init.js" defer></script> added to <head>. INIT_ORDER is executed at DOMContentLoaded, orchestrating the initialization of the modules in the correct order.

109.5 Health Badge Real Data (MED-3)

Health badge HP:N% now uses real data:

109.6 Marker Engine Cleanup

109.7 Timer Consolidation Badge (B1)

Badge TMR:N in the cockpit strip shows the total number of active timers. Tooltip with breakdown: name, interval, tab guard, status. TitanTimers.getAll() displays the full list.

109.8 Marker Engine Health Badge (B2)

Badge MRK:S12/F3/T8 in cockpit strip shows count per source of markers. Color coding: green (all sources > 0), gold (partial), red (no marker). Visually confirm that FIX-1 and FIX-6 are working.

109.9 Duplicate Poll Detector (B3)

Guard dev-only enabled via localStorage.setItem('titanDebug', '1'). Wrapper on invoke with ring buffer 50 entries. If the same Tauri command appears 2+ times in 1 second, log [TITAN] Duplicate poll detected: in the console.

109.10 Chart Marker Stats Overlay (B4)

Micro-overlay on chart (top left corner): SIG:12 FILL:3 ST:8 TOT:23. Semi-transparent (opacity 0.5), 9px cyber-HUD font. Automatically updated every _merge(). CSS: .chart-marker-stats.

109.11 Incremental SessionAnalytics (B5)

recalculate_stats() from titan-risk no longer does O(n) full-scan. Running totals running_gross_wins and running_gross_losses are maintained incrementally in record_trade_with_duration (O(1)). restore_trade_pnls does a single O(n) pass at startup.

109.12 IPC Optimizations


110. Wave 3A โ€” Persistence+Defaults (Session 72)

110.1 Settings Error Propagation (CRIT-7)

All 8 commands that save settings to disk (update_settings, batch_update_settings, set_active_symbol, set_position_mode, set_dry_run, set_symbol_override, remove_symbol_override, apply_full_settings) propagated the error with let _ = -- any write failure was silently ignored.

Fix: Each command returns Err(e) to the frontend with tracing::error!. Issue event settings:save-failed visible in Save Event Timeline (B3).

110.2 Journal Atomic Save (CRIT-17)

TradeJournal::save() used fs::write() directly. A crash in the middle of writing could corrupt the JSON file.

Fix: Write tmp + fs::rename(). The pattern is atomic on POSIX -- the final file is either completely old or completely new, never partial. Emits event journal:saved for timeline UI.

110.3 Profile Load Validation (CRIT-18)

110.4 Dry-Run Default True (CRIT-19)

110.4 Dry-Run Default True (CRIT-19)

110.4 Dry-Run Default True (CRIT-19)

Fresh install had dry_run_enabled: false in AppState::default(). A new user starting the bot for the first time was automatically running with real money.

Fixed:

110.5 WS Auth via Query Parameter (CRIT-2)

The WebSocket /ws from the web dashboard asked for the token only in the Authorization: Bearer header. The native browser WebSocket API (used by new WebSocket(url)) does not support custom headers.

Fix: Handler /ws accepts token and via ?token=... query parameter. The frontend transmits ws=new WebSocket(proto+'//'+location.host+'/ws?token='+encodeURIComponent(token)). The /ws route is separated in ws_router with its own auth middleware.

110.6 Trade PnLs Ring Buffer + Welford Sharpe (HIGH-17)

trade_pnls: Vec<Decimal> was growing indefinitely -- after 10,000+ trades, the vector was consuming significant memory and sharpe_ratio() was doing O(n) full scan on each call.

Fixed:

110.7 HashMap TTL Eviction (HIGH-18)

4 HashMaps in TradingState grew indefinitely in long sessions:

Fix: evict_stale_entries() with different TTL policies:

MapTTLCondition
fill_cumulative24hTimestamp > 24h without activity
failed_order_cooldownexpiredTimestamp value < now
trail_highs / trail_lowsorphanNo active position on the symbol

110.8 WS Reconnect Staleness Flag (HIGH-19)

After a disconnect+reconnect on the market data stream, the first 30 seconds of data may have gaps or stagnant values. The bot had no detection mechanism.

Fixed:

110.9 Persistence Health Dashboard (B1)

Cyber-HUD panel with 2x2 grid in the monitoring area:

CellMetracolors
DISKSettings save statusgreen (ok) / red (fail)
JRNLJournal save statusgreen (saved) / gold (dirty)
PROFProfile loaded namegreen (loaded)
DRYgreen (ON) / red (OFF with neon pulses)green (ON) / red (OFF with neon pulses)

CSS: .persist-health-grid, .persist-cell, .persist-val. Neon colors with pulsation on critical states.

110.10 Memory Pressure Gauge (B2)

Badge MEM:N in cockpit strip. N = total number of entries from the 4 critical HashMaps in TradingState.

EntriesColorMeaning
< 500GREENENormal
500-2000GoldieRaised
> 2000edHigh pressure

Backend: map_entries_total added in get_risk_status JSON.

110.11 Save Event Timeline (B3)

Chronological timeline in Persistence Health panel with chips per save event:

110.12 Dry-Run Guard Overlay (B4)

When dry_run=false (live trading):

110.13 Eviction Stats Counter (B5)

Badge EVT:N in cockpit strip. N = total entries evicted by evict_stale_entries() since startup.

EvictionsColor
GREENEGREENE
100-1000Goldie
> 1000ed

Backend: evicted_entries_total exposed in get_risk_status from AtomicU64.

110.14 Persistence Optimizations

OPT-1: Batch Settings Save Debounce

batch_update_settings execute a single save_settings_to_disk at the end, instead of write per field. Reduce N disk writes to 1 per batch.

OPT-2: Journal Save Debounce

TradeJournal with dirty: bool and last_save_epoch: u64. Save effectively only if:

  1. dirty == true (there is unsaved data)
  2. >= 30s have passed since the last save

flush() forced to graceful_shutdown so as not to lose data. Reduces N disk writes to ~2/minute during active periods.

OPT-3: Snapshot Delta Compression

save_state_snapshot compare the SHA-256 hash of the serialized snapshot with the previous hash (read from the .sha256 sidecar file). If they are identical, skip write completely. Reduces disk writes to 0 when the state does not change (idle periods).