# Foxhunt HFT Trading Terminal - Ratatui Widgets ## Overview This document describes the specialized Ratatui widgets implemented for the Foxhunt HFT trading terminal. These widgets provide real-time financial data visualization with high-performance rendering and interactive capabilities. ## Architecture The widget system is built on top of Ratatui and provides: - **High-performance rendering** for real-time financial data - **Interactive mouse and keyboard support** for navigation and configuration - **Color-coded status indicators** for risk levels and market conditions - **Responsive layouts** that adapt to different terminal sizes - **Custom drawing** for specialized financial charts - **Data binding** with automatic updates from live data streams ## Widget Modules ### 1. Base Framework (`mod.rs`) The foundation module provides: ```rust // Common traits and utilities pub trait FinancialWidget { type Data; fn update_data(&mut self, data: Self::Data); fn clear(&mut self); fn title(&self) -> &str; fn has_data(&self) -> bool; } // Color scheme for consistent theming pub struct FinancialColors { pub profit: Color, // Green for profits pub loss: Color, // Red for losses pub neutral: Color, // Yellow for neutral pub bid: Color, // Cyan for bids pub ask: Color, // Magenta for asks // ... more colors } // Data structures for financial information pub struct Candle { /* OHLC + volume */ } pub struct OrderLevel { /* price, size, count */ } pub struct PnlData { /* P&L tracking */ } pub struct RiskMetrics { /* risk monitoring */ } ``` ### 2. Candlestick Chart (`candlestick_chart.rs`) Real-time price visualization with: ```rust let chart = CandlestickChart::new("EURUSD", 200) .with_precision(4) // 4 decimal places .with_volume(true) // Show volume bars .with_time_range(300); // 5 minutes of data // Features: // - Auto-scaling price range // - Volume indicators at bottom // - Price grid lines and labels // - Real-time candle updates // - Color-coded bull/bear candles ``` **Visual Layout:** ``` ┌─ EURUSD Price Chart ─────────────────────────┐ │ CLOSE: 1.0825 (+0.15%) │ │ ┌────────────────────────────────────────┐ │ 1.0850 │ │ ███ │ │ │ │ █████ │ │ 1.0825 │ │ ███████ │ │ │ │ █████████ │ │ 1.0800 │ │ ███████████ │ │ │ │ █████████████ │ │ 1.0775 │ │ ███████████████ │ │ │ │ ████ Volume ████ │ │ │ └────────────────────────────────────────┘ │ └──────────────────────────────────────────────┘ ``` ### 3. Order Book Widget (`order_book.rs`) Market depth visualization: ```rust let order_book = OrderBookWidget::new("Order Book") .with_depth_levels(15) // Show 15 levels per side .with_price_precision(4) // 4 decimal places .with_count_display(true) // Show order counts .with_depth_bars(true); // Visual depth bars // Features: // - Bid/ask levels with price, size, count // - Visual depth representation // - Spread calculation and highlighting // - Size aggregation options // - Real-time updates ``` **Visual Layout:** ``` ┌─ Order Book ──────────────────────────────────┐ │ Best: 1.0824 / 1.0825 | Spread: 0.0001 │ │ Bid Price │ Bid Size │Count│Price │Ask Size│ │ 1.0824 │ 150 │ 3 │ │ │ │ 1.0823 │ 200 │ 5 │ │ │ │ 1.0822 │ 100 │ 2 │ │ │ │ ──────────┴──────────┴─────┼────────┴────────│ │ Spread: 0.0001 (1 bps) │ │ ──────────┬──────────┬─────┼────────┬────────│ │ │ │ │1.0825 │ 120 │ │ │ │ │1.0826 │ 180 │ │ │ │ │1.0827 │ 90 │ └───────────────────────────────────────────────┘ ``` ### 4. P&L Heatmap (`pnl_heatmap.rs`) Portfolio performance visualization: ```rust let heatmap = PnlHeatmap::new("P&L Performance") .with_grouping(HeatmapGrouping::Strategy) // Group by strategy .with_percentage(true) // Show percentages .with_counts(true); // Show trade counts // Features: // - Strategy/time-based grouping // - Color intensity based on P&L magnitude // - Interactive cell selection // - Performance metrics summary // - Configurable aggregation periods ``` **Visual Layout:** ``` ┌─ P&L Performance ─────────────────────────────┐ │ Total: +1,250 | Win Rate: 65.2% (15/23) │ │ ┌─Strategy A─┐ ┌─Strategy B─┐ ┌─Strategy C─┐ │ │ │ +850 │ │ -200 │ │ +600 │ │ │ │ +12.5% │ │ -3.2% │ │ +8.1% │ │ │ │ (8 trades) │ │ (3 trades) │ │ (12 trades)│ │ │ └────────────┘ └────────────┘ └────────────┘ │ │ Green=Profit Red=Loss Intensity=Size │ └───────────────────────────────────────────────┘ ``` ### 5. Risk Gauge Widget (`risk_gauge.rs`) Real-time risk monitoring: ```rust let risk_gauge = RiskGauge::new("Risk Monitor") .with_style(GaugeStyle::Semicircular) // Gauge appearance .with_labels(true) // Show percentages .with_trends(true); // Show trend arrows // Features: // - VaR utilization tracking // - Position size monitoring // - Drawdown indicators // - Color-coded risk levels // - Historical trend analysis ``` **Visual Layout:** ``` ┌─ Risk Monitor ────────────────────────────────┐ │ VaR: 65.0% | Pos: 45.0% | Risk: MEDIUM │ │ ┌─VaR Util─┐ ┌─Position─┐ ┌─Drawdown─┐ │ │ │ 65% │ │ 45% │ │ -2.5% │ │ │ │ ████▒▒ │ │ ███▒▒▒ │ │ █▒▒▒▒▒ │ │ │ │ ↗ │ │ → │ │ ↘ │ │ │ └──────────┘ └──────────┘ └──────────┘ │ │ Green=Safe Yellow=Caution Red=Critical │ └───────────────────────────────────────────────┘ ``` ### 6. Sparkline Widget (`sparkline.rs`) Compact time series visualization: ```rust let sparkline = Sparkline::new("Price Trend", 100) .with_current_value(true) // Show latest value .with_auto_scale(true) // Auto-scale range .with_precision(4); // Display precision // Features: // - Minimal chart for small spaces // - Trend visualization // - Current value display // - Auto-scaling data range // - Color-coded trend direction ``` **Visual Layout:** ``` ┌─ Price Trend ─────────────────┐ │ ▁▂▃▅▆█▆▅▃▂▁▂▃▅▆█▆▅▃▂▁▂▃▅▆█ │ │ Current: 1.0825 (+0.15%) │ └───────────────────────────────┘ ``` ### 7. Configuration Form (`config_form.rs`) Interactive settings management: ```rust let config_form = ConfigForm::new("System Configuration") .add_text_field("api_endpoint", "API Endpoint", "ws://localhost:8080", true) .add_number_field("update_interval", "Update Interval", 250.0, 50.0, 5000.0, true) .add_boolean_field("enable_sound", "Enable Sound Alerts", false) .add_select_field("risk_level", "Risk Level", vec!["Low", "Medium", "High"], None, true) .with_inline_errors(true); // Features: // - Multiple input field types // - Real-time validation // - Keyboard navigation // - Custom validators // - Form submission handling ``` **Visual Layout:** ``` ┌─ System Configuration ────────────────────────┐ │ Navigate: ↑↓ Select: Enter Submit: S │ │ > API Endpoint: ws://localhost:8080 │ │ Update Interval: 250 (range: 50-5000) │ │ ☑ Enable Sound Alerts │ │ Risk Level: Medium ▼ (3) │ │ ⚠ Update interval must be >= 50ms │ └───────────────────────────────────────────────┘ ``` ## Enhanced Terminal UI The `EnhancedTerminalUI` integrates all widgets into a comprehensive dashboard: ### Dashboard Layout ``` ┌═══════════════════════════════════════════════════════════════════════════╗ ║ FOXHUNT HFT TRADING DASHBOARD ║ ╚═══════════════════════════════════════════════════════════════════════════╝ ┌─────────────────────────────────────┬─────────────────────────────────────┐ │ Price Chart │ Risk Monitor │ │ ████████████████████████████████ │ VaR: 65% Position: 45% │ │ ████ Volume ████████████████████ │ ████████▒▒ ███████▒▒▒ │ │ │ Drawdown: -2.5% Sharpe: 1.25 │ └─────────────────────────────────────┼─────────────────────────────────────┤ │ P&L Heatmap │ P&L Trend │ │ [Strategy A] [Strategy B] [C] │ ▁▂▃▅▆█▆▅▃▂▁▂▃▅▆█▆▅▃▂▁ │ │ +850 -200 +600 │ Current: +1,250 (+15.2%) │ └─────────────────────────────────────┴─────────────────────────────────────┘ 1:Dashboard 2:Trading 3:Risk 4:Market 5:Health 6:Config Q:Quit ``` ### View Navigation - **Dashboard (1)**: Overview with all key metrics - **Trading (2)**: Price chart + order book - **Risk (3)**: Risk gauges + P&L heatmap - **Market Data (4)**: Order book + price/volume sparklines - **Health (5)**: System status and performance - **Configuration (6)**: Interactive settings form ## Usage Examples ### Basic Widget Setup ```rust use tli::ui::widgets::*; // Create and configure widgets let mut price_chart = CandlestickChart::new("EURUSD", 200) .with_precision(4) .with_volume(true); // Update with real-time data price_chart.add_candle(Candle { timestamp: Utc::now(), open: Decimal::new(10825, 4), high: Decimal::new(10850, 4), low: Decimal::new(10800, 4), close: Decimal::new(10835, 4), volume: Decimal::new(1500, 0), }); // Render in Ratatui f.render_widget(price_chart, area); ``` ### Enhanced UI Application ```rust use tli::EnhancedTerminalUI; #[tokio::main] async fn main() -> Result<()> { let mut ui = EnhancedTerminalUI::new(); ui.start().await?; Ok(()) } ``` ### Environment Configuration ```bash # Enable enhanced UI (default: true) export FOXHUNT_ENHANCED_UI=true # Service endpoints export FOXHUNT_SERVICE_HOST=localhost # Run the terminal cargo run --bin tli ``` ## Performance Characteristics - **Update Frequency**: 4 FPS (250ms intervals) for smooth real-time updates - **Memory Usage**: Circular buffers prevent memory growth - **Rendering**: Minimal redraws using Ratatui's efficient rendering - **Data Handling**: Zero-copy where possible, efficient serialization ## Keyboard Controls ### Global Navigation - `1-6`: Switch between views - `q`: Quit application - `Ctrl+C`: Graceful shutdown ### Configuration Form - `↑↓`: Navigate fields - `Enter`: Edit field - `Space`: Toggle boolean fields - `Tab`: Next field - `Esc`: Cancel editing - `S`: Submit form ## Color Coding - **Green**: Profits, low risk, healthy status - **Red**: Losses, high risk, critical alerts - **Yellow**: Neutral, medium risk, warnings - **Cyan**: Bid prices, buy orders - **Magenta**: Ask prices, sell orders - **Gray**: Disabled, no data, background ## Real-time Data Integration The widgets are designed to integrate with live data streams: ```rust // Example data update cycle async fn update_widgets(widgets: &mut UIWidgets) { // Market data updates if let Ok(candle) = market_data_service.get_latest_candle().await { widgets.price_chart.add_candle(candle); } // Order book updates if let Ok(book) = market_data_service.get_order_book().await { widgets.order_book.update_order_book(book); } // Risk metrics updates if let Ok(risk) = risk_service.get_current_metrics().await { widgets.risk_gauge.update_metrics(risk); } // P&L updates if let Ok(pnl_data) = portfolio_service.get_pnl_data().await { widgets.pnl_heatmap.add_data(pnl_data); } } ``` ## Testing Each widget includes comprehensive unit tests: ```bash # Run widget tests cargo test --package tli widgets # Run with coverage cargo test --package tli widgets -- --test-threads=1 # Benchmark performance cargo bench --package tli widget_performance ``` ## Future Enhancements Planned improvements: 1. **Mouse Support**: Click-to-select, scroll-to-zoom 2. **Theme Customization**: User-defined color schemes 3. **Data Export**: Save chart data to files 4. **Alert System**: Visual/audio notifications 5. **Plugin Architecture**: Custom widget development 6. **Mobile Support**: Responsive design for smaller terminals ## Contributing When adding new widgets: 1. Implement the `FinancialWidget` trait 2. Follow the established color scheme 3. Add comprehensive tests 4. Update this documentation 5. Ensure real-time performance ## Dependencies - `ratatui`: Terminal UI framework - `crossterm`: Terminal control - `chrono`: Date/time handling - `foxhunt-core`: Core types and utilities - `color-eyre`: Error handling and display