27de93f78f
Syntax Tests / build (push) Has been cancelled
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
Python Virtual Environments / build (push) Has been cancelled
* Market orders wait for fresh data instead of filling on stale prices A market order would previously fill immediately on the most recent available data even when that data was older than StalePriceTimeSpan (default one hour), only attaching a warning. This is unrealistic for a coarse resolution asset (hour/daily) where the latest bar is the stale previous close when the order is placed mid-bar or via an intraday scheduled event. The default fill models (FillModel, EquityFillModel, FutureFillModel) now wait for fresh data instead of filling on a stale price, but only for hour and daily resolutions; the order fills when the next bar closes. For minute/second/tick subscriptions the previous behavior is kept (fill on the stale price with a warning), since stale data there is a genuine gap rather than a bar still forming. Adds HourResolutionMarketOrderStalePriceRegressionAlgorithm, updates the FillOutsideHours daily expectation, and regenerates statistics for the hour/daily algorithms whose fills change. FutureOptionDaily buys and liquidates a day apart now (a same-day buy + liquidate cannot fill on daily data once stale fills are disabled). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Normalize and correct StalePriceTimeSpan XML docs The interface and class docs now match and reflect the actual behavior: the wait-for-fresh-data only applies to hour/daily resolutions, while minute/second/tick subscriptions still fill on stale data with a warning. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Fill resting market orders at the bar open instead of the close A hour/daily market order that was resting before the current bar opened (it predates the bar - placed after the previous close or while waiting for fresh data) now fills at the bar open, the price when trading resumed (like a MarketOnOpen), instead of the bar close. Orders placed during the bar still fill at the current/close price, so intraday mid-bar fills are unchanged. Equity fills are unchanged (resting equity orders are already converted to MarketOnOpen by QCAlgorithm.MarketOrder). Adds the shared FillModel.GetMarketFillPrice helper used by the base FillModel and FutureFillModel, a unit test, and regenerates statistics for the affected daily/hour futures, index and crypto regression algorithms (order counts unchanged, only fill prices). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Add regression algorithm asserting resting market orders fill at the bar open RestingMarketOrderFillsAtBarOpenRegressionAlgorithm buys a daily future on the bar that delivers it (fills at that bar's close) and submits a liquidation while the market is closed (overnight pulse, no fresh bar). The liquidation rests and fills on a later bar at the bar open, not its close - asserting the new GetMarketFillPrice behavior. The in-bar buy is asserted to fill at the close, for contrast. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Carry the bar start time on Prices instead of re-reading the cache Add Prices.Time (the bar start, mirroring BaseData.Time/EndTime), populated from the source bar/tick in every GetPrices path. GetMarketFillPrice now uses prices.Time directly instead of a second asset.Cache.GetData() lookup. Behavior is unchanged (prices.Time equals the previously read cache time). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Add regression algorithm asserting in-session hour orders fill at the latest close HourMarketOrderFillsAtBarCloseRegressionAlgorithm submits an hour resolution market order mid-bar (via an intraday scheduled event) while the market is open, using the default one hour StalePriceTimeSpan. It asserts the order fills immediately at the latest available bar's close - not waiting and not at the bar open - since the latest bar is within the stale window. Guards the resting-order open-fill behavior against affecting ordinary in-session fills. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * Regenerate custom fill model algorithm statistics for the open-fill change CustomModelsAlgorithm and CustomPartialFillModelAlgorithm subscribe SPY at hour resolution and their custom fill models delegate to base.MarketFill, so resting orders now fill at the bar open. Regenerate their statistics (C#/Python) and the inline expected statistics of the PEP8StyleCustomModelsWork test. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
212 lines
8.5 KiB
C#
212 lines
8.5 KiB
C#
/*
|
|
* 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.
|
|
*
|
|
*/
|
|
|
|
using System;
|
|
using System.Linq;
|
|
using QuantConnect.Data;
|
|
using QuantConnect.Interfaces;
|
|
using QuantConnect.Securities;
|
|
using System.Collections.Generic;
|
|
using QuantConnect.Securities.Future;
|
|
using QuantConnect.Data.UniverseSelection;
|
|
|
|
namespace QuantConnect.Algorithm.CSharp
|
|
{
|
|
/// <summary>
|
|
/// Regression algorithm using and testing HSI futures and index
|
|
/// </summary>
|
|
public class HSIFutureHourRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
|
|
{
|
|
private int _symbolChangeEvent;
|
|
private Symbol _contractSymbol;
|
|
private Symbol _index;
|
|
private Symbol _futureSymbol;
|
|
|
|
/// <summary>
|
|
/// The data resolution
|
|
/// </summary>
|
|
protected virtual Resolution Resolution => Resolution.Hour;
|
|
|
|
/// <summary>
|
|
/// Initialize your algorithm and add desired assets.
|
|
/// </summary>
|
|
public override void Initialize()
|
|
{
|
|
SetStartDate(2013, 10, 20);
|
|
SetEndDate(2013, 10, 30);
|
|
|
|
SetAccountCurrency("HKD");
|
|
SetTimeZone(TimeZones.HongKong);
|
|
|
|
UniverseSettings.Resolution = Resolution;
|
|
_index = AddIndex("HSI", Resolution).Symbol;
|
|
var future = AddFuture(Futures.Indices.HangSeng, Resolution);
|
|
future.SetFilter(TimeSpan.Zero, TimeSpan.FromDays(182));
|
|
_futureSymbol = future.Symbol;
|
|
|
|
var seeder = new FuncSecuritySeeder(GetLastKnownPrices);
|
|
SetSecurityInitializer(security => seeder.SeedSecurity(security));
|
|
}
|
|
|
|
/// <summary>
|
|
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
|
|
/// </summary>
|
|
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
|
|
public override void OnData(Slice slice)
|
|
{
|
|
foreach (var changedEvent in slice.SymbolChangedEvents.Values)
|
|
{
|
|
Debug($"{Time} - SymbolChanged event: {changedEvent}");
|
|
if (Time.TimeOfDay != TimeSpan.Zero)
|
|
{
|
|
throw new RegressionTestException($"{Time} unexpected symbol changed event {changedEvent}!");
|
|
}
|
|
_symbolChangeEvent++;
|
|
}
|
|
|
|
if (!Portfolio.Invested)
|
|
{
|
|
foreach (var chain in slice.FutureChains)
|
|
{
|
|
// find the front contract expiring no earlier than in 90 days
|
|
var contract = (
|
|
from futuresContract in chain.Value.OrderBy(x => x.Expiry)
|
|
select futuresContract
|
|
).FirstOrDefault();
|
|
|
|
// if found, trade it
|
|
if (contract != null)
|
|
{
|
|
_contractSymbol = contract.Symbol;
|
|
MarketOrder(_contractSymbol, 1);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
Liquidate();
|
|
}
|
|
}
|
|
|
|
public override void OnEndOfAlgorithm()
|
|
{
|
|
if (_symbolChangeEvent != 1)
|
|
{
|
|
throw new RegressionTestException($"Got no expected symbol changed event count {_symbolChangeEvent}!");
|
|
}
|
|
|
|
// Get the margin requirements
|
|
var buyingPowerModel = Securities[_contractSymbol].BuyingPowerModel;
|
|
var futureMarginModel = buyingPowerModel as FutureMarginModel;
|
|
if (buyingPowerModel == null)
|
|
{
|
|
throw new RegressionTestException($"Invalid buying power model. Found: {buyingPowerModel.GetType().Name}. Expected: {nameof(FutureMarginModel)}");
|
|
}
|
|
var initialOvernight = futureMarginModel.InitialOvernightMarginRequirement;
|
|
var maintenanceOvernight = futureMarginModel.MaintenanceOvernightMarginRequirement;
|
|
var initialIntraday = futureMarginModel.InitialIntradayMarginRequirement;
|
|
var maintenanceIntraday = futureMarginModel.MaintenanceIntradayMarginRequirement;
|
|
|
|
var lastDataFuture = Securities[_futureSymbol].GetLastData();
|
|
if (lastDataFuture == null || (lastDataFuture.EndTime - lastDataFuture.Time) != TimeSpan.FromHours(Resolution == Resolution.Hour ? 1 : 7.25)
|
|
|| lastDataFuture.EndTime.Date != lastDataFuture.Time.Date)
|
|
{
|
|
throw new RegressionTestException($"Unexpected data for symbol {_futureSymbol}!");
|
|
}
|
|
|
|
var lastDataIndex = Securities[_index].GetLastData();
|
|
if (lastDataIndex == null || (lastDataIndex.EndTime - lastDataIndex.Time) != TimeSpan.FromHours(Resolution == Resolution.Hour ? 1 : 6.5)
|
|
|| lastDataFuture.EndTime.Date != lastDataFuture.Time.Date)
|
|
{
|
|
throw new RegressionTestException($"Unexpected data for symbol {_index}!");
|
|
}
|
|
}
|
|
|
|
public override void OnSecuritiesChanged(SecurityChanges changes)
|
|
{
|
|
foreach (var addedSecurity in changes.AddedSecurities)
|
|
{
|
|
if (addedSecurity.Symbol.SecurityType == SecurityType.Future
|
|
&& !addedSecurity.Symbol.IsCanonical()
|
|
&& !addedSecurity.HasData)
|
|
{
|
|
throw new RegressionTestException($"Future contracts did not work up as expected: {addedSecurity.Symbol}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
|
|
/// </summary>
|
|
public bool CanRunLocally { get; } = true;
|
|
|
|
/// <summary>
|
|
/// This is used by the regression test system to indicate which languages this algorithm is written in.
|
|
/// </summary>
|
|
public List<Language> Languages { get; } = new() { Language.CSharp };
|
|
|
|
/// <summary>
|
|
/// Data Points count of all timeslices of algorithm
|
|
/// </summary>
|
|
public virtual long DataPoints => 654;
|
|
|
|
/// <summary>
|
|
/// Data Points count of the algorithm history
|
|
/// </summary>
|
|
public virtual int AlgorithmHistoryDataPoints => 133;
|
|
|
|
/// <summary>
|
|
/// Final status of the algorithm
|
|
/// </summary>
|
|
public virtual AlgorithmStatus AlgorithmStatus => AlgorithmStatus.Completed;
|
|
|
|
/// <summary>
|
|
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
|
|
/// </summary>
|
|
public virtual Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
|
|
{
|
|
{"Total Orders", "44"},
|
|
{"Average Win", "3.60%"},
|
|
{"Average Loss", "-2.01%"},
|
|
{"Compounding Annual Return", "-86.799%"},
|
|
{"Drawdown", "21.100%"},
|
|
{"Expectancy", "-0.118"},
|
|
{"Start Equity", "100000"},
|
|
{"End Equity", "94080"},
|
|
{"Net Profit", "-5.920%"},
|
|
{"Sharpe Ratio", "-0.569"},
|
|
{"Sortino Ratio", "-0.673"},
|
|
{"Probabilistic Sharpe Ratio", "36.195%"},
|
|
{"Loss Rate", "68%"},
|
|
{"Win Rate", "32%"},
|
|
{"Profit-Loss Ratio", "1.79"},
|
|
{"Alpha", "0"},
|
|
{"Beta", "0"},
|
|
{"Annual Standard Deviation", "1.109"},
|
|
{"Annual Variance", "1.231"},
|
|
{"Information Ratio", "-0.563"},
|
|
{"Tracking Error", "1.109"},
|
|
{"Treynor Ratio", "0"},
|
|
{"Total Fees", "$1520.00"},
|
|
{"Estimated Strategy Capacity", "$3400000.00"},
|
|
{"Lowest Capacity Asset", "HSI VL6DN7UV65S9"},
|
|
{"Portfolio Turnover", "4585.54%"},
|
|
{"Drawdown Recovery", "0"},
|
|
{"OrderListHash", "b51907531791771ca92599e32ce2c2f8"}
|
|
};
|
|
}
|
|
}
|