execution-modes.md
1 # Execution Modes Guide 2 3 4 5 This comprehensive guide covers Planar's three execution modes and how to safely transition between them. Learn how to develop [strategies](../guides/strategy-development.md) in [simulation](../guides/execution-modes.md#simulation-mode), validate them in paper mode, and deploy them for [live trading](../guides/execution-modes.md#live-mode) with proper risk management. 6 7 ## Quick Navigation 8 9 - **[Mode Overview](#Mode-Overview)** - Understanding the three execution modes 10 - **[Simulation Mode](#Simulation-Mode)** - Backtesting with historical data 11 - **[Paper Mode](#Paper-Mode)** - Real-time simulation without capital risk 12 - **[Live Mode](#Live-Mode)** - Real trading with actual capital 13 - **[Mode Transitions](#Mode-Transitions)** - Safe progression between modes 14 - **[Best Practices](#Best-Practices)** - Guidelines for each mode 15 - **[troubleshooting](../troubleshooting/index.md)** - Common issues and solutions 16 17 ## Prerequisites 18 19 - Completed the [Getting Started Guide](../getting-started/index.md) 20 - Basic understanding of [Strategy Development](strategy-development.md)) 21 - Familiarity with [Data Management](../guides/data-management.md) 22 23 ## Related Topics 24 25 - **[Strategy Development](strategy-development.md))** - Building trading [strategies](../guides/strategy-development.md) 26 - **[Risk Management](../advanced/risk-management.md)** - Managing trading risks 27 - **[optimization](../optimization.md)** - Parameter tuning and [backtesting](../guides/execution-modes.md#simulation-mode) 28 29 ## Mode Overview 30 31 Planar supports three distinct execution modes, each designed for different stages of [strategy](../guides/strategy-development.md) development and deployment: 32 33 ### Mode Comparison Matrix 34 35 | Feature | Sim Mode | Paper Mode | Live Mode | 36 |---------|----------|------------|-----------| 37 | **Data Source** | Historical | Live Market Data | Live Market Data | 38 | **Order Execution** | Simulated | Simulated | Real Exchange API | 39 | **Capital Risk** | None | None | Real Money | 40 | **Market Impact** | None | None | Real | 41 | **Latency** | None | Real Network | Real Network + Exchange | 42 | **Slippage** | Modeled | Modeled from Order Book | Real Market Slippage | 43 | **Fees** | Modeled | Modeled | Real Exchange Fees | 44 | **Order Book** | Historical/Modeled | Real-time | Real-time | 45 | **Speed** | Very Fast | Real-time | Real-time | 46 | **API Limits** | None | Rate Limited | Rate Limited | 47 | **Funding Costs** | Modeled | Modeled | Real | 48 49 ### Development Workflow 50 51 The recommended development workflow follows a systematic progression through all three modes: 52 53 ```mermaid 54 graph TD 55 A[Strategy Idea] --> B[Sim Mode Development] 56 B --> C[Parameter Optimization] 57 C --> D[Historical Validation] 58 D --> E{Results Satisfactory?} 59 E -->|No| B 60 E -->|Yes| F[Paper Mode Testing] 61 F --> G[Real-time Validation] 62 G --> H[Market Condition Testing] 63 H --> I{Paper Results Good?} 64 I -->|No| J[Refine Strategy] 65 J --> B 66 I -->|Yes| K[Live Mode Preparation] 67 K --> L[Small Capital Test] 68 L --> M[Gradual Scale-up] 69 M --> N[Full Deployment] 70 ``` 71 72 ## Simulation Mode 73 74 Simulation mode (Sim) is designed for strategy development and [backtesting](../guides/execution-modes.md#simulation-mode) using historical data. It provides fast execution with no capital risk, making it ideal for initial development and [optimization](../optimization.md). 75 76 ### Basic Sim Mode Setup 77 78 79 ### Advanced Sim Configuration 80 81 82 ### Sim Mode Features 83 84 #### Realistic Order Execution 85 86 87 #### Performance Optimization 88 89 90 #### Walk-Forward Analysis 91 92 93 ### Sim Mode Best Practices 94 95 1. **Avoid Overfitting**: Use out-of-sample testing and walk-forward analysis 96 2. **Model Reality**: Include realistic slippage, fees, and execution delays 97 3. **Validate Assumptions**: Test across different market conditions 98 4. **Performance Monitoring**: Track key metrics throughout development 99 100 ## Paper Mode 101 102 Paper mode provides real-time simulation using live [market data](../guides/data-management.md) without risking actual capital. It's essential for validating strategies with current market conditions before live deployment. 103 104 ### Basic Paper Mode Setup 105 106 107 ### Advanced Paper Configuration 108 109 110 ### Paper Mode Features 111 112 #### Real-Time Order Execution 113 114 ```julia 115 # Activate Planar project 116 import Pkg 117 Pkg.activate("Planar") 118 119 try 120 using Planar 121 using Dates 122 @environment! 123 124 # Define order side constants for the example 125 @enum OrderSide Buy Sell 126 127 # Helper functions for paper mode execution (implement based on your system) 128 function get_order_book(ai) 129 # Placeholder - replace with actual order book retrieval 130 return (bids = [(50000.0, 1.0), (49999.0, 2.0)], asks = [(50001.0, 1.0), (50002.0, 2.0)]) 131 end 132 133 function sweep_asks(order_book, amount) 134 # Placeholder implementation 135 return (50001.0, min(amount, 1.0)) # (price, filled_amount) 136 end 137 138 function sweep_bids(order_book, amount) 139 # Placeholder implementation 140 return (50000.0, min(amount, 1.0)) # (price, filled_amount) 141 end 142 143 # Market orders use real order book data 144 function execute_market_order_paper(s, ai, side, amount) 145 # Get current order book 146 order_book = get_order_book(ai) 147 148 # Calculate execution based on available liquidity 149 if side == Buy 150 execution_price, filled_amount = sweep_asks(order_book, amount) 151 else 152 execution_price, filled_amount = sweep_bids(order_book, amount) 153 end 154 155 # Execute with realistic slippage (example implementation) 156 @info "Paper trade executed: $side $filled_amount at $execution_price" 157 158 return (price = execution_price, amount = filled_amount, timestamp = now()) 159 end 160 161 println("Paper trading functions defined successfully") 162 163 catch e 164 @warn "Planar not available: $e" 165 end 166 ``` 167 168 #### Live Data Integration 169 170 ```julia 171 # Activate Planar project 172 import Pkg 173 Pkg.activate("Planar") 174 175 try 176 using Planar 177 @environment! 178 179 # Helper functions for live monitoring (implement based on your system) 180 function isrunning(s) 181 return true # Placeholder - replace with actual strategy status check 182 end 183 184 function get_live_price(ai) 185 return 50000.0 + rand() * 1000 # Placeholder live price 186 end 187 188 function update_strategy_price!(s, ai, price) 189 @info "Updated price for $(ai.symbol): $price" 190 end 191 192 function analyze_order_book(ai) 193 return (spread_pct = rand() * 0.5, depth = rand() * 100) # Placeholder analysis 194 end 195 196 # Set up real-time data monitoring 197 function setup_live_monitoring(s) 198 @async begin 199 while isrunning(s) 200 # Example universe iteration (in real usage, s.universe would be defined) 201 example_symbols = ["BTC/USDT", "ETH/USDT"] 202 203 for symbol in example_symbols 204 # Update live prices 205 current_price = get_live_price(symbol) 206 @info "Updated price for $symbol: $current_price" 207 208 # Monitor order book changes 209 book_analysis = analyze_order_book(symbol) 210 if book_analysis.spread_pct > 0.2 # Wide spread alert 211 @warn "Wide spread detected for $symbol: $(book_analysis.spread_pct)%" 212 end 213 end 214 sleep(1) # Update every second 215 end 216 end 217 end 218 219 println("Live monitoring functions defined successfully") 220 221 catch e 222 @warn "Planar not available: $e" 223 end 224 ``` 225 226 #### Performance Tracking 227 228 229 ### Paper Mode Best Practices 230 231 1. **Conservative Sizing**: Use smaller position sizes than in simulation 232 2. **Monitor Spreads**: Watch for wide spreads that affect execution 233 3. **Test Market Conditions**: Run during different market volatility periods 234 4. **Validate Timing**: Ensure strategy works with real-time data delays 235 236 ## Live Mode 237 238 Live mode executes real trades with actual capital using [exchanges](../exchanges.md) APIs. This mode requires careful setup, comprehensive risk management, and continuous monitoring. 239 240 ### Basic Live Mode Setup 241 242 243 ### Advanced Live Configuration 244 245 246 ### Live Mode Features 247 248 #### Real-Time Risk Management 249 250 251 #### Emergency Procedures 252 253 254 #### Event Tracing and Analysis 255 256 257 ### Live Mode Best Practices 258 259 1. **Start Small**: Begin with minimal capital and position sizes 260 2. **Monitor Continuously**: Set up comprehensive monitoring and alerts 261 3. **Test Thoroughly**: Use sandbox mode extensively before going live 262 4. **Risk Management**: Implement multiple layers of risk controls 263 5. **Emergency Procedures**: Have clear emergency stop procedures 264 265 ## Mode Transitions 266 267 Safe transition between modes is crucial for successful strategy deployment. Each transition requires validation and configuration adjustments. 268 269 ### Sim to Paper Transition 270 271 #### Pre-transition Validation 272 273 274 #### Configuration Adjustments 275 276 277 ### Paper to Live Transition 278 279 #### Comprehensive Validation 280 281 282 #### Live Mode Preparation 283 284 285 ### Gradual Deployment Strategy 286 287 ```julia 288 # Activate Planar project 289 import Pkg 290 Pkg.activate("Planar") 291 292 try 293 using Planar 294 @environment! 295 296 # Helper functions for deployment (implement based on your system) 297 function check_milestone(s, milestone) 298 # Placeholder - implement actual milestone checking 299 return rand() > 0.8 # Random success for example 300 end 301 302 function add_capital!(s, amount) 303 @info "Adding $amount to strategy capital" 304 end 305 306 function send_alert(s, message) 307 @info "Alert: $message" 308 end 309 310 # Implement gradual capital deployment 311 function implement_gradual_deployment(s, total_capital, deployment_schedule) 312 current_deployment = 0.0 313 314 for (milestone, capital_pct) in deployment_schedule 315 # Wait for milestone achievement 316 while !check_milestone(s, milestone) 317 sleep(3600) # Check every hour 318 end 319 320 # Increase capital allocation 321 new_deployment = total_capital * capital_pct 322 additional_capital = new_deployment - current_deployment 323 324 if additional_capital > 0 325 add_capital!(s, additional_capital) 326 current_deployment = new_deployment 327 328 @info "Capital deployment milestone reached" milestone capital_pct current_deployment 329 send_alert(s, "Deployed $(round(capital_pct*100))% of capital ($current_deployment USDT)") 330 end 331 end 332 end 333 334 # Example deployment schedule 335 deployment_schedule = [ 336 (:first_week_profitable, 0.1), # 10% after first profitable week 337 (:month_positive, 0.25), # 25% after first profitable month 338 (:three_months_stable, 0.5), # 50% after three stable months 339 (:six_months_proven, 1.0) # 100% after six months of success 340 ] 341 342 println("Gradual deployment functions defined successfully") 343 344 catch e 345 @warn "Planar not available: $e" 346 end 347 ``` 348 349 ## Best Practices 350 351 ### Development Workflow 352 353 1. **Start in Sim Mode**: Develop and optimize strategies using historical data 354 2. **Validate Thoroughly**: Use walk-forward analysis and out-of-sample testing 355 3. **Test in Paper Mode**: Validate with real market conditions for at least 30 days 356 4. **Deploy Gradually**: Start live trading with small capital and scale up slowly 357 5. **Monitor Continuously**: Implement comprehensive monitoring and alerting 358 359 ### Risk Management 360 361 1. **Position Sizing**: Use conservative position sizes, especially when transitioning 362 2. **Stop Losses**: Implement multiple layers of stop-loss protection 363 3. **Diversification**: Avoid concentration in correlated assets 364 4. **Capital Limits**: Set strict daily and total loss limits 365 5. **Emergency Procedures**: Have clear emergency stop procedures 366 367 ### Configuration Management 368 369 370 ## Troubleshooting 371 372 ### Common Issues by Mode 373 374 #### Sim Mode Issues 375 376 **Problem**: Strategy works perfectly in simulation but fails in paper mode 377 **Solution**: 378 - Add realistic slippage and execution delays 379 - Use out-of-sample testing 380 - Implement proper risk management 381 382 **Problem**: Slow [backtest](../guides/execution-modes.md#simulation-mode) performance 383 **Solution**: 384 - Enable parallel processing 385 - Use data chunking 386 - Optimize strategy logic 387 388 #### Paper Mode Issues 389 390 **Problem**: Orders not filling as expected 391 **Solution**: 392 - Check order book depth 393 - Adjust limit order prices 394 - Consider using market orders for urgent trades 395 396 **Problem**: Performance differs significantly from simulation 397 **Solution**: 398 - Analyze execution quality 399 - Check for wide spreads 400 - Validate market impact assumptions 401 402 #### Live Mode Issues 403 404 **Problem**: API connection failures 405 **Solution**: 406 - Implement connection resilience 407 - Use proper timeout settings 408 - Set up reconnection logic 409 410 **Problem**: Unexpected losses 411 **Solution**: 412 - Review risk management settings 413 - Check for slippage and fees 414 - Analyze execution quality 415 416 ### Debugging Tools 417 418 419 This comprehensive execution modes guide provides everything you need to safely develop, test, and deploy trading strategies across all three modes. Start with simulation for development, validate in paper mode, and deploy to live trading with proper risk management and monitoring.