From ddb7bb0ce62269f59f86c13e76eab7e7868408cc Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:21:18 +0000 Subject: [PATCH 1/6] Size futures margin calls without targets beyond the futures margin limit A single-security position group whose security also has holdings in other groups, such as futures sharing contracts with a future option covered call, was sized by the security's buying power model, which applies the margin delta to all of the security's holdings. With little equity left the resulting target went past 1, which FutureMarginModel rejects, so the margin call threw instead of liquidating. Such groups are now sized like groups that aren't held: the fewest of their own lots whose margin covers the deficit. Adds futures margin call tests: long and short, alongside a stock, and sharing contracts with a future option strategy. Co-Authored-By: Claude Opus 5.5 --- Common/Securities/DefaultMarginCallModel.cs | 9 +- .../Common/Securities/MarginCallModelTests.cs | 121 +++++++++++++++++- 2 files changed, 123 insertions(+), 7 deletions(-) diff --git a/Common/Securities/DefaultMarginCallModel.cs b/Common/Securities/DefaultMarginCallModel.cs index 81e0661523ba..94adbddf0eaa 100644 --- a/Common/Securities/DefaultMarginCallModel.cs +++ b/Common/Securities/DefaultMarginCallModel.cs @@ -207,7 +207,9 @@ protected virtual IEnumerable GenerateMarginCallOrders(Margi var currentlyUsedBuyingPower = positionGroup.BuyingPowerModel.GetReservedBuyingPowerForPositionGroup(Portfolio, positionGroup); decimal absQuantity; - if (Portfolio.Positions.Groups.TryGetGroup(positionGroup.Key, out var heldPositionGroup) && heldPositionGroup.Quantity == positionGroup.Quantity) + if (Portfolio.Positions.Groups.TryGetGroup(positionGroup.Key, out var heldPositionGroup) && heldPositionGroup.Quantity == positionGroup.Quantity + // a single security's buying power model sizes from all of its holdings, which other position groups can share + && (positionGroup.Count > 1 || positionGroup.Single().Quantity == Portfolio.Securities[positionGroup.Single().Symbol].Holdings.Quantity)) { // if currentlyUsedBuyingPower > deltaAccountCurrency, means we can keep using the diff in buying power var buyingPowerToKeep = Math.Max(0, currentlyUsedBuyingPower - deltaAccountCurrency); @@ -225,8 +227,9 @@ protected virtual IEnumerable GenerateMarginCallOrders(Margi } else { - // the holdings left after other liquidations can form a group that isn't held, which the buying power model - // sizes from the held one: the fewest lots of this group whose margin covers the deficit are liquidated instead + // the holdings left after other liquidations can form a group that isn't held, and a security's holdings can be + // shared with other groups, which the buying power model sizes from: the fewest lots of this group whose margin + // covers the deficit are liquidated instead var heldLots = Math.Abs(positionGroup.Quantity); var lowerLots = 1m; var upperLots = Math.Ceiling(heldLots); diff --git a/Tests/Common/Securities/MarginCallModelTests.cs b/Tests/Common/Securities/MarginCallModelTests.cs index 62b6e887cb38..446d8369dd22 100644 --- a/Tests/Common/Securities/MarginCallModelTests.cs +++ b/Tests/Common/Securities/MarginCallModelTests.cs @@ -24,6 +24,7 @@ using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Securities; +using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; using QuantConnect.Securities.Positions; @@ -466,10 +467,11 @@ public void LiquidatesPositionGroupsSharingALegForTheDeficitOpenMarginCallOrders } else { - // the open covered call liquidation releases $5000: the stock group is liquidated again for the rest + // the open covered call liquidation releases $5000: the stock group is liquidated again for the $2500 left, + // the 50 shares whose own margin covers it Assert.AreEqual(1, marginCallOrders.Count); Assert.IsNull(marginCallOrders[0].GroupOrderManager); - Assert.AreEqual(-51, marginCallOrders[0].Quantity); + Assert.AreEqual(-50, marginCallOrders[0].Quantity); } // once every margin call order is closed, the margin call is generated again from the current holdings @@ -834,13 +836,14 @@ public void LiquidatesAStockGroupSharingTheUnderlyingOfARejectedComboOrder() var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out _); Assert.AreEqual(3, marginCallOrders.Count); - // the combo order is rejected: the stock group is liquidated as generated for the whole $4100 deficit + // the combo order is rejected: the stock group is liquidated as generated for the whole $4100 deficit, the 82 shares + // whose own margin covers it var tickets = portfolio.MarginCallModel.ExecuteMarginCall(marginCallOrders); Assert.AreEqual(3, tickets.Count); Assert.IsTrue(tickets.Take(2).All(ticket => ticket.Status == OrderStatus.Invalid && ticket.SubmitRequest.GroupOrderManager != null)); Assert.AreEqual(Symbols.SPY, tickets[2].Symbol); Assert.IsNull(tickets[2].SubmitRequest.GroupOrderManager); - Assert.AreEqual(-83, tickets[2].Quantity); + Assert.AreEqual(-82, tickets[2].Quantity); Assert.IsTrue(tickets[2].Status.IsOpen()); } @@ -948,6 +951,90 @@ public void LiquidatesMultiLotPositionGroupsOnceWithTheirHeldQuantities() Assert.AreEqual(0, portfolio.MarginCallModel.GetMarginCallOrders(out _).Count); } + [TestCase(10)] + [TestCase(-10)] + public void GeneratesMarginCallOrdersForFutures(int quantity) + { + var orderProcessor = new FakeOrderProcessor(); + // $60000 maintenance margin against a $30000 portfolio: the $30000 the futures keep is a target of the whole + // portfolio value, which holds the 4 contracts whose $6600 initial margin each fits in it + var portfolio = GetFuturesPortfolio(orderProcessor, 30000, quantity); + Assert.AreEqual(60000, portfolio.TotalMarginUsed); + Assert.AreEqual(30000, portfolio.TotalPortfolioValue); + + var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out var issueMarginCallWarning); + Assert.IsTrue(issueMarginCallWarning); + Assert.AreEqual(1, marginCallOrders.Count); + Assert.AreEqual(Symbols.Future_ESZ18_Dec2018, marginCallOrders[0].Symbol); + Assert.AreEqual(-Math.Sign(quantity) * 6, marginCallOrders[0].Quantity); + + var orders = ExecuteMarginCall(portfolio, orderProcessor, marginCallOrders); + Assert.AreEqual(-Math.Sign(quantity) * 6, orders.Single().Quantity); + } + + [TestCase(10)] + [TestCase(-10)] + public void GeneratesMarginCallOrdersForFuturesAlongsideAnotherSecurity(int quantity) + { + var orderProcessor = new FakeOrderProcessor(); + var portfolio = GetFuturesPortfolio(orderProcessor, 30000, quantity); + + // 100 AAPL shares at $100 with 2x leverage, bought at $120 so they're the loser and liquidated first + var stock = GetSecurity(Symbols.AAPL, portfolio.CashBook); + portfolio.Securities.Add(stock); + stock.SetLeverage(2); + stock.SetMarketPrice(new Tick(DateTime.Now, Symbols.AAPL, 100m, 100m)); + stock.Holdings.SetHoldings(120m, 100); + portfolio.InvalidateTotalPortfolioValue(); + Assert.AreEqual(65000, portfolio.TotalMarginUsed); + Assert.AreEqual(40000, portfolio.TotalPortfolioValue); + + // the $25000 deficit: the futures keep $35000 of their $60000 margin, 5 contracts at $6600 initial margin each, + // and the stock none of its $5000 + var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out _); + Assert.AreEqual(2, marginCallOrders.Count); + Assert.AreEqual(-Math.Sign(quantity) * 5, marginCallOrders.Single(request => request.Symbol == Symbols.Future_ESZ18_Dec2018).Quantity); + Assert.AreEqual(-100, marginCallOrders.Single(request => request.Symbol == Symbols.AAPL).Quantity); + + // the stock order releases $5000, the futures one is scaled down to the 4 contracts whose $6000 maintenance margin each + // covers the $20000 left + var orders = ExecuteMarginCall(portfolio, orderProcessor, marginCallOrders); + Assert.AreEqual(2, orders.Count); + Assert.AreEqual(-100, orders[0].Quantity); + Assert.AreEqual(-Math.Sign(quantity) * 4, orders[1].Quantity); + } + + [TestCase(10, OptionRight.Call)] + [TestCase(-10, OptionRight.Put)] + public void GeneratesMarginCallOrdersForFuturesSharedWithAFutureOptionStrategy(int quantity, OptionRight right) + { + var orderProcessor = new FakeOrderProcessor(); + var portfolio = GetFuturesPortfolio(orderProcessor, 5000, quantity); + + // a short future option covered by one of the futures: the 9 others are a futures group of their own + var future = portfolio.Securities[Symbols.Future_ESZ18_Dec2018]; + var optionSymbol = Symbol.CreateOption(future.Symbol, Market.CME, OptionStyle.American, right, 2900m, new DateTime(2018, 12, 21)); + var option = new QuantConnect.Securities.FutureOption.FutureOption(optionSymbol, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), + new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), portfolio.CashBook, + RegisteredSecurityDataTypesProvider.Null, new SecurityCache(), future); + option.FeeModel = new ConstantFeeModel(0); + portfolio.Securities.Add(option); + option.SetMarketPrice(new Tick(new DateTime(2018, 10, 1), optionSymbol, 10m, 10m)); + option.Holdings.SetHoldings(10m, -1); + portfolio.InvalidateTotalPortfolioValue(); + Assert.AreEqual(2, portfolio.Positions.Groups.Count); + Assert.AreEqual(4990, portfolio.TotalPortfolioValue); + + // the strategy's margin and the $54000 of the futures group leave a deficit larger than the latter, which is liquidated + // entirely + var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out _); + Assert.AreEqual(3, marginCallOrders.Count); + Assert.AreEqual(-Math.Sign(quantity) * 9, marginCallOrders.Single(request => request.GroupOrderManager == null).Quantity); + Assert.AreEqual(-Math.Sign(quantity), marginCallOrders.Single(request => request.Symbol == future.Symbol + && request.GroupOrderManager != null).Quantity); + Assert.AreEqual(1, marginCallOrders.Single(request => request.Symbol == optionSymbol).Quantity); + } + public enum OpenOrderKind { MarginCall, @@ -989,6 +1076,32 @@ private SecurityPortfolioManager GetStocksPortfolio(IOrderProcessor orderProcess return portfolio; } + private SecurityPortfolioManager GetFuturesPortfolio(IOrderProcessor orderProcessor, decimal cash, int quantity) + { + var portfolio = GetPortfolio(orderProcessor, 0); + portfolio.MarginCallModel = new DefaultMarginCallModel(portfolio, null); + portfolio.Transactions.MarketOrderFillTimeout = TimeSpan.Zero; + + // the ES maintenance margin is $6000 per contract on this date + var time = new DateTime(2018, 10, 1); + var future = new Future( + SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), + new SubscriptionDataConfig(typeof(TradeBar), Symbols.Future_ESZ18_Dec2018, Resolution.Minute, TimeZones.NewYork, + TimeZones.NewYork, true, false, false), + new Cash(Currencies.USD, 0, 1m), + new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), + portfolio.CashBook, + RegisteredSecurityDataTypesProvider.Null); + future.FeeModel = new ConstantFeeModel(0); + portfolio.Securities.Add(future); + future.SetMarketPrice(new Tick(time, future.Symbol, 2900m, 2900m)); + future.Holdings.SetHoldings(2900m, quantity); + portfolio.CashBook[Currencies.USD].SetAmount(cash); + portfolio.InvalidateTotalPortfolioValue(); + + return portfolio; + } + private SecurityPortfolioManager GetSpyPortfolio(IOrderProcessor orderProcessor, decimal cash, int callQuantity) { var portfolio = GetPortfolio(orderProcessor, 0); From 2c9122cc9ba7458792311d80fe6f927d98d63182 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:13:41 +0000 Subject: [PATCH 2/6] Size shared single-security groups by their buying power model again Routing them to the lot search sized stocks shared with option strategies differently and left out liquidation fees. The futures margin model's guard is relaxed for reducing targets instead, in the next commit. Co-Authored-By: Claude Opus 5.5 --- Common/Securities/DefaultMarginCallModel.cs | 9 +++------ Tests/Common/Securities/MarginCallModelTests.cs | 10 ++++------ 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/Common/Securities/DefaultMarginCallModel.cs b/Common/Securities/DefaultMarginCallModel.cs index 94adbddf0eaa..81e0661523ba 100644 --- a/Common/Securities/DefaultMarginCallModel.cs +++ b/Common/Securities/DefaultMarginCallModel.cs @@ -207,9 +207,7 @@ protected virtual IEnumerable GenerateMarginCallOrders(Margi var currentlyUsedBuyingPower = positionGroup.BuyingPowerModel.GetReservedBuyingPowerForPositionGroup(Portfolio, positionGroup); decimal absQuantity; - if (Portfolio.Positions.Groups.TryGetGroup(positionGroup.Key, out var heldPositionGroup) && heldPositionGroup.Quantity == positionGroup.Quantity - // a single security's buying power model sizes from all of its holdings, which other position groups can share - && (positionGroup.Count > 1 || positionGroup.Single().Quantity == Portfolio.Securities[positionGroup.Single().Symbol].Holdings.Quantity)) + if (Portfolio.Positions.Groups.TryGetGroup(positionGroup.Key, out var heldPositionGroup) && heldPositionGroup.Quantity == positionGroup.Quantity) { // if currentlyUsedBuyingPower > deltaAccountCurrency, means we can keep using the diff in buying power var buyingPowerToKeep = Math.Max(0, currentlyUsedBuyingPower - deltaAccountCurrency); @@ -227,9 +225,8 @@ protected virtual IEnumerable GenerateMarginCallOrders(Margi } else { - // the holdings left after other liquidations can form a group that isn't held, and a security's holdings can be - // shared with other groups, which the buying power model sizes from: the fewest lots of this group whose margin - // covers the deficit are liquidated instead + // the holdings left after other liquidations can form a group that isn't held, which the buying power model + // sizes from the held one: the fewest lots of this group whose margin covers the deficit are liquidated instead var heldLots = Math.Abs(positionGroup.Quantity); var lowerLots = 1m; var upperLots = Math.Ceiling(heldLots); diff --git a/Tests/Common/Securities/MarginCallModelTests.cs b/Tests/Common/Securities/MarginCallModelTests.cs index 446d8369dd22..59b3cc082a83 100644 --- a/Tests/Common/Securities/MarginCallModelTests.cs +++ b/Tests/Common/Securities/MarginCallModelTests.cs @@ -467,11 +467,10 @@ public void LiquidatesPositionGroupsSharingALegForTheDeficitOpenMarginCallOrders } else { - // the open covered call liquidation releases $5000: the stock group is liquidated again for the $2500 left, - // the 50 shares whose own margin covers it + // the open covered call liquidation releases $5000: the stock group is liquidated again for the rest Assert.AreEqual(1, marginCallOrders.Count); Assert.IsNull(marginCallOrders[0].GroupOrderManager); - Assert.AreEqual(-50, marginCallOrders[0].Quantity); + Assert.AreEqual(-51, marginCallOrders[0].Quantity); } // once every margin call order is closed, the margin call is generated again from the current holdings @@ -836,14 +835,13 @@ public void LiquidatesAStockGroupSharingTheUnderlyingOfARejectedComboOrder() var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out _); Assert.AreEqual(3, marginCallOrders.Count); - // the combo order is rejected: the stock group is liquidated as generated for the whole $4100 deficit, the 82 shares - // whose own margin covers it + // the combo order is rejected: the stock group is liquidated as generated for the whole $4100 deficit var tickets = portfolio.MarginCallModel.ExecuteMarginCall(marginCallOrders); Assert.AreEqual(3, tickets.Count); Assert.IsTrue(tickets.Take(2).All(ticket => ticket.Status == OrderStatus.Invalid && ticket.SubmitRequest.GroupOrderManager != null)); Assert.AreEqual(Symbols.SPY, tickets[2].Symbol); Assert.IsNull(tickets[2].SubmitRequest.GroupOrderManager); - Assert.AreEqual(-82, tickets[2].Quantity); + Assert.AreEqual(-83, tickets[2].Quantity); Assert.IsTrue(tickets[2].Status.IsOpen()); } From 6e869766bdaaad85be1ae8a7d65dded0aa4d4c50 Mon Sep 17 00:00:00 2001 From: stoicAI1776 Date: Sat, 18 Apr 2026 02:47:08 +0530 Subject: [PATCH 3/6] Handle futures delta reductions when target buying power exceeds 100% --- Common/Securities/Future/FutureMarginModel.cs | 28 +++++++++++++- .../FutureMarginBuyingPowerModelTests.cs | 37 +++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) diff --git a/Common/Securities/Future/FutureMarginModel.cs b/Common/Securities/Future/FutureMarginModel.cs index 59459f61ceeb..201ad483a0f4 100644 --- a/Common/Securities/Future/FutureMarginModel.cs +++ b/Common/Securities/Future/FutureMarginModel.cs @@ -111,7 +111,8 @@ public override void SetLeverage(Security security, decimal leverage) public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { - if (Math.Abs(parameters.TargetBuyingPower) > 1) + if (Math.Abs(parameters.TargetBuyingPower) > 1 + && !IsReducingExistingExposure(parameters)) { throw new InvalidOperationException( "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + @@ -120,6 +121,31 @@ public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBu return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } + /// + /// Futures can temporarily exceed 100% target buying power during margin call liquidation requests. + /// In these cases we allow leveraged targets only when they reduce existing exposure. + /// + private bool IsReducingExistingExposure(GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) + { + var totalPortfolioValue = parameters.Portfolio.TotalPortfolioValue; + if (totalPortfolioValue == 0) + { + return false; + } + + var currentMargin = this.GetInitialMarginRequirement( + parameters.Security, parameters.Security.Holdings.Quantity + ); + if (currentMargin == 0) + { + return false; + } + + var targetMargin = parameters.TargetBuyingPower * totalPortfolioValue; + return Math.Sign(targetMargin) == Math.Sign(currentMargin) + && Math.Abs(targetMargin) <= Math.Abs(currentMargin); + } + /// /// Gets the total margin required to execute the specified order in units of the account currency including fees /// diff --git a/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs b/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs index 067ad229b736..0062808171ce 100644 --- a/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs +++ b/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs @@ -496,6 +496,43 @@ public void GetMaximumOrderQuantityForTargetBuyingPower_ThrowsForInvalidTarget(d 0))); } + [Test] + public void GetMaximumOrderQuantityForDeltaBuyingPower_AllowsReducingLeveragedTarget() + { + var algorithm = new QCAlgorithm(); + algorithm.SetFinishedWarmingUp(); + algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); + + var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar; + var futureSecurity = algorithm.AddFuture(ticker); + Update(futureSecurity, 100, algorithm); + + algorithm.Portfolio.SetCash(1000); + futureSecurity.Holdings.SetHoldings(100, 10); + algorithm.Portfolio.InvalidateTotalPortfolioValue(); + + var usedBuyingPower = futureSecurity.BuyingPowerModel.GetReservedBuyingPowerForPosition( + new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower; + var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; + var targetBuyingPower = 1.1m * totalPortfolioValue; + var deltaBuyingPower = targetBuyingPower - usedBuyingPower; + + Assert.Greater(Math.Abs(usedBuyingPower / totalPortfolioValue), 1m); + Assert.Less(deltaBuyingPower, 0m); + + Assert.DoesNotThrow(() => + { + var result = futureSecurity.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( + new GetMaximumOrderQuantityForDeltaBuyingPowerParameters( + algorithm.Portfolio, + futureSecurity, + deltaBuyingPower, + 0 + )); + Assert.Less(result.Quantity, 0m); + }); + } + [TestCase(1)] [TestCase(0.5)] [TestCase(-1)] From 9917dd4608ed0b12e2ac4737b5285804fc67f700 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:18:15 +0000 Subject: [PATCH 4/6] Cover fees in margin call liquidations of shared holdings Fills the stock order of the rejected covered call combo test with a fee, and adds a partial liquidation of futures shared with a rejected future option strategy, long and short, asserting the margin left after the fill. Co-Authored-By: Claude Opus 5.5 --- .../Common/Securities/MarginCallModelTests.cs | 70 ++++++++++++++----- 1 file changed, 54 insertions(+), 16 deletions(-) diff --git a/Tests/Common/Securities/MarginCallModelTests.cs b/Tests/Common/Securities/MarginCallModelTests.cs index 59b3cc082a83..53d87a96cf0e 100644 --- a/Tests/Common/Securities/MarginCallModelTests.cs +++ b/Tests/Common/Securities/MarginCallModelTests.cs @@ -843,6 +843,12 @@ public void LiquidatesAStockGroupSharingTheUnderlyingOfARejectedComboOrder() Assert.IsNull(tickets[2].SubmitRequest.GroupOrderManager); Assert.AreEqual(-83, tickets[2].Quantity); Assert.IsTrue(tickets[2].Status.IsOpen()); + + // the fill and its $1 fee leave the account within its margin requirement + var order = Order.CreateOrder(tickets[2].SubmitRequest); + portfolio.ProcessFills(new List { new OrderEvent(order, DateTime.UtcNow, new OrderFee(new CashAmount(1, Currencies.USD))) + { FillPrice = 100m, FillQuantity = order.Quantity, Status = OrderStatus.Filled } }); + Assert.GreaterOrEqual(portfolio.MarginRemaining, 0); } [Test] @@ -1007,20 +1013,7 @@ public void GeneratesMarginCallOrdersForFuturesAlongsideAnotherSecurity(int quan public void GeneratesMarginCallOrdersForFuturesSharedWithAFutureOptionStrategy(int quantity, OptionRight right) { var orderProcessor = new FakeOrderProcessor(); - var portfolio = GetFuturesPortfolio(orderProcessor, 5000, quantity); - - // a short future option covered by one of the futures: the 9 others are a futures group of their own - var future = portfolio.Securities[Symbols.Future_ESZ18_Dec2018]; - var optionSymbol = Symbol.CreateOption(future.Symbol, Market.CME, OptionStyle.American, right, 2900m, new DateTime(2018, 12, 21)); - var option = new QuantConnect.Securities.FutureOption.FutureOption(optionSymbol, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), - new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), portfolio.CashBook, - RegisteredSecurityDataTypesProvider.Null, new SecurityCache(), future); - option.FeeModel = new ConstantFeeModel(0); - portfolio.Securities.Add(option); - option.SetMarketPrice(new Tick(new DateTime(2018, 10, 1), optionSymbol, 10m, 10m)); - option.Holdings.SetHoldings(10m, -1); - portfolio.InvalidateTotalPortfolioValue(); - Assert.AreEqual(2, portfolio.Positions.Groups.Count); + var portfolio = GetSharedFuturesPortfolio(orderProcessor, 5000, quantity, right); Assert.AreEqual(4990, portfolio.TotalPortfolioValue); // the strategy's margin and the $54000 of the futures group leave a deficit larger than the latter, which is liquidated @@ -1028,9 +1021,32 @@ public void GeneratesMarginCallOrdersForFuturesSharedWithAFutureOptionStrategy(i var marginCallOrders = portfolio.MarginCallModel.GetMarginCallOrders(out _); Assert.AreEqual(3, marginCallOrders.Count); Assert.AreEqual(-Math.Sign(quantity) * 9, marginCallOrders.Single(request => request.GroupOrderManager == null).Quantity); - Assert.AreEqual(-Math.Sign(quantity), marginCallOrders.Single(request => request.Symbol == future.Symbol + Assert.AreEqual(-Math.Sign(quantity), marginCallOrders.Single(request => request.Symbol == Symbols.Future_ESZ18_Dec2018 && request.GroupOrderManager != null).Quantity); - Assert.AreEqual(1, marginCallOrders.Single(request => request.Symbol == optionSymbol).Quantity); + Assert.AreEqual(1, marginCallOrders.Single(request => request.Symbol.SecurityType == SecurityType.FutureOption).Quantity); + } + + [TestCase(10, OptionRight.Call)] + [TestCase(-10, OptionRight.Put)] + public void LiquidatesFuturesSharedWithARejectedFutureOptionStrategyForTheDeficitAndFees(int quantity, OptionRight right) + { + // the brokerage rejects combo orders, so the futures group's order has to cover the deficit by itself + var orderProcessor = new FakeOrderProcessor { RejectsOrder = requests => requests[0].OrderType == OrderType.ComboMarket }; + var portfolio = GetSharedFuturesPortfolio(orderProcessor, 0, quantity, right); + portfolio.CashBook[Currencies.USD].AddAmount(portfolio.TotalMarginUsed - 12000 - portfolio.TotalPortfolioValue); + portfolio.InvalidateTotalPortfolioValue(); + Assert.AreEqual(12000, portfolio.TotalMarginUsed - portfolio.TotalPortfolioValue); + + var tickets = portfolio.MarginCallModel.ExecuteMarginCall(portfolio.MarginCallModel.GetMarginCallOrders(out _)); + Assert.AreEqual(3, tickets.Count); + var futuresTicket = tickets.Single(ticket => ticket.SubmitRequest.GroupOrderManager == null); + Assert.AreEqual(-Math.Sign(quantity) * 3, futuresTicket.Quantity); + + // the fill and its $1 fee leave the account within its margin requirement + var order = Order.CreateOrder(futuresTicket.SubmitRequest); + portfolio.ProcessFills(new List { new OrderEvent(order, DateTime.UtcNow, new OrderFee(new CashAmount(1, Currencies.USD))) + { FillPrice = 2900m, FillQuantity = order.Quantity, Status = OrderStatus.Filled } }); + Assert.GreaterOrEqual(portfolio.MarginRemaining, 0); } public enum OpenOrderKind @@ -1100,6 +1116,28 @@ private SecurityPortfolioManager GetFuturesPortfolio(IOrderProcessor orderProces return portfolio; } + /// + /// Gets a futures portfolio where one of the futures covers a short future option, so the others are a group of their own + /// + private SecurityPortfolioManager GetSharedFuturesPortfolio(IOrderProcessor orderProcessor, decimal cash, int quantity, + OptionRight right) + { + var portfolio = GetFuturesPortfolio(orderProcessor, cash, quantity); + var future = portfolio.Securities[Symbols.Future_ESZ18_Dec2018]; + var optionSymbol = Symbol.CreateOption(future.Symbol, Market.CME, OptionStyle.American, right, 2900m, new DateTime(2018, 12, 21)); + var option = new QuantConnect.Securities.FutureOption.FutureOption(optionSymbol, SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), + new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)), portfolio.CashBook, + RegisteredSecurityDataTypesProvider.Null, new SecurityCache(), future); + option.FeeModel = new ConstantFeeModel(0); + portfolio.Securities.Add(option); + option.SetMarketPrice(new Tick(new DateTime(2018, 10, 1), optionSymbol, 10m, 10m)); + option.Holdings.SetHoldings(10m, -1); + portfolio.InvalidateTotalPortfolioValue(); + Assert.AreEqual(2, portfolio.Positions.Groups.Count); + + return portfolio; + } + private SecurityPortfolioManager GetSpyPortfolio(IOrderProcessor orderProcessor, decimal cash, int callQuantity) { var portfolio = GetPortfolio(orderProcessor, 0); From bbdc30465705a8bffb7aaa18d23e04a46a092f90 Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:23:21 +0000 Subject: [PATCH 5/6] Inline the futures leveraged target reduction check The check had a single call site and its summary described margin calls only, while it applies to every target request: a leveraged target is allowed only when it reduces the current position. Co-Authored-By: Claude Opus 5.5 --- Common/Securities/Future/FutureMarginModel.cs | 41 +++++-------------- 1 file changed, 11 insertions(+), 30 deletions(-) diff --git a/Common/Securities/Future/FutureMarginModel.cs b/Common/Securities/Future/FutureMarginModel.cs index 201ad483a0f4..8e53fea0bb15 100644 --- a/Common/Securities/Future/FutureMarginModel.cs +++ b/Common/Securities/Future/FutureMarginModel.cs @@ -111,41 +111,22 @@ public override void SetLeverage(Security security, decimal leverage) public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { - if (Math.Abs(parameters.TargetBuyingPower) > 1 - && !IsReducingExistingExposure(parameters)) + if (Math.Abs(parameters.TargetBuyingPower) > 1) { - throw new InvalidOperationException( - "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + - $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); + // a leveraged target is allowed only when it reduces the current position, such as a margin call liquidating + // holdings whose margin is above the portfolio value + var currentMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Security.Holdings.Quantity); + var targetMargin = parameters.TargetBuyingPower * parameters.Portfolio.TotalPortfolioValue; + if (currentMargin == 0 || Math.Sign(targetMargin) != Math.Sign(currentMargin) || Math.Abs(targetMargin) > Math.Abs(currentMargin)) + { + throw new InvalidOperationException( + "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + + $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); + } } return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } - /// - /// Futures can temporarily exceed 100% target buying power during margin call liquidation requests. - /// In these cases we allow leveraged targets only when they reduce existing exposure. - /// - private bool IsReducingExistingExposure(GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) - { - var totalPortfolioValue = parameters.Portfolio.TotalPortfolioValue; - if (totalPortfolioValue == 0) - { - return false; - } - - var currentMargin = this.GetInitialMarginRequirement( - parameters.Security, parameters.Security.Holdings.Quantity - ); - if (currentMargin == 0) - { - return false; - } - - var targetMargin = parameters.TargetBuyingPower * totalPortfolioValue; - return Math.Sign(targetMargin) == Math.Sign(currentMargin) - && Math.Abs(targetMargin) <= Math.Abs(currentMargin); - } - /// /// Gets the total margin required to execute the specified order in units of the account currency including fees /// From 7004d1f3e5b358294dd8359fa33ea5bb58cf4bff Mon Sep 17 00:00:00 2001 From: "quantconnect-kronos[bot]" <346399058+quantconnect-kronos[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:36:38 +0000 Subject: [PATCH 6/6] Confine the futures leveraged target relaxation to delta requests Target requests, such as SetHoldings, reject leveraged targets again as on master. FutureMarginModel overrides the delta request instead: a delta that only reduces the holdings, as a margin call's does, is sized past a 100% target, and the result is capped so that fees with a portfolio value near zero never size the order past the holdings or against them. Co-Authored-By: Claude Opus 5.5 --- Common/Securities/Future/FutureMarginModel.cs | 48 ++++++++++++++---- .../FutureMarginBuyingPowerModelTests.cs | 49 +++++++++++++++++++ 2 files changed, 87 insertions(+), 10 deletions(-) diff --git a/Common/Securities/Future/FutureMarginModel.cs b/Common/Securities/Future/FutureMarginModel.cs index 8e53fea0bb15..8bde3efe264d 100644 --- a/Common/Securities/Future/FutureMarginModel.cs +++ b/Common/Securities/Future/FutureMarginModel.cs @@ -113,20 +113,48 @@ public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBu { if (Math.Abs(parameters.TargetBuyingPower) > 1) { - // a leveraged target is allowed only when it reduces the current position, such as a margin call liquidating - // holdings whose margin is above the portfolio value - var currentMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Security.Holdings.Quantity); - var targetMargin = parameters.TargetBuyingPower * parameters.Portfolio.TotalPortfolioValue; - if (currentMargin == 0 || Math.Sign(targetMargin) != Math.Sign(currentMargin) || Math.Abs(targetMargin) > Math.Abs(currentMargin)) - { - throw new InvalidOperationException( - "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + - $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); - } + throw new InvalidOperationException( + "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + + $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); } return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } + /// + /// Get the maximum market order quantity to obtain a delta in the buying power used by a security. + /// The deltas sign defines the position side to apply it to, positive long, negative short. + /// + /// An object containing the portfolio, the security and the delta buying power + /// Returns the maximum allowed market order quantity and if zero, also the reason + /// Used by the margin call model to reduce the position by a delta percent. + public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForDeltaBuyingPower( + GetMaximumOrderQuantityForDeltaBuyingPowerParameters parameters) + { + var holdingsQuantity = parameters.Security.Holdings.Quantity; + var usedBuyingPower = GetReservedBuyingPowerForPosition(new ReservedBuyingPowerForPositionParameters(parameters.Security)) + .AbsoluteUsedBuyingPower; + var targetBuyingPower = Math.Sign(holdingsQuantity) * usedBuyingPower + parameters.DeltaBuyingPower; + var totalPortfolioValue = parameters.Portfolio.TotalPortfolioValue; + + // a delta that only reduces the holdings, such as a margin call's, targets more margin than the portfolio value when the + // holdings already use more than it, which isn't a leveraged target + if (totalPortfolioValue == 0 || Math.Abs(targetBuyingPower) <= Math.Abs(totalPortfolioValue) + || Math.Sign(targetBuyingPower) != Math.Sign(holdingsQuantity) || Math.Abs(targetBuyingPower) > usedBuyingPower) + { + return base.GetMaximumOrderQuantityForDeltaBuyingPower(parameters); + } + + var result = base.GetMaximumOrderQuantityForTargetBuyingPower(new GetMaximumOrderQuantityForTargetBuyingPowerParameters( + parameters.Portfolio, parameters.Security, targetBuyingPower / totalPortfolioValue, + parameters.MinimumOrderMarginPortfolioPercentage, parameters.SilenceNonErrorReasons)); + + // fees can size the order past the holdings, or against the reduction, when the portfolio value is close to zero + var reducedQuantity = Math.Sign(result.Quantity) == -Math.Sign(holdingsQuantity) + ? Math.Min(Math.Abs(result.Quantity), Math.Abs(holdingsQuantity)) + : 0; + return new GetMaximumOrderQuantityResult(-Math.Sign(holdingsQuantity) * reducedQuantity, result.Reason, result.IsError); + } + /// /// Gets the total margin required to execute the specified order in units of the account currency including fees /// diff --git a/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs b/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs index 0062808171ce..d2d6fa73e02d 100644 --- a/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs +++ b/Tests/Common/Securities/FutureMarginBuyingPowerModelTests.cs @@ -27,6 +27,7 @@ using QuantConnect.Data.Market; using QuantConnect.Logging; using QuantConnect.Orders; +using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; @@ -533,6 +534,54 @@ public void GetMaximumOrderQuantityForDeltaBuyingPower_AllowsReducingLeveragedTa }); } + [TestCase(10)] + [TestCase(-10)] + public void GetMaximumOrderQuantityForTargetBuyingPower_ThrowsForLeveragedTargetReducingTheHoldings(int quantity) + { + var algorithm = new QCAlgorithm(); + algorithm.SetFinishedWarmingUp(); + algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); + var futureSecurity = algorithm.AddFuture(QuantConnect.Securities.Futures.Financials.EuroDollar); + Update(futureSecurity, 100, algorithm); + algorithm.Portfolio.SetCash(1000); + futureSecurity.Holdings.SetHoldings(100, quantity); + algorithm.Portfolio.InvalidateTotalPortfolioValue(); + + // only margin call deltas reduce the holdings past a leveraged target, target requests keep rejecting it + var target = Math.Sign(quantity) * 1.1m; + Assert.Less(1.1m * algorithm.Portfolio.TotalPortfolioValue, futureSecurity.BuyingPowerModel.GetReservedBuyingPowerForPosition( + new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower); + Assert.Throws(() => futureSecurity.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( + new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algorithm.Portfolio, futureSecurity, target, 0))); + } + + [TestCase(10)] + [TestCase(-10)] + public void GetMaximumOrderQuantityForDeltaBuyingPower_ReducesLeveragedHoldingsWithoutReversingThem(int quantity) + { + var algorithm = new QCAlgorithm(); + algorithm.SetFinishedWarmingUp(); + algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); + var futureSecurity = algorithm.AddFuture(QuantConnect.Securities.Futures.Financials.EuroDollar); + futureSecurity.FeeModel = new ConstantFeeModel(2.5m); + Update(futureSecurity, 100, algorithm); + futureSecurity.Holdings.SetHoldings(100, quantity); + + // a $2 portfolio value, less than an order's fee, which sizes a fee adjusted target past the holdings + algorithm.Portfolio.CashBook[Currencies.USD].AddAmount(2 - algorithm.Portfolio.TotalPortfolioValue); + algorithm.Portfolio.InvalidateTotalPortfolioValue(); + Assert.AreEqual(2, algorithm.Portfolio.TotalPortfolioValue); + + var usedBuyingPower = futureSecurity.BuyingPowerModel.GetReservedBuyingPowerForPosition( + new ReservedBuyingPowerForPositionParameters(futureSecurity)).AbsoluteUsedBuyingPower; + var result = futureSecurity.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( + new GetMaximumOrderQuantityForDeltaBuyingPowerParameters(algorithm.Portfolio, futureSecurity, + -Math.Sign(quantity) * usedBuyingPower * 0.1m, 0)); + + Assert.AreEqual(-Math.Sign(quantity), Math.Sign(result.Quantity)); + Assert.LessOrEqual(Math.Abs(result.Quantity), Math.Abs(quantity)); + } + [TestCase(1)] [TestCase(0.5)] [TestCase(-1)]