Lean · 第 4 章 QCAlgorithm 用户 API 章节摘要:本章钻取第 4 层——用户 API 层 QCAlgorithm。这是用户写算法唯一需要接触的门面(Facade)。QCAlgorithm 用 partial class 拆成 9 个文件(主类 + History/Indicators/Trading/Universe/Plotting/Framework/Python/Framework.Python),继承 MarshalByRefObject(跨 AppDomain 隔离用户 DLL)+ IAlgorithm(引擎契约)。用户只需 override Initialize()(配置回测)和 OnData(Slice)(策略逻辑)。
章节摘要:本章钻取第 4 层——用户 API 层 QCAlgorithm。这是用户写算法唯一需要接触的门面(Facade)。QCAlgorithm 用 partial class 拆成 9 个文件(主类 + History/Indicators/Trading/Universe/Plotting/Framework/Python/Framework.Python),继承 MarshalByRefObject(跨 AppDomain 隔离用户 DLL)+ IAlgorithm(引擎契约)。用户只需 override Initialize()(配置回测)和 OnData(Slice)(策略逻辑)。本章用 BasicTemplateAlgorithm 最简示例(C#+Python 对照)展示用户视角,然后逐 partial 文件讲清各能力。本章共 3 节,前置依赖为第 1-3 章。
本章钻取"用户API层"——用户继承 QCAlgorithm 写策略。
阅读完本章,你应当能够:
QCAlgorithm : MarshalByRefObject, IAlgorithm;partial 9文件(主类字段/Initialize/状态/消息队列 + History + Indicators + Trading + Universe + Plotting + Framework + Python + Framework.Python);_locked 锁定(Initialize后禁AddSecurity);MarshalByRefObject跨AppDomain(用户DLL隔离可卸载);DocumentationAttribute 15+分类自动生成API文档。
C#版(_spy Symbol预定义/Initialize设日期资金AddEquity/OnData if !Portfolio.Invested SetHoldings满仓/IRegressionAlgorithmDefinition回归测试元数据ExpectedStatistics);Python版对照(同样Initialize/OnData,.py文件algorithm-language=Python);SetHoldings(symbol,weight)百分比再平衡高层API;用户只需override两方法其余交框架。
Trading(SetHoldings/Order/MarketOrder/LimitOrder/StopMarketOrder/Liquidate);Universe(AddEquity/AddForex/AddOption/AddFuture/AddCrypto/AddSecurity);History(History多重载/GetLastKnownPrices/WarmUpIndicator预热);Indicators(SMA/EMA/RSI/MACD/Bollinger简写工厂自动管理预热);Plotting(Plot/AddChart)。
前置知识:第 1-3 章;C# 基础。
后续延伸:第 5 章钻取 OnData 收到的 Slice 数据怎么来(数据流层)。