Files
quantconnect--lean/Algorithm.Python/OrderTicketAssignmentDemoAlgorithm.py
T
Jhonathan Abreu d82d70dacf
API Tests / build (push) Has been cancelled
Benchmarks / build (push) Has been cancelled
Build & Test Lean / build (push) Has been cancelled
Regression Tests / build (push) Has been cancelled
Report Generator Tests / build (push) Has been cancelled
Research Regression Tests / build (push) Has been cancelled
Syntax Tests / build (push) Has been cancelled
Python Virtual Environments / build (push) Has been cancelled
Support asynchronous non-market orders (#8946)
* Add 'asynchronous' parameter to trading api

* Add regression algorithms

* More fixes for asynchronous orders

* Fix failing unit tests

* Fix failing unit tests

* Add multiple orders requests in transaction handler

Make each transaction thread handle requests corresponding to the same order

* Refactor order state machine in BrokerageTransactionHandler

Now using a single dictionary to hold orders and their state, either pending for submission, open or closed.

* Revert: remove complete orders from new state machine in BTH

* Add order ticket to new BTH open orders state machine

* Run syn in Backtesting transaction handler for new orders submission

* Remove OpenOrderState.SubmissionPending property

* Add Security to OpenOrderState

* Minor fix

* Cleanup

* Some cleanup in BTH

* Cleanup

* Minor fix

* Minor unit test fix

* Minor fix

* Make Brokerage.ConcurrencyEnable property virtual

* Minor change

* Cleanup

* Add 'asynchronous' parameter to SetHoldings api

* Improve regression algorithms
2025-09-10 08:29:50 -04:00

56 lines
2.6 KiB
Python

# 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.
from datetime import timedelta
from AlgorithmImports import *
### <summary>
### Demonstration on how to access order tickets right after placing an order.
### </summary>
class OrderTicketAssignmentDemoAlgorithm(QCAlgorithm):
'''Demonstration on how to access order tickets right after placing an order.'''
def initialize(self):
self.set_start_date(2013, 10, 7)
self.set_end_date(2013, 10, 11)
self.set_cash(100000)
self._symbol = self.add_equity("SPY").symbol
self.trade_count = 0
self.consolidate(self._symbol, timedelta(hours=1), self.hour_consolidator)
def hour_consolidator(self, bar: TradeBar):
# Reset self.ticket to None on each new bar
self.ticket = None
self.ticket = self.market_order(self._symbol, 1, asynchronous=True)
self.debug(f"{self.time}: Buy: Price {bar.price}, order_id: {self.ticket.order_id}")
self.trade_count += 1
def on_order_event(self, order_event: OrderEvent):
# We cannot access self.ticket directly because it is assigned asynchronously:
# this order event could be triggered before self.ticket is assigned.
ticket = order_event.ticket
if ticket is None:
raise AssertionError("Expected order ticket in order event to not be null")
if self.ticket is None:
raise AssertionError("Expected the ticket to have been returned by the MarketOrder call")
if ticket.order_id != self.ticket.order_id:
raise AssertionError("Expected the ticket in the order event to be the same instance as the one returned by MarketOrder")
self.debug(ticket.to_string())
def on_end_of_algorithm(self):
# Just checking that orders were placed
if not self.portfolio.invested or self.trade_count != self.transactions.orders_count:
raise AssertionError(f"Expected the portfolio to have holdings and to have {self.trade_count} trades, but had {self.transactions.orders_count}")