title: Chapter 13: Live Trading Preparation¶
Chapter 13: Live Trading Preparation¶
This chapter covers the preparation work before live trading, including brokerage integration, account configuration, and risk management.
13.1 Live Trading Overview¶
13.1.1 Differences Between Backtesting and Live Trading¶
| Aspect | Backtesting | Live Trading |
|---|---|---|
| Data | Historical data, deterministic | Real-time data, uncertain |
| Slippage | Model estimate | Real slippage |
| Fills | Assumed to fill | May not fill |
| Latency | No latency | Network latency |
| Psychology | No emotional impact | Psychology affects decisions |
| Costs | Simplified fees | Actual fees |
| Time | Completes in seconds | Unfolds in real time |
13.1.2 Pre-Live Checklist¶
- [ ] Strategy has been thoroughly backtested
- [ ] Parameters validated out-of-sample
- [ ] Brokerage API and its limits understood
- [ ] Risk management rules set up
- [ ] Monitoring plan prepared
- [ ] Alert notifications configured
- [ ] Paper trading tested
13.2 Brokerage Integration¶
13.2.1 Supported Brokerages¶
Equity/ETF brokerages: - Interactive Brokers - international broker with global market access - Tradier - US stocks and options - Alpaca / TradeStation / Charles Schwab / Tastytrade and others
Cryptocurrency exchanges:
- Coinbase (GDAX is its old name; Market.GDAX is marked obsolete)
- Bitfinex
- Binance
- Kraken
- Bybit
Forex brokerages: - OANDA - FXCM
Other supported brokerages include Trading Technologies, Zerodha, Samco, and Exante; see the
environmentsconfiguration block in the engine'sLauncher/config.jsonfor the complete list.
13.2.2 Interactive Brokers Configuration¶
Installing IB Gateway¶
- Download IB Gateway or TWS
- Enable the ActiveX/Socket client
- Configure the API port (corresponds to
ib-portin config.json, default 4002) - Create a trading account
Configuration File¶
{
"live-mode": true,
"live-mode-brokerage": "InteractiveBrokersBrokerage",
// IB 账户信息使用扁平键(见 Launcher/config.json)
"ib-account": "DU1234567",
"ib-host": "127.0.0.1",
"ib-port": "4002",
"ib-password": "your_password",
// 任务队列处理器为类名字符串
"job-queue-handler": "QuantConnect.Queues.JobQueue"
}
13.2.3 Cryptocurrency Exchange Configuration¶
Bitfinex Configuration¶
{
"live-mode": true,
"live-mode-brokerage": "BitfinexBrokerage",
"bitfinex-api-key": "your_api_key",
"bitfinex-api-secret": "your_api_secret",
"job-queue-handler": "QuantConnect.Queues.JobQueue"
}
Binance Configuration¶
{
"live-mode": true,
"live-mode-brokerage": "BinanceBrokerage",
"binance-api-key": "your_api_key",
"binance-api-secret": "your_api_secret"
}
13.2.4 Paper Trading Configuration¶
Use Paper Brokerage for simulated trading:
{
"live-mode": true,
"live-mode-brokerage": "PaperBrokerage"
}
13.3 Live Risk Management¶
13.3.1 Basic Risk Rules¶
class RiskManagedLiveStrategy(QCAlgorithm):
"""
带风险管理的实盘策略
"""
def Initialize(self):
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
# 风险参数
self.max_position_size = 0.2 # 单个仓位最大20%
self.max_total_exposure = 0.8 # 总持仓最大80%
self.max_daily_loss = 0.02 # 日最大亏损2%
self.max_drawdown = 0.10 # 最大回撤10%
self.daily_start_value = None
self.peak_value = None
# 调度:每日检查风险
self.Schedule.On(
self.DateRules.EveryDay(),
self.TimeRules.BeforeMarketOpen(self.spy, 5),
self.DailyRiskCheck
)
def DailyRiskCheck(self):
"""每日风险检查"""
# 重置每日起始值
self.daily_start_value = self.Portfolio.TotalPortfolioValue
def CheckRiskLimits(self):
"""检查风险限制"""
current_value = self.Portfolio.TotalPortfolioValue
# 更新峰值
if self.peak_value is None or current_value > self.peak_value:
self.peak_value = current_value
# 检查每日亏损
if self.daily_start_value:
daily_pnl = (current_value / self.daily_start_value - 1)
if daily_pnl < -self.max_daily_loss:
self.Error(f"Daily loss limit exceeded: {daily_pnl:.2%}")
self.Liquidate()
return False
# 检查最大回撤
if self.peak_value:
drawdown = (current_value / self.peak_value - 1)
if drawdown < -self.max_drawdown:
self.Error(f"Max drawdown exceeded: {drawdown:.2%}")
self.Liquidate()
return False
return True
def OnData(self, data):
# 在每次交易前检查风险
if not self.CheckRiskLimits():
return
# 正常交易逻辑
# ...
13.3.2 Position Sizing¶
def CalculatePositionSize(self, symbol, risk_per_trade=0.02):
"""
计算基于风险的仓位大小
Args:
symbol: 证券Symbol
risk_per_trade: 每笔交易风险比例
"""
# 获取账户总值
portfolio_value = self.Portfolio.TotalPortfolioValue
# 计算风险金额
risk_amount = portfolio_value * risk_per_trade
# 获取当前价格和ATR
price = self.Securities[symbol].Price
atr = self.ATR(symbol, 14).Current.Value if self.ATR(symbol, 14).IsReady else price * 0.02
# 基于ATR的止损距离
stop_distance = atr * 2
# 计算股数
if stop_distance > 0:
shares = int(risk_amount / stop_distance)
else:
shares = 0
# 检查最大仓位限制
position_value = shares * price
max_position_value = portfolio_value * self.max_position_size
if position_value > max_position_value:
shares = int(max_position_value / price)
return shares
13.4 Pre-Live Testing¶
13.4.1 Paper Trading Test¶
class PaperTradingTest(QCAlgorithm):
"""
模拟盘测试策略
在实盘前,先用模拟盘测试策略
"""
def Initialize(self):
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
# 模拟盘模式标识
self.is_paper_trading = True
def OnData(self, data):
if self.is_paper_trading:
# 模拟盘模式:记录但不实际交易
self.Debug(f"[PAPER] Signal at {self.Time}")
return
# 实盘模式
self.ExecuteTrade()
13.4.2 Pre-Live Verification¶
# 1. 连接测试(模拟盘使用 Paper Trading 券商)
lean live deploy "MyStrategy" --brokerage "Paper Trading"
# 2. 检查订单
# 观察订单是否正常生成和执行
# 3. 检查持仓
# 确认持仓正确记录
# 4. 检查收益
# 确认收益计算正确
# 5. 测试异常情况
# 断开连接、重启等
13.5 Monitoring and Alerts¶
13.5.1 Setting Up Monitoring¶
class MonitoredLiveStrategy(QCAlgorithm):
"""
带监控的实盘策略
"""
def Initialize(self):
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
# 监控变量
self.last_log_time = self.Time
self.log_interval = timedelta(hours=1)
# 告警阈值
self.alert_low_balance = 10000 # 低于1万美元告警
self.alert_large_loss = 0.05 # 单笔亏损超过5%告警
def LogStatus(self):
"""记录当前状态"""
now = self.Time
if (now - self.last_log_time) >= self.log_interval:
portfolio = self.Portfolio
self.Debug(f"[STATUS] {now}")
self.Debug(f" Portfolio Value: ${portfolio.TotalPortfolioValue:,.2f}")
self.Debug(f" Cash: ${portfolio.Cash:,.2f}")
self.Debug(f" Invested: {portfolio.Invested}")
# 检查低余额告警
if portfolio.Cash < self.alert_low_balance:
self.Log(f"Low balance alert: ${portfolio.Cash:,.2f}")
self.last_log_time = now
def OnOrderEvent(self, orderEvent):
"""订单事件监控"""
if orderEvent.Status == OrderStatus.Filled:
fill_price = orderEvent.FillPrice
# 检查大额亏损(OrderEvent 直接提供 Direction/Symbol 等成员)
if orderEvent.Direction == OrderDirection.Sell:
holdings = self.Portfolio[orderEvent.Symbol]
if holdings.AveragePrice > 0:
pnl_pct = (fill_price / holdings.AveragePrice - 1)
if pnl_pct < -self.alert_large_loss:
self.Error(f"Large loss alert: {orderEvent.Symbol} | P&L: {pnl_pct:.2%}")
def OnData(self, data):
# 记录状态
self.LogStatus()
# 正常交易逻辑
# ...
13.5.2 Notification Setup¶
class NotificationStrategy(QCAlgorithm):
"""
带通知的策略
"""
def Initialize(self):
# ...
# Notify 是 NotificationManager 实例,直接调用 Email/Sms/Web 方法发送,
# 没有 NotificationType 配置结构;这里只保存通知地址
self.alert_email = "your_email@example.com"
self.alert_webhook_url = "https://your-webhook-url.com/alert"
def SendAlert(self, message, level="info"):
"""
发送告警
Args:
message: 告警消息
level: 告警级别 (info, warning, error)
"""
# 记录日志(QCAlgorithm 没有 Warn 方法,警告语义用 Log)
if level == "error":
self.Error(f"[ALERT] {message}")
else:
self.Log(f"[ALERT] {message}")
# 发送邮件通知(地址, 主题, 内容)
self.Notify.Email(self.alert_email, "Strategy Alert", message)
# 发送 webhook(地址, 数据)
payload = {"message": message, "level": level}
self.Notify.Web(self.alert_webhook_url, payload)
13.6 Final Pre-Live Checks¶
13.6.1 Technical Checks¶
- [ ] Brokerage API connection working
- [ ] Data feed available
- [ ] Network connection stable
- [ ] Server clock synchronized
- [ ] Sufficient disk space
13.6.2 Strategy Checks¶
- [ ] Strategy parameters confirmed
- [ ] Risk parameters set
- [ ] Stop-loss and take-profit configured
- [ ] Maximum position limits in place
13.6.3 Capital Checks¶
- [ ] Minimum capital requirement met
- [ ] Buffer capital reserved
- [ ] Fee budget
- [ ] Sufficient margin
13.7 Complete Example: A Live-Ready Strategy¶
from AlgorithmImports import *
class LiveReadyStrategy(QCAlgorithm):
"""
实盘准备就绪的策略
包含完整的风险管理和监控
"""
def Initialize(self):
# 基本设置
self.SetStartDate(2023, 1, 1)
self.SetEndDate(2023, 12, 31)
self.SetCash(100000)
# Portfolio 没有 StartingCash 属性,在此保存初始资金
self.starting_cash = self.Portfolio.TotalPortfolioValue
# 添加证券
self.spy = self.AddEquity("SPY", Resolution.Minute).Symbol
# 数据设置
self.Securities[self.spy].SetDataNormalizationMode(
DataNormalizationMode.Adjusted
)
# 指标
self.sma_fast = self.SMA(self.spy, 20)
self.sma_slow = self.SMA(self.spy, 50)
self.atr = self.ATR(self.spy, 14)
self.SetWarmUp(TimeSpan.FromDays(60))
# ========== 风险参数 ==========
self.max_position_size = 0.2 # 最大单仓位20%
self.stop_loss_pct = 0.03 # 3% 止损
self.take_profit_pct = 0.06 # 6% 止盈
self.max_daily_loss = 0.02 # 日最大亏损2%
self.max_drawdown = 0.10 # 最大回撤10%
# 状态变量
self.entry_price = None
self.daily_start_value = None
self.peak_value = None
self.last_log_time = None
# 调度任务
self.Schedule.On(
self.DateRules.EveryDay(self.spy),
self.TimeRules.BeforeMarketOpen(self.spy, 5),
self.DailyInitialize
)
self.Schedule.On(
self.DateRules.EveryDay(self.spy),
self.TimeRules.Every(TimeSpan.FromHours(1)),
self.HourlyStatus
)
self.Debug("Live Ready Strategy Initialized")
self.Debug(f"Risk Parameters: MaxPos={self.max_position_size}, "
f"StopLoss={self.stop_loss_pct}, TakeProfit={self.take_profit_pct}")
def DailyInitialize(self):
"""每日初始化"""
self.daily_start_value = self.Portfolio.TotalPortfolioValue
self.Debug(f"\n=== Trading Day: {self.Time.date()} ===")
self.Debug(f"Starting Value: ${self.daily_start_value:,.2f}")
def HourlyStatus(self):
"""每小时状态检查"""
if not self.CheckRiskLimits():
return
portfolio = self.Portfolio
self.Debug(f"[{self.Time.strftime('%H:%M')}] Portfolio: ${portfolio.TotalPortfolioValue:,.2f}, "
f"Cash: ${portfolio.Cash:,.2f}")
def CheckRiskLimits(self):
"""检查风险限制"""
current_value = self.Portfolio.TotalPortfolioValue
# 更新峰值
if self.peak_value is None or current_value > self.peak_value:
self.peak_value = current_value
# 检查每日亏损
if self.daily_start_value:
daily_pnl = (current_value / self.daily_start_value - 1)
if daily_pnl < -self.max_daily_loss:
self.Error(f"Daily loss limit: {daily_pnl:.2%}. Liquidating.")
self.Liquidate()
return False
# 检查最大回撤
if self.peak_value:
drawdown = (current_value / self.peak_value - 1)
if drawdown < -self.max_drawdown:
self.Error(f"Max drawdown: {drawdown:.2%}. Liquidating.")
self.Liquidate()
return False
return True
def OnData(self, data):
# 风险检查
if not self.CheckRiskLimits():
return
# 检查止损止盈
if self.Portfolio[self.spy].Invested:
if self.CheckExitSignals(data[self.spy].Price):
return
# 交易逻辑
if self.sma_fast.IsReady and self.atr.IsReady:
if self.sma_fast.Current.Value > self.sma_slow.Current.Value:
if not self.Portfolio[self.spy].IsLong:
self.EnterPosition()
else:
if self.Portfolio[self.spy].IsLong:
self.ExitPosition("Signal Change")
def EnterPosition(self):
"""开仓"""
price = self.Securities[self.spy].Price
# 计算仓位大小(基于风险)
atr = self.atr.Current.Value
risk_amount = self.Portfolio.TotalPortfolioValue * 0.02 # 2% 风险
stop_distance = atr * 2
if stop_distance > 0:
shares = int(risk_amount / stop_distance)
else:
shares = int((self.Portfolio.Cash * 0.9) / price)
# 限制最大仓位
max_shares = int((self.Portfolio.TotalPortfolioValue * self.max_position_size) / price)
shares = min(shares, max_shares)
if shares > 0:
self.MarketOrder(self.spy, shares)
self.entry_price = price
self.Debug(f"[ENTER] Bought {shares} shares at ${price:.2f}")
def CheckExitSignals(self, price):
"""检查退出信号"""
if self.entry_price is None:
return False
# 止损
pnl = (price / self.entry_price - 1)
if pnl <= -self.stop_loss_pct:
self.ExitPosition("Stop Loss")
return True
# 止盈
elif pnl >= self.take_profit_pct:
self.ExitPosition("Take Profit")
return True
return False
def ExitPosition(self, reason=""):
"""平仓"""
if self.Portfolio[self.spy].Invested:
price = self.Securities[self.spy].Price
pnl = (price / self.entry_price - 1) * 100 if self.entry_price else 0
self.Liquidate(self.spy)
self.Debug(f"[EXIT] {reason} at ${price:.2f}, P&L: {pnl:.2f}")
self.entry_price = None
def OnOrderEvent(self, orderEvent):
"""订单事件"""
if orderEvent.Status == OrderStatus.Filled:
self.Debug(f"[ORDER] {orderEvent.Symbol} | "
f"Qty: {orderEvent.FillQuantity} | "
f"Price: ${orderEvent.FillPrice:.2f}")
def OnEndOfAlgorithm(self):
"""结束时总结"""
self.Debug("\n" + "="*60)
self.Debug("LIVE READY STRATEGY - SUMMARY")
self.Debug("="*60)
final_return = self.Portfolio.TotalPortfolioValue / self.starting_cash - 1
self.Debug(f"Final Return: {final_return:.2%}")
self.Debug("="*60)