Team Ai
Modelpublic

ParallelLLC/algorithmic_trading

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
27likes32downloads
UI_SETUP.md390 linesDownload Raw Back to root
1# UI Integration Guide2 3This guide covers the comprehensive UI system for the Algorithmic Trading project, providing multiple interface options for different use cases.4 5## ๐ŸŽฏ UI Options Overview6 7### 1. **Streamlit UI** - Quick Prototyping8- **Best for**: Data scientists, quick experiments, rapid prototyping9- **Features**: Interactive widgets, real-time data visualization, easy configuration10- **Port**: 850111- **URL**: http://localhost:850112 13### 2. **Dash UI** - Enterprise Dashboards14- **Best for**: Production dashboards, real-time monitoring, complex analytics15- **Features**: Advanced charts, real-time updates, professional styling16- **Port**: 805017- **URL**: http://localhost:805018 19### 3. **Jupyter UI** - Interactive Notebooks20- **Best for**: Research, experimentation, educational purposes21- **Features**: Interactive widgets, code execution, rich documentation22- **Port**: 888823- **URL**: http://localhost:888824 25### 4. **WebSocket Server** - Real-time Data26- **Best for**: Real-time trading signals, live data streaming27- **Features**: WebSocket API, real-time updates, trading signals28- **Port**: 876529- **URL**: ws://localhost:876530 31## ๐Ÿš€ Quick Start32 33### Prerequisites34```bash35# Install UI dependencies36pip install -r requirements.txt37 38# Verify installation39python -c "import streamlit, dash, plotly, ipywidgets; print('โœ… All UI dependencies installed')"40```41 42### Launch Individual UIs43 44#### Streamlit (Recommended for beginners)45```bash46python ui_launcher.py streamlit47```48 49#### Dash (Recommended for production)50```bash51python ui_launcher.py dash52```53 54#### Jupyter Lab55```bash56python ui_launcher.py jupyter57```58 59#### WebSocket Server60```bash61python ui_launcher.py websocket62```63 64#### Launch All UIs65```bash66python ui_launcher.py all67```68 69## ๐Ÿ“Š Streamlit UI Features70 71### Dashboard72- **System Status**: Real-time trading status, portfolio value, P&L73- **Configuration Management**: Load and modify trading parameters74- **Quick Actions**: One-click data loading, Alpaca connection, model training75 76### Data Ingestion77- **Multiple Sources**: CSV, Alpaca API, Synthetic data78- **Data Validation**: Automatic data quality checks79- **Technical Indicators**: Automatic calculation of moving averages, RSI, MACD80- **Interactive Charts**: Candlestick, line, volume charts with Plotly81 82### Alpaca Integration83- **Account Connection**: Secure API key management84- **Market Status**: Real-time market hours and status85- **Position Monitoring**: Current positions and portfolio value86- **Order Management**: Buy/sell order execution87 88### FinRL Training89- **Algorithm Selection**: PPO, A2C, DDPG, TD390- **Hyperparameter Tuning**: Learning rate, batch size, training steps91- **Training Progress**: Real-time training metrics and progress92- **Model Evaluation**: Performance metrics and backtesting93 94### Trading Controls95- **Live Trading**: Start/stop live trading with Alpaca96- **Backtesting**: Historical strategy testing97- **Risk Management**: Position sizing and drawdown limits98- **Emergency Stop**: Immediate trading halt99 100### Portfolio Monitoring101- **Real-time Portfolio**: Live portfolio value and P&L102- **Position Analysis**: Individual position performance103- **Allocation Charts**: Portfolio allocation visualization104- **Risk Metrics**: Sharpe ratio, drawdown analysis105 106## ๐Ÿ“ˆ Dash UI Features107 108### Enterprise Dashboard109- **Professional Styling**: Bootstrap themes and responsive design110- **Real-time Updates**: Live data streaming and updates111- **Advanced Charts**: Interactive Plotly charts with zoom, pan, hover112- **Multi-page Navigation**: Tabbed interface for different functions113 114### Advanced Analytics115- **Technical Analysis**: Advanced charting with indicators116- **Performance Metrics**: Comprehensive trading performance analysis117- **Risk Management**: Advanced risk monitoring and alerts118- **Strategy Comparison**: Multiple strategy backtesting and comparison119 120### Real-time Monitoring121- **Live Trading Activity**: Real-time trade execution monitoring122- **System Alerts**: Automated alerts for important events123- **Portfolio Tracking**: Live portfolio updates and analysis124- **Market Data**: Real-time market data visualization125 126## ๐Ÿ““ Jupyter UI Features127 128### Interactive Development129- **Widget-based Interface**: Interactive controls for all functions130- **Code Execution**: Direct Python code execution and experimentation131- **Data Exploration**: Interactive data analysis and visualization132- **Model Development**: Iterative model training and testing133 134### Research Tools135- **Notebook Integration**: Rich documentation and code examples136- **Data Analysis**: Pandas and NumPy integration137- **Visualization**: Matplotlib, Seaborn, Plotly integration138- **Experiment Tracking**: Training history and model comparison139 140## ๐Ÿ”Œ WebSocket API141 142### Real-time Data Streaming143```javascript144// Connect to WebSocket server145const ws = new WebSocket('ws://localhost:8765');146 147// Listen for market data updates148ws.onmessage = function(event) {149    const data = JSON.parse(event.data);150    151    if (data.type === 'market_data') {152        console.log('Price:', data.price);153        console.log('Volume:', data.volume);154    }155    156    if (data.type === 'trading_signal') {157        console.log('Signal:', data.signal);158    }159    160    if (data.type === 'portfolio_update') {161        console.log('Portfolio:', data.account);162    }163};164```165 166### Available Message Types167- `market_data`: Real-time price and volume data168- `trading_signal`: FinRL model trading signals169- `portfolio_update`: Account and position updates170- `trading_status`: Trading system status171- `system_alert`: System alerts and notifications172 173## ๐Ÿ› ๏ธ Configuration174 175### Environment Variables176```bash177# Alpaca API credentials178export ALPACA_API_KEY="your_api_key"179export ALPACA_SECRET_KEY="your_secret_key"180 181# UI configuration182export STREAMLIT_SERVER_PORT=8501183export DASH_SERVER_PORT=8050184export JUPYTER_PORT=8888185export WEBSOCKET_PORT=8765186```187 188### Configuration File189```yaml190# config.yaml191ui:192  streamlit:193    server_port: 8501194    server_address: "0.0.0.0"195    theme: "light"196  197  dash:198    server_port: 8050199    server_address: "0.0.0.0"200    theme: "bootstrap"201  202  jupyter:203    port: 8888204    ip: "0.0.0.0"205    token: ""206  207  websocket:208    host: "0.0.0.0"209    port: 8765210    max_connections: 100211```212 213## ๐Ÿ”ง Customization214 215### Adding Custom Charts216```python217# In ui/streamlit_app.py218def create_custom_chart(data):219    fig = go.Figure()220    fig.add_trace(go.Scatter(221        x=data['timestamp'],222        y=data['custom_indicator'],223        name='Custom Indicator'224    ))225    return fig226```227 228### Custom Trading Strategies229```python230# In ui/dash_app.py231def custom_strategy(data, config):232    # Implement your custom strategy233    signals = []234    for i in range(len(data)):235        if data['sma_20'][i] > data['sma_50'][i]:236            signals.append('BUY')237        else:238            signals.append('SELL')239    return signals240```241 242### WebSocket Custom Messages243```python244# In ui/websocket_server.py245async def broadcast_custom_message(self, message_type, data):246    message = {247        "type": message_type,248        "timestamp": datetime.now().isoformat(),249        "data": data250    }251    await self.broadcast(message)252```253 254## ๐Ÿš€ Deployment255 256### Docker Deployment257```bash258# Build UI-enabled Docker image259docker build -t trading-ui .260 261# Run with UI ports exposed262docker run -p 8501:8501 -p 8050:8050 -p 8888:8888 -p 8765:8765 trading-ui263```264 265### Production Deployment266```bash267# Using Gunicorn for production268pip install gunicorn269 270# Start Dash app with Gunicorn271gunicorn -w 4 -b 0.0.0.0:8050 ui.dash_app:app272 273# Start Streamlit with production settings274streamlit run ui/streamlit_app.py --server.port 8501 --server.address 0.0.0.0275```276 277### Cloud Deployment278```bash279# Deploy to Heroku280heroku create trading-ui-app281git push heroku main282 283# Deploy to AWS284aws ecs create-service --cluster trading-cluster --service-name trading-ui285```286 287## ๐Ÿ” Troubleshooting288 289### Common Issues290 291#### Port Already in Use292```bash293# Find process using port294lsof -i :8501295 296# Kill process297kill -9 <PID>298 299# Or use different port300python ui_launcher.py streamlit --port 8502301```302 303#### Missing Dependencies304```bash305# Install missing packages306pip install streamlit dash plotly ipywidgets307 308# Or reinstall all requirements309pip install -r requirements.txt310```311 312#### Alpaca Connection Issues313```bash314# Check API credentials315echo $ALPACA_API_KEY316echo $ALPACA_SECRET_KEY317 318# Test connection319python -c "from agentic_ai_system.alpaca_broker import AlpacaBroker; print('Connection test')"320```321 322### Debug Mode323```bash324# Enable debug logging325export LOG_LEVEL=DEBUG326 327# Run with debug output328python ui_launcher.py streamlit --debug329```330 331## ๐Ÿ“š API Reference332 333### Streamlit Functions334- `create_streamlit_app()`: Create Streamlit application335- `TradingUI.run()`: Run the main UI application336- `load_configuration()`: Load trading configuration337- `display_system_status()`: Show system status338 339### Dash Functions340- `create_dash_app()`: Create Dash application341- `TradingDashApp.setup_layout()`: Setup dashboard layout342- `TradingDashApp.setup_callbacks()`: Setup interactive callbacks343 344### Jupyter Functions345- `create_jupyter_interface()`: Create Jupyter interface346- `TradingJupyterUI.display_interface()`: Display interactive widgets347- `TradingJupyterUI.update_chart()`: Update chart displays348 349### WebSocket Functions350- `create_websocket_server()`: Create WebSocket server351- `TradingWebSocketServer.broadcast()`: Broadcast messages352- `TradingWebSocketServer.handle_client_message()`: Handle client messages353 354## ๐Ÿค Contributing355 356### Adding New UI Features3571. Create feature branch: `git checkout -b feature/new-ui-feature`3582. Implement feature in appropriate UI module3593. Add tests in `tests/ui/` directory3604. Update documentation3615. Submit pull request362 363### UI Development Guidelines364- Follow PEP 8 style guidelines365- Add type hints for all functions366- Include docstrings for all classes and methods367- Write unit tests for new features368- Update documentation for new features369 370## ๐Ÿ“ž Support371 372For UI-related issues:3731. Check the troubleshooting section3742. Review the logs in `logs/ui/` directory3753. Create an issue on GitHub with detailed error information3764. Include system information and error logs377 378## ๐Ÿ”„ Updates379 380### UI Version History381- **v1.0.0**: Initial UI implementation with Streamlit, Dash, Jupyter, and WebSocket382- **v1.1.0**: Added real-time data streaming and advanced charts383- **v1.2.0**: Enhanced portfolio monitoring and risk management384- **v1.3.0**: Added custom strategy development tools385 386### Upcoming Features387- **v1.4.0**: Machine learning model visualization388- **v1.5.0**: Advanced backtesting interface389- **v1.6.0**: Multi-asset portfolio management390- **v1.7.0**: Social trading features