Skip to content

Commit c5c56bf

Browse files
authored
Fix symbol changed events emission time (#8552)
* Fix symbol changed events emission time Ensure the symbol changed events are emitted after the securities are processes by the main loop in the AlgorithmManager. This way the algorithm has access to the new symbol security since it would be added by the securities processing logic. Also, allow all securities to be properly updated, including prices and cash, before emitting the event, so that the any logic (like placing orders) done by the algorithm on the handler has the correct data. * Minor fix * Minor change * Minor change
1 parent 9b35411 commit c5c56bf

File tree

3 files changed

+213
-22
lines changed

3 files changed

+213
-22
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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 QuantConnect.Data.Market;
17+
18+
namespace QuantConnect.Algorithm.CSharp
19+
{
20+
/// <summary>
21+
/// Regression algorithm asserting that the new symbol, on a security changed event,
22+
/// is added to the securities collection and is tradable.
23+
/// This specific algorithm tests the manual rollover with the symbol changed event
24+
/// that is received in the <see cref="OnSymbolChangedEvents(SymbolChangedEvents)"/> handler.
25+
/// </summary>
26+
public class ManualContinuousFuturesPositionRolloverFromSymbolChangedEventHandlerRegressionAlgorithm
27+
: ManualContinuousFuturesPositionRolloverRegressionAlgorithm
28+
{
29+
public override void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged)
30+
{
31+
if (!Portfolio.Invested)
32+
{
33+
return;
34+
}
35+
36+
ManualPositionsRollover(symbolsChanged);
37+
}
38+
}
39+
}
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
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 QuantConnect.Data;
17+
using QuantConnect.Orders;
18+
using QuantConnect.Interfaces;
19+
using System.Collections.Generic;
20+
using QuantConnect.Securities.Future;
21+
using Futures = QuantConnect.Securities.Futures;
22+
using QuantConnect.Data.Market;
23+
24+
namespace QuantConnect.Algorithm.CSharp
25+
{
26+
/// <summary>
27+
/// Regression algorithm asserting that the new symbol, on a security changed event,
28+
/// is added to the securities collection and is tradable.
29+
/// This specific algorithm tests the manual rollover with the symbol changed event
30+
/// that is received in the slice in <see cref="OnData(Slice)"/>.
31+
/// </summary>
32+
public class ManualContinuousFuturesPositionRolloverRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
33+
{
34+
private Future _continuousContract;
35+
36+
public override void Initialize()
37+
{
38+
SetStartDate(2013, 7, 1);
39+
SetEndDate(2014, 1, 1);
40+
41+
_continuousContract = AddFuture(Futures.Indices.SP500EMini,
42+
dataNormalizationMode: DataNormalizationMode.BackwardsRatio,
43+
dataMappingMode: DataMappingMode.LastTradingDay,
44+
contractDepthOffset: 0
45+
);
46+
}
47+
48+
public override void OnData(Slice slice)
49+
{
50+
if (!Portfolio.Invested)
51+
{
52+
Order(_continuousContract.Mapped, 1);
53+
}
54+
else
55+
{
56+
ManualPositionsRollover(slice.SymbolChangedEvents);
57+
}
58+
}
59+
60+
protected void ManualPositionsRollover(SymbolChangedEvents symbolChangedEvents)
61+
{
62+
foreach (var changedEvent in symbolChangedEvents.Values)
63+
{
64+
Debug($"{Time} - SymbolChanged event: {changedEvent}");
65+
66+
// This access will throw if any of the symbols are not in the securities collection
67+
var oldSecurity = Securities[changedEvent.OldSymbol];
68+
var newSecurity = Securities[changedEvent.NewSymbol];
69+
70+
if (!oldSecurity.Invested) continue;
71+
72+
// Rolling over: liquidate any position of the old mapped contract and switch to the newly mapped contract
73+
var quantity = oldSecurity.Holdings.Quantity;
74+
var tag = $"Rollover - Symbol changed at {Time}: {changedEvent.OldSymbol} -> {changedEvent.NewSymbol}";
75+
Liquidate(symbol: oldSecurity.Symbol, tag: tag);
76+
Order(newSecurity.Symbol, quantity, tag: tag);
77+
}
78+
}
79+
80+
public override void OnOrderEvent(OrderEvent orderEvent)
81+
{
82+
Debug($"{orderEvent}");
83+
}
84+
85+
public override void OnEndOfAlgorithm()
86+
{
87+
if (Transactions.OrdersCount < 3)
88+
{
89+
throw new RegressionTestException("Expected at least 3 orders.");
90+
}
91+
}
92+
93+
/// <summary>
94+
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
95+
/// </summary>
96+
public bool CanRunLocally { get; } = true;
97+
98+
/// <summary>
99+
/// This is used by the regression test system to indicate which languages this algorithm is written in.
100+
/// </summary>
101+
public List<Language> Languages { get; } = new() { Language.CSharp };
102+
103+
/// <summary>
104+
/// Data Points count of all timeslices of algorithm
105+
/// </summary>
106+
public long DataPoints => 713375;
107+
108+
/// <summary>
109+
/// Data Points count of the algorithm history
110+
/// </summary>
111+
public int AlgorithmHistoryDataPoints => 0;
112+
113+
/// <summary>
114+
/// Final status of the algorithm
115+
/// </summary>
116+
public AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
117+
118+
/// <summary>
119+
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
120+
/// </summary>
121+
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
122+
{
123+
{"Total Orders", "3"},
124+
{"Average Win", "7.01%"},
125+
{"Average Loss", "0%"},
126+
{"Compounding Annual Return", "15.617%"},
127+
{"Drawdown", "1.600%"},
128+
{"Expectancy", "0"},
129+
{"Start Equity", "100000"},
130+
{"End Equity", "107578.9"},
131+
{"Net Profit", "7.579%"},
132+
{"Sharpe Ratio", "1.706"},
133+
{"Sortino Ratio", "0.919"},
134+
{"Probabilistic Sharpe Ratio", "88.924%"},
135+
{"Loss Rate", "0%"},
136+
{"Win Rate", "100%"},
137+
{"Profit-Loss Ratio", "0"},
138+
{"Alpha", "0.08"},
139+
{"Beta", "0.094"},
140+
{"Annual Standard Deviation", "0.059"},
141+
{"Annual Variance", "0.003"},
142+
{"Information Ratio", "-1.246"},
143+
{"Tracking Error", "0.094"},
144+
{"Treynor Ratio", "1.06"},
145+
{"Total Fees", "$6.45"},
146+
{"Estimated Strategy Capacity", "$2900000000.00"},
147+
{"Lowest Capacity Asset", "ES VMKLFZIH2MTD"},
148+
{"Portfolio Turnover", "1.37%"},
149+
{"OrderListHash", "4b28a221076b82e98fbbcb38c22b3013"}
150+
};
151+
}
152+
}

Engine/AlgorithmManager.cs

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -224,28 +224,6 @@ public void Run(AlgorithmNodePacket job, IAlgorithm algorithm, ISynchronizer syn
224224
// Update the current slice before firing scheduled events or any other task
225225
algorithm.SetCurrentSlice(timeSlice.Slice);
226226

227-
if (timeSlice.Slice.SymbolChangedEvents.Count != 0)
228-
{
229-
try
230-
{
231-
algorithm.OnSymbolChangedEvents(timeSlice.Slice.SymbolChangedEvents);
232-
}
233-
catch (Exception err)
234-
{
235-
algorithm.SetRuntimeError(err, "OnSymbolChangedEvents");
236-
return;
237-
}
238-
239-
foreach (var symbol in timeSlice.Slice.SymbolChangedEvents.Keys)
240-
{
241-
// cancel all orders for the old symbol
242-
foreach (var ticket in transactions.GetOpenOrderTickets(x => x.Symbol == symbol))
243-
{
244-
ticket.Cancel("Open order cancelled on symbol changed event");
245-
}
246-
}
247-
}
248-
249227
if (timeSlice.SecurityChanges != SecurityChanges.None)
250228
{
251229
algorithm.ProcessSecurityChanges(timeSlice.SecurityChanges);
@@ -305,6 +283,28 @@ public void Run(AlgorithmNodePacket job, IAlgorithm algorithm, ISynchronizer syn
305283
// security prices got updated
306284
algorithm.Portfolio.InvalidateTotalPortfolioValue();
307285

286+
if (timeSlice.Slice.SymbolChangedEvents.Count != 0)
287+
{
288+
try
289+
{
290+
algorithm.OnSymbolChangedEvents(timeSlice.Slice.SymbolChangedEvents);
291+
}
292+
catch (Exception err)
293+
{
294+
algorithm.SetRuntimeError(err, "OnSymbolChangedEvents");
295+
return;
296+
}
297+
298+
foreach (var symbol in timeSlice.Slice.SymbolChangedEvents.Keys)
299+
{
300+
// cancel all orders for the old symbol
301+
foreach (var ticket in transactions.GetOpenOrderTickets(x => x.Symbol == symbol))
302+
{
303+
ticket.Cancel("Open order cancelled on symbol changed event");
304+
}
305+
}
306+
}
307+
308308
// process fill models on the updated data before entering algorithm, applies to all non-market orders
309309
transactions.ProcessSynchronousEvents();
310310

0 commit comments

Comments
 (0)