|
| 1 | +/* |
| 2 | + * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. |
| 3 | + * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. |
| 4 | + * |
| 5 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + * you may not use this file except in compliance with the License. |
| 7 | + * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | +*/ |
| 15 | + |
| 16 | +using System; |
| 17 | +using System.Collections.Generic; |
| 18 | +using QuantConnect.Data; |
| 19 | +using QuantConnect.Interfaces; |
| 20 | +using QuantConnect.Orders; |
| 21 | + |
| 22 | +namespace QuantConnect.Algorithm.CSharp |
| 23 | +{ |
| 24 | + /// <summary> |
| 25 | + /// Regression algorithm for the winner path of a one-cancels-the-other (OCO) order group: buys SPY at |
| 26 | + /// market, then places a 2-leg OCO group (a take-profit limit leg 1% above the entry price and a stop-market |
| 27 | + /// leg 30% below it, which the January 2019 rally can never reach). The limit leg should fill and the group |
| 28 | + /// should cancel the stop leg in the same order-event batch |
| 29 | + /// </summary> |
| 30 | + public class OneCancelsTheOtherOrderRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition |
| 31 | + { |
| 32 | + private Symbol _spy; |
| 33 | + private List<OrderTicket> _tickets; |
| 34 | + |
| 35 | + // tracks every order event this algorithm receives, relevant or not, so we can tell whether two |
| 36 | + // particular events were delivered back to back (same batch) or with something else in between |
| 37 | + private int _orderEventCount; |
| 38 | + |
| 39 | + private int? _winnerOrderId; |
| 40 | + private DateTime _winnerFillUtcTime; |
| 41 | + private int _winnerFillEventCount; |
| 42 | + private bool _siblingCanceledInSameBatch; |
| 43 | + |
| 44 | + public override void Initialize() |
| 45 | + { |
| 46 | + SetStartDate(2019, 1, 1); |
| 47 | + SetEndDate(2019, 1, 20); |
| 48 | + |
| 49 | + _spy = AddEquity("SPY", Resolution.Hour).Symbol; |
| 50 | + } |
| 51 | + |
| 52 | + public override void OnData(Slice slice) |
| 53 | + { |
| 54 | + // trade exactly once: once the winning leg closes the position, Portfolio.Invested goes back to |
| 55 | + // false and this would otherwise place a second, independent OCO group on top of the first |
| 56 | + if (_tickets == null && !Portfolio.Invested) |
| 57 | + { |
| 58 | + MarketOrder(_spy, 100); |
| 59 | + |
| 60 | + // take profit +1% is reached by the January rally; the stop -30% can never fill |
| 61 | + _tickets = OneCancelsTheOtherOrder(_spy, -100, |
| 62 | + limitPrice: Math.Round(Securities[_spy].Price * 1.01m, 2), |
| 63 | + stopPrice: Math.Round(Securities[_spy].Price * 0.70m, 2)); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public override void OnOrderEvent(OrderEvent orderEvent) |
| 68 | + { |
| 69 | + _orderEventCount++; |
| 70 | + |
| 71 | + if (_tickets == null || (orderEvent.OrderId != _tickets[0].OrderId && orderEvent.OrderId != _tickets[1].OrderId)) |
| 72 | + { |
| 73 | + // not one of our OCO legs (for example the entry market order) |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + if (orderEvent.Status == OrderStatus.Filled) |
| 78 | + { |
| 79 | + if (_winnerOrderId.HasValue) |
| 80 | + { |
| 81 | + throw new RegressionTestException( |
| 82 | + $"Order {orderEvent.OrderId} filled after order {_winnerOrderId} had already won the OCO group. Only one leg should ever fill."); |
| 83 | + } |
| 84 | + |
| 85 | + _winnerOrderId = orderEvent.OrderId; |
| 86 | + _winnerFillUtcTime = orderEvent.UtcTime; |
| 87 | + _winnerFillEventCount = _orderEventCount; |
| 88 | + } |
| 89 | + else if (orderEvent.Status == OrderStatus.Canceled) |
| 90 | + { |
| 91 | + if (!_winnerOrderId.HasValue) |
| 92 | + { |
| 93 | + throw new RegressionTestException($"Order {orderEvent.OrderId} was canceled before any leg of the group had filled."); |
| 94 | + } |
| 95 | + |
| 96 | + // the sibling cancel must land in the same order-event batch as the winning fill: same |
| 97 | + // timestamp, and delivered as the very next order event this algorithm receives after the fill |
| 98 | + if (orderEvent.UtcTime != _winnerFillUtcTime || _orderEventCount != _winnerFillEventCount + 1) |
| 99 | + { |
| 100 | + throw new RegressionTestException( |
| 101 | + "Expected the losing leg's Canceled event to arrive in the same order-event batch as the winning Filled event."); |
| 102 | + } |
| 103 | + |
| 104 | + _siblingCanceledInSameBatch = true; |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + public override void OnEndOfAlgorithm() |
| 109 | + { |
| 110 | + if (_tickets == null || _tickets.Count != 2) |
| 111 | + { |
| 112 | + throw new RegressionTestException("Expected the one-cancels-the-other order group to have been placed with 2 legs."); |
| 113 | + } |
| 114 | + |
| 115 | + // limit leg won, stop leg was canceled by the group |
| 116 | + if (_tickets[0].Status != OrderStatus.Filled) |
| 117 | + { |
| 118 | + throw new RegressionTestException($"Expected the take-profit limit order to be filled, but it was {_tickets[0].Status}."); |
| 119 | + } |
| 120 | + |
| 121 | + if (_tickets[1].Status != OrderStatus.Canceled) |
| 122 | + { |
| 123 | + throw new RegressionTestException($"Expected the stop-loss order to be canceled by the group, but it was {_tickets[1].Status}."); |
| 124 | + } |
| 125 | + |
| 126 | + if (Portfolio.Invested) |
| 127 | + { |
| 128 | + throw new RegressionTestException("Expected no open position at the end of the algorithm: the winning limit leg should have closed it."); |
| 129 | + } |
| 130 | + |
| 131 | + if (!_siblingCanceledInSameBatch) |
| 132 | + { |
| 133 | + throw new RegressionTestException("Expected the stop-loss leg's Canceled event to have arrived in the same order-event batch as the winning fill."); |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /// <summary> |
| 138 | + /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. |
| 139 | + /// </summary> |
| 140 | + public bool CanRunLocally { get; } = true; |
| 141 | + |
| 142 | + /// <summary> |
| 143 | + /// This is used by the regression test system to indicate which languages this algorithm is written in. |
| 144 | + /// </summary> |
| 145 | + public List<Language> Languages { get; } = new() { Language.CSharp, Language.Python }; |
| 146 | + |
| 147 | + /// <summary> |
| 148 | + /// Data Points count of all timeslices of algorithm |
| 149 | + /// </summary> |
| 150 | + public long DataPoints => 190; |
| 151 | + |
| 152 | + /// <summary> |
| 153 | + /// Data Points count of the algorithm history |
| 154 | + /// </summary> |
| 155 | + public int AlgorithmHistoryDataPoints => 0; |
| 156 | + |
| 157 | + /// <summary> |
| 158 | + /// Final status of the algorithm |
| 159 | + /// </summary> |
| 160 | + public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed; |
| 161 | + |
| 162 | + /// <summary> |
| 163 | + /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm |
| 164 | + /// </summary> |
| 165 | + public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> |
| 166 | + { |
| 167 | + {"Total Orders", "3"}, |
| 168 | + {"Average Win", "0.24%"}, |
| 169 | + {"Average Loss", "0%"}, |
| 170 | + {"Compounding Annual Return", "4.986%"}, |
| 171 | + {"Drawdown", "0.000%"}, |
| 172 | + {"Expectancy", "0"}, |
| 173 | + {"Start Equity", "100000"}, |
| 174 | + {"End Equity", "100235.79"}, |
| 175 | + {"Net Profit", "0.236%"}, |
| 176 | + {"Sharpe Ratio", "0.613"}, |
| 177 | + {"Sortino Ratio", "0"}, |
| 178 | + {"Probabilistic Sharpe Ratio", "45.094%"}, |
| 179 | + {"Loss Rate", "0%"}, |
| 180 | + {"Win Rate", "100%"}, |
| 181 | + {"Profit-Loss Ratio", "0"}, |
| 182 | + {"Alpha", "0.011"}, |
| 183 | + {"Beta", "-0.003"}, |
| 184 | + {"Annual Standard Deviation", "0.009"}, |
| 185 | + {"Annual Variance", "0"}, |
| 186 | + {"Information Ratio", "-8.833"}, |
| 187 | + {"Tracking Error", "0.18"}, |
| 188 | + {"Treynor Ratio", "-1.72"}, |
| 189 | + {"Total Fees", "$2.00"}, |
| 190 | + {"Estimated Strategy Capacity", "$140000000.00"}, |
| 191 | + {"Lowest Capacity Asset", "SPY R735QTJ8XC9X"}, |
| 192 | + {"Portfolio Turnover", "2.64%"}, |
| 193 | + {"Drawdown Recovery", "0"}, |
| 194 | + {"OrderListHash", "d0a9c717f35803df04a8ab7f31697c5c"} |
| 195 | + }; |
| 196 | + } |
| 197 | +} |
0 commit comments