# 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 AlgorithmImports import *### <summary>### Basic algorithm demonstrating how to place trailing stop orders.### </summary>### <meta name="tag" content="trading and orders" />### <meta name="tag" content="placing orders" />### <meta name="tag" content="trailing stop order"/>class TrailingStopOrderRegressionAlgorithm(QCAlgorithm):'''Basic algorithm demonstrating how to place trailing stop orders.'''buy_trailing_amount = 2sell_trailing_amount = 0.5asynchronous_orders = Falsedef 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").symbolself._buy_order_ticket: OrderTicket = Noneself._sell_order_ticket: OrderTicket = Noneself._previous_slice: Slice = Nonedef on_data(self, slice: Slice):if not slice.contains_key(self._symbol):returnif self._buy_order_ticket is None:self._buy_order_ticket = self.trailing_stop_order(self._symbol, 100, trailing_amount=self.buy_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)elif self._buy_order_ticket.status != OrderStatus.FILLED:stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)# Get the previous bar to compare to the stop price,# because stop price update attempt with the current slice data happens after OnData.low = self._previous_slice.quote_bars[self._symbol].ask.low if self._previous_slice.quote_bars.contains_key(self._symbol) \else self._previous_slice.bars[self._symbol].lowstop_price_to_market_price_distance = stop_price - lowif stop_price_to_market_price_distance > self.buy_trailing_amount:raise AssertionError(f"StopPrice {stop_price} should be within {self.buy_trailing_amount} of the previous low price {low} at all times.")if self._sell_order_ticket is None:if self.portfolio.invested:self._sell_order_ticket = self.trailing_stop_order(self._symbol, -100, trailing_amount=self.sell_trailing_amount, trailing_as_percentage=False, asynchronous=self.asynchronous_orders)elif self._sell_order_ticket.status != OrderStatus.FILLED:stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)# Get the previous bar to compare to the stop price,# because stop price update attempt with the current slice data happens after OnData.high = self._previous_slice.quote_bars[self._symbol].bid.high if self._previous_slice.quote_bars.contains_key(self._symbol) \else self._previous_slice.bars[self._symbol].highstop_price_to_market_price_distance = high - stop_priceif stop_price_to_market_price_distance > self.sell_trailing_amount:raise AssertionError(f"StopPrice {stop_price} should be within {self.sell_trailing_amount} of the previous high price {high} at all times.")self._previous_slice = slicedef on_order_event(self, orderEvent: OrderEvent):if orderEvent.status == OrderStatus.FILLED:if orderEvent.direction == OrderDirection.BUY:stop_price = self._buy_order_ticket.get(OrderField.STOP_PRICE)if orderEvent.fill_price < stop_price:raise AssertionError(f"Buy trailing stop order should have filled with price greater than or equal to the stop price {stop_price}. "f"Fill price: {orderEvent.fill_price}")else:stop_price = self._sell_order_ticket.get(OrderField.STOP_PRICE)if orderEvent.fill_price > stop_price:raise AssertionError(f"Sell trailing stop order should have filled with price less than or equal to the stop price {stop_price}. "f"Fill price: {orderEvent.fill_price}")def on_end_of_algorithm(self):for ticket in self.transactions.get_order_tickets():if ticket.submit_request.asynchronous != self.asynchronous_orders:raise AssertionError("Expected all orders to have the same asynchronous flag as the algorithm.")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。