开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

boxigg/Lean

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (15)
标签 (4153)
master
copilot/find-syntax-test-issue
dynamic-cache-mock-20230220
bug-milk-class-3-future-options-expiration
bug-buying-power-model-convergence
ccxt-pro-integration
feature-ib-fa-groups
feature-python-dataframe-performance-2
feature-notebook-engine
bug-4764-option-auto-exercise-early-market-close-regression-algorithm
equity-taq-wip
performance-nary-tree-synchronizer
feature-optimize-python-load
feature-1093-vwap-order-type
desktop-mk-ii
17757
17758
17755
17756
17752
17753
17754
17749
17750
17751
17746
17747
17748
17735
17736
17737
17738
17739
17740
17741
master
分支 (15)
标签 (4153)
master
copilot/find-syntax-test-issue
dynamic-cache-mock-20230220
bug-milk-class-3-future-options-expiration
bug-buying-power-model-convergence
ccxt-pro-integration
feature-ib-fa-groups
feature-python-dataframe-performance-2
feature-notebook-engine
bug-4764-option-auto-exercise-early-market-close-regression-algorithm
equity-taq-wip
performance-nary-tree-synchronizer
feature-optimize-python-load
feature-1093-vwap-order-type
desktop-mk-ii
17757
17758
17755
17756
17752
17753
17754
17749
17750
17751
17746
17747
17748
17735
17736
17737
17738
17739
17740
17741
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (15)
标签 (4153)
master
copilot/find-syntax-test-issue
dynamic-cache-mock-20230220
bug-milk-class-3-future-options-expiration
bug-buying-power-model-convergence
ccxt-pro-integration
feature-ib-fa-groups
feature-python-dataframe-performance-2
feature-notebook-engine
bug-4764-option-auto-exercise-early-market-close-regression-algorithm
equity-taq-wip
performance-nary-tree-synchronizer
feature-optimize-python-load
feature-1093-vwap-order-type
desktop-mk-ii
17757
17758
17755
17756
17752
17753
17754
17749
17750
17751
17746
17747
17748
17735
17736
17737
17738
17739
17740
17741
Lean
/
Algorithm.Python
/
ComboOrderTicketDemoAlgorithm.py
Lean
/
Algorithm.Python
/
ComboOrderTicketDemoAlgorithm.py
ComboOrderTicketDemoAlgorithm.py 10.63 KB
一键复制 编辑 原始数据 按行查看 历史
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
from AlgorithmImports import *
### <summary>
### Algorithm for testing submit/update/cancel for combo orders
### </summary>
class ComboOrderTicketDemoAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2015, 12, 24)
self.set_end_date(2015, 12, 24)
self.set_cash(100000)
equity = self.add_equity("GOOG", leverage=4, fill_forward=True)
option = self.add_option(equity.symbol, fill_forward=True)
self._option_symbol = option.symbol
option.set_filter(lambda u: u.standards_only().strikes(-2, +2).expiration(0, 180))
self._open_market_orders = []
self._open_leg_limit_orders = []
self._open_limit_orders = []
self._order_legs = None
def on_data(self, data: Slice) -> None:
if self._order_legs is None:
if self.is_market_open(self._option_symbol):
chain = data.option_chains.get(self._option_symbol)
if chain:
call_contracts = [contract for contract in chain if contract.right == OptionRight.CALL]
call_contracts_by_expiry = [(key, list(group)) for key, group in itertools.groupby(call_contracts, key=lambda x: x.expiry)]
call_contracts_by_expiry.sort(key=lambda x: x[0])
call_contracts = call_contracts_by_expiry[0][1]
call_contracts.sort(key=lambda x: x.strike)
if len(call_contracts) < 3:
return
quantities = [1, -2, 1]
self._order_legs = []
for i, contract in enumerate(call_contracts[:3]):
leg = Leg.create(contract.symbol, quantities[i])
self._order_legs.append(leg)
else:
# COMBO MARKET ORDERS
self.combo_market_orders()
# COMBO LIMIT ORDERS
self.combo_limit_orders()
# COMBO LEG LIMIT ORDERS
self.combo_leg_limit_orders()
def combo_market_orders(self) -> None:
if len(self._open_market_orders) != 0 or self._order_legs is None:
return
self.log("Submitting combo market orders")
tickets = self.combo_market_order(self._order_legs, 2, asynchronous=False)
self._open_market_orders.extend(tickets)
tickets = self.combo_market_order(self._order_legs, 2, asynchronous=True)
self._open_market_orders.extend(tickets)
for ticket in tickets:
response = ticket.cancel("Attempt to cancel combo market order")
if response.is_success:
raise AssertionError("Combo market orders should fill instantly, they should not be cancelable in backtest mode: " + response.order_id)
def combo_limit_orders(self) -> None:
if len(self._open_limit_orders) == 0:
self.log("Submitting ComboLimitOrder")
current_price = sum([leg.quantity * self.securities[leg.symbol].close for leg in self._order_legs])
tickets = self.combo_limit_order(self._order_legs, 2, current_price + 1.5)
self._open_limit_orders.extend(tickets)
# These won't fill, we will test cancel with this
tickets = self.combo_limit_order(self._order_legs, -2, current_price + 3)
self._open_limit_orders.extend(tickets)
else:
combo1 = self._open_limit_orders[:len(self._order_legs)]
combo2 = self._open_limit_orders[-len(self._order_legs):]
# check if either is filled and cancel the other
if self.check_group_orders_for_fills(combo1, combo2):
return
# if neither order has filled, bring in the limits by a penny
ticket = combo1[0]
new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + 0.01, 2)
self.debug(f"Updating limits - Combo 1 {ticket.order_id}: {new_limit:.2f}")
fields = UpdateOrderFields()
fields.limit_price = new_limit
fields.tag = f"Update #{len(ticket.update_requests) + 1}"
ticket.update(fields)
ticket = combo2[0]
new_limit = round(ticket.get(OrderField.LIMIT_PRICE) - 0.01, 2)
self.debug(f"Updating limits - Combo 2 {ticket.order_id}: {new_limit:.2f}")
fields.limit_price = new_limit
fields.tag = f"Update #{len(ticket.update_requests) + 1}"
ticket.update(fields)
def combo_leg_limit_orders(self) -> None:
if len(self._open_leg_limit_orders) == 0:
self.log("Submitting ComboLegLimitOrder")
# submit a limit order to buy 2 shares at .1% below the bar's close
for leg in self._order_legs:
close = self.securities[leg.symbol].close
leg.order_price = close * .999
tickets = self.combo_leg_limit_order(self._order_legs, quantity=2)
self._open_leg_limit_orders.extend(tickets)
# submit another limit order to sell 2 shares at .1% above the bar's close
for leg in self._order_legs:
close = self.securities[leg.symbol].close
leg.order_price = close * 1.001
tickets = self.combo_leg_limit_order(self._order_legs, -2)
self._open_leg_limit_orders.extend(tickets)
else:
combo1 = self._open_leg_limit_orders[:len(self._order_legs)]
combo2 = self._open_leg_limit_orders[-len(self._order_legs):]
# check if either is filled and cancel the other
if self.check_group_orders_for_fills(combo1, combo2):
return
# if neither order has filled, bring in the limits by a penny
for ticket in combo1:
new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)
self.debug(f"Updating limits - Combo #1: {new_limit:.2f}")
fields = UpdateOrderFields()
fields.limit_price = new_limit
fields.tag = f"Update #{len(ticket.update_requests) + 1}"
ticket.update(fields)
for ticket in combo2:
new_limit = round(ticket.get(OrderField.LIMIT_PRICE) + (1 if ticket.quantity > 0 else -1) * 0.01, 2)
self.debug(f"Updating limits - Combo #2: {new_limit:.2f}")
fields.limit_price = new_limit
fields.tag = f"Update #{len(ticket.update_requests) + 1}"
ticket.update(fields)
def on_order_event(self, order_event: OrderEvent) -> None:
order = self.transactions.get_order_by_id(order_event.order_id)
if order_event.quantity == 0:
raise AssertionError("OrderEvent quantity is Not expected to be 0, it should hold the current order Quantity")
if order_event.quantity != order.quantity:
raise AssertionError("OrderEvent quantity should hold the current order Quantity. "
f"Got {order_event.quantity}, expected {order.quantity}")
if order.type == OrderType.COMBO_LEG_LIMIT and order_event.limit_price == 0:
raise AssertionError("OrderEvent.LIMIT_PRICE is not expected to be 0 for ComboLegLimitOrder")
def check_group_orders_for_fills(self, combo1: list[OrderTicket], combo2: list[OrderTicket]) -> bool:
if all(x.status == OrderStatus.FILLED for x in combo1):
self.log(f"{combo1[0].order_type}: Canceling combo #2, combo #1 is filled.")
if any(OrderExtensions.is_open(x.status) for x in combo2):
for ticket in combo2:
ticket.cancel("Combo #1 filled.")
return True
if all(x.status == OrderStatus.FILLED for x in combo2):
self.log(f"{combo2[0].order_type}: Canceling combo #1, combo #2 is filled.")
if any(OrderExtensions.is_open(x.status) for x in combo1):
for ticket in combo1:
ticket.cancel("Combo #2 filled.")
return True
return False
def on_end_of_algorithm(self) -> None:
filled_orders = list(self.transactions.get_orders(lambda x: x.status == OrderStatus.FILLED))
order_tickets = list(self.transactions.get_order_tickets())
open_orders = self.transactions.get_open_orders()
open_order_tickets = list(self.transactions.get_open_order_tickets())
remaining_open_orders = self.transactions.get_open_orders_remaining_quantity()
# 6 market, 6 limit, 6 leg limit.
# Out of the 6 limit orders, 3 are expected to be canceled.
expected_orders_count = 18
expected_fills_count = 15
if len(filled_orders) != expected_fills_count or len(order_tickets) != expected_orders_count:
raise AssertionError(f"There were expected {expected_fills_count} filled orders and {expected_orders_count} order tickets, but there were {len(filled_orders)} filled orders and {len(order_tickets)} order tickets")
filled_combo_market_orders = [x for x in filled_orders if x.type == OrderType.COMBO_MARKET]
filled_combo_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LIMIT]
filled_combo_leg_limit_orders = [x for x in filled_orders if x.type == OrderType.COMBO_LEG_LIMIT]
if len(filled_combo_market_orders) != 6 or len(filled_combo_limit_orders) != 3 or len(filled_combo_leg_limit_orders) != 6:
raise AssertionError("There were expected 6 filled market orders, 3 filled combo limit orders and 6 filled combo leg limit orders, "
f"but there were {len(filled_combo_market_orders)} filled market orders, {len(filled_combo_limit_orders)} filled "
f"combo limit orders and {len(filled_combo_leg_limit_orders)} filled combo leg limit orders")
if len(open_orders) != 0 or len(open_order_tickets) != 0:
raise AssertionError("No open orders or tickets were expected")
if remaining_open_orders != 0:
raise AssertionError("No remaining quantity to be filled from open orders was expected")
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

暂无描述
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/boxigg/Lean.git
git@gitee.com:boxigg/Lean.git
boxigg
Lean
Lean
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /