Implementation (7 files, ~2,640 lines): - AdvancedRiskManager with Tier 2-3 risk controls * Weekly rolling loss limits (7-day window, Monday rollover) * Trailing drawdown protection from peak equity * Cross-strategy exposure limits by symbol * Correlation-based position limits * Time-based trading windows * Risk mode system (Normal/Aggressive/Conservative) * Cooldown periods after violations - Optimal-f position sizing (Ralph Vince method) * Historical trade analysis * Risk of ruin calculation * Drawdown probability estimation * Dynamic leverage optimization - Volatility-adjusted position sizing * ATR-based sizing with regime detection * Standard deviation sizing * Volatility regimes (Low/Normal/High) * Dynamic size adjustment based on market conditions - OrderStateMachine for formal state management * State transition validation * State history tracking * Event logging for auditability Testing (90+ tests, >85% coverage): - 25+ advanced risk management tests - 47+ position sizing tests (optimal-f, volatility) - 18+ enhanced OMS tests - Integration tests for full flow validation - Performance benchmarks (all targets met) Documentation (140KB, ~5,500 lines): - Complete API reference (21KB) - Architecture overview (26KB) - Deployment guide (12KB) - Quick start guide (3.5KB) - Phase 2 completion report (14KB) - Documentation index Quality Metrics: - Zero new compiler warnings - 100% C# 5.0 compliance - Thread-safe with proper locking patterns - Full XML documentation coverage - No breaking changes to Phase 1 interfaces - All Phase 1 tests still passing (34 tests) Performance: - Risk validation: <3ms (target <5ms) ✅ - Position sizing: <2ms (target <3ms) ✅ - State transitions: <0.5ms (target <1ms) ✅ Phase 2 Status: ✅ COMPLETE Time: ~3 hours (vs 10-12 hours estimated manual) Ready for: Phase 3 (Market Microstructure & Execution)
12 KiB
NT8 SDK - Deployment Guide
Version: 0.2.0
Target Platform: NinjaTrader 8
Last Updated: February 15, 2026
Table of Contents
- Prerequisites
- Development Deployment
- Simulation Deployment
- Production Deployment
- Verification
- Troubleshooting
Prerequisites
System Requirements
Minimum:
- Windows 10 (64-bit)
- .NET Framework 4.8
- 8GB RAM
- NinjaTrader 8.0.20.1 or higher
Recommended:
- Windows 11 (64-bit)
- .NET Framework 4.8
- 16GB RAM
- SSD storage
- NinjaTrader 8.1.x (latest)
Software Requirements
- Visual Studio 2022 (recommended)
- Or VS Code with C# extension
- Git for version control
- NinjaTrader 8 installed and licensed
- Build Tools
- .NET Framework 4.8 SDK
- MSBuild
Development Deployment
Step 1: Build SDK
# Navigate to repository
cd C:\dev\nt8-sdk
# Clean previous builds
dotnet clean
# Build in Release mode
dotnet build --configuration Release
# Verify build
.\verify-build.bat
Expected Output:
✅ All checks passed!
Build is ready for NT8 integration
Step 2: Run Tests
# Run all tests
dotnet test --configuration Release
# Verify test results
# Expected: 90+ tests passing, 0 failures
Step 3: Copy SDK DLLs
Source Location:
src/NT8.Core/bin/Release/net48/NT8.Core.dll
src/NT8.Core/bin/Release/net48/NT8.Core.pdb
Destination:
C:\Users\[YourUsername]\Documents\NinjaTrader 8\bin\Custom\
PowerShell Copy Command:
$source = "C:\dev\nt8-sdk\src\NT8.Core\bin\Release\net48"
$dest = "$env:USERPROFILE\Documents\NinjaTrader 8\bin\Custom"
Copy-Item "$source\NT8.Core.dll" $dest -Force
Copy-Item "$source\NT8.Core.pdb" $dest -Force
# Copy dependencies
Copy-Item "$source\Microsoft.Extensions.*.dll" $dest -Force
Copy-Item "$source\Newtonsoft.Json.dll" $dest -Force
Step 4: Deploy Strategy Wrappers
Source Location:
src/NT8.Adapters/Wrappers/*.cs
Destination:
C:\Users\[YourUsername]\Documents\NinjaTrader 8\bin\Custom\Strategies\
Copy Command:
$wrapperSource = "C:\dev\nt8-sdk\src\NT8.Adapters\Wrappers"
$strategyDest = "$env:USERPROFILE\Documents\NinjaTrader 8\bin\Custom\Strategies"
Copy-Item "$wrapperSource\*.cs" $strategyDest -Force
Simulation Deployment
Step 1: Compile in NinjaTrader
- Open NinjaTrader 8
- Click Tools → NinjaScript Editor (F5)
- Wait for editor to load
- Click Compile → Compile All (F5)
- Verify: "Compilation Successful" message
If Errors:
- Check that all DLLs copied correctly
- Verify .NET Framework 4.8 installed
- See Troubleshooting
Step 2: Configure Simulation Account
- Tools → Connections
- Select Kinetick - End Of Day (free)
- Click Connect
- Verify connection status: Connected
Step 3: Create Strategy Instance
- New → Strategy
- Select your strategy (e.g., "SimpleORBNT8")
- Configure parameters:
Symbol: ES 03-26
Data Series: 5 Minute
From Template: Default
Risk Parameters:
- Stop Ticks: 8
- Target Ticks: 16
- Daily Loss Limit: $1000
- Risk Per Trade: $200
- Click Apply → OK
Step 4: Enable Strategy on Chart
- Open chart for ES 03-26 (5 minute)
- Right-click chart → Strategies
- Select your strategy
- Enabled: Check
- Calculate: On bar close
- Click OK
Step 5: Monitor Simulation
Watch For:
- Strategy loads without errors
- No log errors in Output window
- Orders appear in "Strategies" tab
- Risk controls trigger appropriately
Simulation Test Checklist:
- Strategy compiles
- Strategy enables on chart
- Orders submit correctly
- Stops placed correctly
- Targets placed correctly
- Daily loss limit triggers
- Position limits enforced
- Emergency flatten works
Run For: Minimum 1 hour live market or 1 day sim/replay
Production Deployment
⚠️ Pre-Production Checklist
CRITICAL: Complete ALL items before live trading:
- All simulation tests passed
- Strategy profitable in simulation (100+ trades)
- Risk controls tested and validated
- Drawdown limits tested
- Weekly limits tested
- Emergency flatten tested
- Connection loss recovery tested
- All edge cases handled
- Monitoring and alerting configured
- Backup plan documented
Step 1: Production Configuration
Create Production Config:
{
"Name": "Production - ES ORB",
"Version": "0.2.0",
"Environment": {
"Mode": "Live",
"DataProvider": "NinjaTrader",
"ExecutionProvider": "NinjaTrader"
},
"Strategies": [
{
"Name": "ES ORB Strategy",
"Symbol": "ES",
"Parameters": {
"StopTicks": 8,
"TargetTicks": 16,
"ORBMinutes": 30
},
"RiskSettings": {
"DailyLossLimit": 500,
"WeeklyLossLimit": 1500,
"MaxTradeRisk": 100,
"MaxOpenPositions": 1,
"TrailingDrawdownLimit": 0.10
},
"SizingSettings": {
"Method": "FixedDollarRisk",
"MinContracts": 1,
"MaxContracts": 2,
"RiskPerTrade": 100
}
}
],
"GlobalRisk": {
"MaxAccountRisk": 0.02,
"DailyLossLimit": 500,
"WeeklyLossLimit": 1500,
"MaxConcurrentTrades": 1,
"EmergencyFlattenEnabled": true,
"TradingHours": ["09:30-16:00"]
},
"Alerts": {
"EmailEnabled": true,
"EmailRecipients": ["your-email@example.com"],
"DiscordEnabled": false
}
}
Conservative First-Week Settings:
- Start with 1 contract only
- Use wider stops initially (12 ticks vs 8)
- Lower daily loss limit ($500 vs $1000)
- Enable all risk tiers
- Monitor continuously
Step 2: Connect Live Account
- Tools → Connections
- Select your broker connection
- Enter credentials
- Click Connect
- VERIFY: Real account connected (check account name)
Step 3: Enable Strategy (Cautiously)
- Open chart for exact contract (e.g., ES 03-26)
- Double-check all parameters
- Start Small: 1 contract, conservative settings
- Enable strategy
- Monitor continuously for first day
Step 4: Production Monitoring
Required Monitoring (First Week):
- Watch every trade live
- Verify order placement correct
- Check risk controls triggering
- Monitor P&L closely
- Log any anomalies
Daily Checklist:
- Review all trades
- Check risk control logs
- Verify P&L accurate
- Review any errors
- Check system health
- Backup configuration
Step 5: Gradual Scale-Up
Week 1: 1 contract, wide stops
Week 2: 1 contract, normal stops (if Week 1 successful)
Week 3: 2 contracts (if Week 2 successful)
Week 4: 2-3 contracts (if Week 3 successful)
Scale-Up Criteria:
- Profitable or break-even
- No system errors
- Risk controls working
- Comfortable with behavior
Verification
Build Verification
# Run verification script
.\verify-build.bat
# Should output:
# ✅ All checks passed!
# Build is ready for NT8 integration
Runtime Verification
Check Logs:
C:\Users\[Username]\Documents\NinjaTrader 8\log\
Look For:
- Strategy initialization messages
- No error exceptions
- Risk validation logs
- Order submission confirmations
Expected Log Entries:
[INFO] SimpleORB initialized: Stop=8, Target=16
[INFO] Risk controls active: Daily limit=$1000
[DEBUG] ORB complete: High=4205.25, Low=4198.50
[INFO] Trade approved: Risk Level=Low
[INFO] Order submitted: ES Buy 2 @ Market
[INFO] Order filled: ES 2 @ 4203.00
Health Checks
Every Hour:
- Strategy still enabled
- No error messages
- Orders executing correctly
- P&L tracking accurate
Every Day:
- Review all trades
- Check risk control logs
- Verify position reconciliation
- Backup critical data
Troubleshooting
Compilation Errors
Error: "Could not find NT8.Core.dll"
Solution: Copy DLL to NinjaTrader 8\bin\Custom\
Error: "Method not found"
Solution: Ensure DLL version matches strategy code
Error: "Could not load file or assembly"
Solution: Copy all dependencies (Microsoft.Extensions.*, Newtonsoft.Json)
Runtime Errors
Error: "NullReferenceException in OnBarUpdate"
Solution: Add null checks:
if (CurrentBar < 1) return;
if (Instrument == null) return;
Error: "Order rejected by broker"
Solution:
- Check account margin
- Verify contract is valid
- Check trading hours
Error: "Risk manager halted trading"
Solution:
- Check daily loss limit
- Review risk logs
- Reset daily limits (if appropriate)
Performance Issues
Symptom: Strategy lagging behind market
Diagnosis:
var sw = Stopwatch.StartNew();
// ... strategy logic
sw.Stop();
_logger.LogDebug("OnBar execution: {0}ms", sw.ElapsedMilliseconds);
Solutions:
- Optimize calculations
- Reduce logging in production
- Check for excessive LINQ
- Profile hot paths
Connection Issues
Symptom: Orders not submitting
Check:
- Connection status
- Account status
- Symbol validity
- Market hours
Recovery:
- Reconnect data feed
- Disable/re-enable strategy
- Emergency flatten if needed
Rollback Procedure
If Issues in Production
- Immediate: Disable strategy
- Flatten: Close all open positions
- Disconnect: From live account
- Investigate: Review logs
- Fix: Address issue
- Re-test: On simulation
- Deploy: Only when confident
Version Rollback
Save Previous Version:
# Before deployment
Copy-Item "NT8.Core.dll" "NT8.Core.dll.backup"
Restore Previous Version:
# If issues
Copy-Item "NT8.Core.dll.backup" "NT8.Core.dll" -Force
Re-compile in NT8
Best Practices
Pre-Deployment
- Always test on simulation first
- Run for minimum 100 trades
- Test all risk control scenarios
- Verify edge case handling
- Document expected behavior
During Deployment
- Deploy outside market hours
- Start with minimal position size
- Monitor continuously first day
- Have emergency procedures ready
- Keep broker support number handy
Post-Deployment
- Review daily performance
- Monitor risk control logs
- Track any anomalies
- Maintain configuration backups
- Document lessons learned
Production Operations
- Never modify code during market hours
- Always test changes on simulation
- Document all configuration changes
- Backup before every deployment
- Monitor continuously
Emergency Procedures
Emergency Flatten
Via Code:
await _riskManager.EmergencyFlatten("Manual intervention");
Via NT8:
- Click "Flatten Everything"
- Or right-click strategy → "Disable"
- Manually close positions if needed
System Halt
If Critical Issue:
- Disable all strategies immediately
- Flatten all positions
- Disconnect from broker
- Investigate offline
- Do not re-enable until resolved
Data Backup
Daily Backup:
# Backup configuration
$date = Get-Date -Format "yyyyMMdd"
Copy-Item "config.json" "config_$date.json"
# Backup logs
Copy-Item "logs\*" "backup\logs_$date\" -Recurse
Support
Internal Support
- Documentation:
/docsdirectory - Examples:
/src/NT8.Strategies/Examples/ - Tests:
/testsdirectory
External Support
- NinjaTrader: support.ninjatrader.com
- Community: Forum, Discord
Reporting Issues
- Collect error logs
- Document reproduction steps
- Include configuration
- Note market conditions
- Create detailed issue report
Remember: Test thoroughly, start small, monitor continuously ✅