Repository navigation
Use the executable spread side for IB option market order fees - #10178
quantconnect-kronos[bot] wants to merge 7 commits into
Conversation
There was a problem hiding this comment.
Approving. The fix is the smallest one that gives the issue's result: GetPotentialOrderPrice now takes the ask for buys and the bid for sells for market, market on open, market on close and combo market orders, which is the side those orders fill at in Lean's fill models and the side every other quote-based fee model already uses (CoinbaseFeeModel, BinanceFeeModel, BitfinexFeeModel, KrakenFeeModel, FTXFeeModel, AlphaStreamsFeeModel; BybitFeeModel prices its sells from the bid too). The reversed mapping dates back to #7436, and nothing in that pull request explains it as a deliberate choice.
What I checked:
GetPotentialOrderPriceis only called for US equity and index options (InteractiveBrokersFeeModel.cs:118), so futures, equities and forex fees are untouched; the limit, stop and combo limit branches don't change.- The new
USAOptionMarketFeeUsesExecutableSideOfTheSpreadcases cross both premium thresholds of the default tier in both directions for all four order types, and fail on master by inspection (e.g. a buy at 0.09/0.11 gets the 0.50 rate from the bid). TheUSAOptionFeeedit to quote on the ask keeps that test about buys; the 24 failures reported with the fix reverted add up (16 new cases plus the 8 market-type buys at 0.07 and 0.2). - The regression statistics only change fees, end equity and, for the two null-margin algorithms, turnover; the bull call spread's fees rising and the bear call spread's falling is what moving buys to the ask and sells to the bid predicts. The Python
NullMarginMultipleOrdersRegressionAlgorithmshares the C# statistics. - CI is green on this commit (API Tests skipped by its workflow). An end-to-end backtest is described with its outcome.
- Nothing private in the diff, commits or description.
Other repositories: the Documentation premium table is updated in QuantConnect/Documentation#2923, which matches this change. No stubs or API changes are needed.
Label: risk:low. It's a two-line bug fix that's easy to revert, makes the estimated commission match the price the order fills at, leaves every path that's right today as it was, and has tests that fail without it, green CI and an end-to-end run.
There was a problem hiding this comment.
Requesting changes for one caller interaction: the quote-side correction is right, but DefaultOptionAssignmentModel.EstimateArbitragePnL values a hypothetical option sale at the bid while constructing a buy to estimate its fee. The corrected buy fee can therefore cause a new early assignment, not merely change commissions. The inline finding contains the base/head reproduction. Please address the sale-side estimate and cover the assignment decision, or obtain a maintainer decision on accepting that limitation rather than silently widening #10139's behavior.
Verification on this head:
dotnet test Tests/QuantConnect.Tests.csproj -c Release --filter FullyQualifiedName~InteractiveBrokersFeeModelTests: 156 passed. Restoring only the original reversed quote selection gives 24 failures, including all 16 new cases; restoring this head gives 156 passed again.- All six affected regression cases passed, including the Python null-margin case, with the edited fees, equity and turnover statistics.
- Tested end to end: 20 SPY option market fills across both premium thresholds charged the ask-based rate for buys and bid-based rate for sells, with all assertions passing. This verifies the intended fee correction, not the assignment interaction.
- A separate .NET 10 assignment reproduction returned quantity 0 with the base fee model and 10 with this head. Correcting only the assignment simulator's hypothetical order to a sale restored quantity 0.
- Lean CI is green; API Tests is skipped by its workflow.
Cross-repository check: QuantConnect/Documentation#2923 correctly updates all four affected premium-table rows; no further documentation or API/stub update is needed for the intended quote-side correction. The coordinated change remains pending the Lean assignment interaction.
Set risk:high on both PRs because the current implementation newly changes simulated assignment outcomes outside the requested fee correction. Existing unrelated option-fee limitations are tracked separately and are not additional blockers here.
| if (order.Direction == OrderDirection.Buy) | ||
| { | ||
| price = security.BidPrice; | ||
| price = security.AskPrice; |
There was a problem hiding this comment.
[P2] Preserve sale-side fee estimation in the assignment simulator. DefaultOptionAssignmentModel.cs:99,112–119 values the counterparty selling an option at the bid, but passes a positive-quantity MarketOrder to this fee model. Changing that synthetic buy to the ask tier raises the estimated sale fee and can newly trigger early assignment. Reproduced with a standard 100-share American call three days before expiry: strike $0.50, short 10 at average $0.10, underlying close $0.54 and bid/ask $0.5009/$0.54, option bid/ask $0.09/$0.11. With identical inputs, base returns arbitrage P/L $0 and assignment quantity 0; this head returns $1.50 and assigns all 10. Correcting only the simulator's hypothetical order to a sale restores quantity 0. The caller's sign error predates this PR, but this incorrect assignment decision is new. Please align that fee estimate with the sale it models and add an assignment regression, or obtain a maintainer decision on accepting the limitation before changing this caller's behavior.
There was a problem hiding this comment.
Fixed in 24624d8: EstimateArbitragePnL now estimates the close's fee with a sale (holding.Quantity), matching the bid it values the close at, instead of a buy. Added EstimatesTheFeeOfClosingTheCounterPartyPositionAsASale with your reproduction (strike 0.50, short 10 at 0.10, underlying 0.5009/0.54, option 0.09/0.11, 3 days out): it passes on master (base and exercise P/L are both -$15, no assignment), fails with only the fee change (assigns 10), and passes with both. Full unit suite (39769 passed) and all 1112 regression cases pass.
|
Addressed the requested change: the default option assignment model now estimates the fee of the counter-party's hypothetical close as a sale, so the corrected buy-side fee can no longer trigger an assignment the base branch wouldn't. New assignment test covers the reproduced case; the description lists the results. The fee correction itself is unchanged. |
There was a problem hiding this comment.
Requesting changes. The fee-model fix from my earlier approval still holds. The new commit (24624d8) fixes the IB assignment case, but it causes the same kind of unwanted assignment for Tastytrade users, so this needs a person to decide the approach.
Same cause, different fee model. EstimateArbitragePnL builds the counter-party's hypothetical close, but it passes that order to the fee model with the algorithm's security, and that security holds the algorithm's short position. InteractiveBrokersFeeModel reads only the order direction (to pick the bid or ask), so it needs a sale. TastytradeFeeModel reads the direction against Security.Holdings (TastytradeFeeModel.cs:59, BrokerageExtensions.GetOrderPosition). A sale against short holdings counts as sell-to-open and pays $1 per contract. On master, a buy against short holdings counts as buy-to-close and is free. So whichever sign the simulator picks, one of the two models gets a wrong close fee.
I reproduced it with the new test's setup, changing only option.FeeModel = new TastytradeFeeModel() (bid 0.09, ask 0.11, short 10):
- this head: assignment quantity 10
- the same head with only
DefaultOptionAssignmentModel.csreverted to master: 0 - bids of 0.095 and 0.10 give 0 in both.
The IB fee change doesn't reach the Tastytrade path, so this new early assignment comes from this commit alone. Among Lean's fee models, only IB and Tastytrade depend on direction for options.
As far as I can see, no sign choice in the simulator gives the master assignment results for both models. That leaves two limitations to choose between, or a wider change:
- Keep the simulator as on master (drop 24624d8). An IB short option whose bid and ask straddle a premium threshold can then be newly assigned, which was the earlier reviewer's finding.
- Keep 24624d8. A Tastytrade short option can then be newly assigned, as shown above.
- Estimate the close fee against the counter-party's position instead of the algorithm's holdings. This is wider than #10139 and changes how the simulator calls the fee models.
A QuantConnect member should pick one. Whatever they pick, the assignment tests should cover both fee models.
What I checked on this commit:
- CI is green (API Tests skipped by its workflow).
DefaultOptionAssignmentModelTestspass on this head. The new test fails with master's assignment model, as described.- Nothing private in the diff, commits or description.
Other repositories: QuantConnect/Documentation#2923 still matches the fee-side change, and no stubs or API changes are needed. It waits on this decision.
Label: risk:high stays on both pull requests. The change now alters simulated early-assignment outcomes for Tastytrade, beyond the fee correction #10139 asks for, and the approach is still open.
|
The reviewer is right, and I confirmed it from the code: I'm not patching this again until a QuantConnect member picks the approach for
Whichever is chosen, I'll add assignment test cases for both the IB and Tastytrade fee models. The fee-model fix itself (ask for buys, bid for sells) and the Documentation table are unaffected by this choice. |
There was a problem hiding this comment.
Still requesting changes. Nothing changed in the code since my last review of 24624d8. The fee-model fix still holds. EstimateArbitragePnL still needs a QuantConnect member to choose an approach, and nobody has decided on this pull request or on #10139 yet.
The new comment adds option 4: keep master's buy direction, but estimate the close fee with a limit order at the bid. I checked how wide it is, so whoever decides has the facts. It is narrower than the comment says:
InteractiveBrokersFeeModelwould price that order at its limit price, the bid, which is what master did for the buy.TastytradeFeeModelwould still see a buy-to-close against the short holdings and charge nothing. So both models would give master's assignment results.- Of the six other fee models the comment lists, only
IndiaFeeModelreads the order's price for options. It usesOrder.GetValue, so a buy limit at the bid is valued atmin(bid, Security.Price)instead ofSecurity.Price(LimitOrder.CalculateOrderValue).EtoroFeeModel,PublicFeeModelandWebullFeeModelprice fromSecurity.Price, and Webull's multi-leg check doesn't count a plainLimit.AlpacaFeeModelsplits maker and taker fees only for crypto.ExanteFeeModelcharges options per contract.
So option 4 changes assignment estimates only for India options, and only on their expiry day, because European options are checked only then. Options 1 and 2 each newly assign short options for one brokerage, and option 3 changes how the simulator calls every fee model. Choosing is still a person's call. Whatever they choose, the assignment tests should cover the IB and Tastytrade fee models.
CI is green on this commit (API Tests skipped by its workflow). Nothing private in the diff, commits, description or comments.
Other repositories: QuantConnect/Documentation#2923 still matches the fee-side fix, which every option keeps. It waits on this decision too.
Label: risk:high stays on both pull requests. The approach to the early-assignment simulator is still open, and the current head newly assigns Tastytrade short options.
|
Correction to option 4 in my previous comment: I checked the six fee models against the code and the review is right. Only |
24624d8 to
dc61fd6
Compare
There was a problem hiding this comment.
Requesting changes. Pricing the fees against the counter-party's long position (the approach chosen in the new commits) fixes what I raised last time: Tastytrade now sees a sell-to-close, and the IB and Tastytrade assignment tests pass. The IB quote-side fix still holds. Two problems remain in the new commits, and both are reproduced locally.
-
The stand-in option has no local time, so a custom fee model that reads it now stops the backtest.
CreateCounterPartyOptionbuilds a newOptionthat never gets aLocalTimeKeeper. If a fee model readsparameters.Security.LocalTime, the call now throwsInvalidOperationException("SetLocalTimeKeeper must be called before using LocalTime"). Nothing catches it on the way fromBacktestingBrokerage.Scan→ProcessAssignmentOrders, so the algorithm dies with a runtime error. I added a test with a fee model that readsSecurity.LocalTimeand a short deep-ITM call 3 days before expiry. It throws on this head and passes with master'sDefaultOptionAssignmentModel.cs. The stand-in should carry the option's local time. Don't do that by callingSetLocalTimeKeeperon it, though: that also rewires the cache it shares with the real option. Please add a test that covers it. -
Tastytrade charges $5 twice for one exercise.
BacktestingBrokeragecalls the fee model once for each fill whose fee is zero (BacktestingBrokerage.cs:369-379). An ITM physically settled exercise has two fills, the option and the underlying, and both pass the option security and the same order. I ranOptionExerciseRegressionAlgorithmwithTastytradeFeeModelset on every security. The singleExerciseOptionof 20 puts filled as two events at $5 each, so it cost $10. The schedule is $5, and master charged $0. The fee model can't tell the two fills apart, so the fix needs one of these: charge the exercise fee only on the option fill in the backtesting brokerage, which also changes every other fee model that charges exercises, or leave the flat fee out of this pull request. A person should pick; the test should cover a full exercise, not just a directGetOrderFeecall.
CI is green on this commit (one build job skipped by its workflow). Nothing private in the diff, commits or description.
Other repositories: QuantConnect/Documentation#2923 still matches the IB fee change. The Tastytrade exercise fee may need a line in the Tastytrade fee model docs.
Label: risk:high stays. The change now also alters Tastytrade exercise fees and how the assignment simulator calls every fee model, and both regressions above are live on this head.
| var symbol = option.Symbol; | ||
| var exchangeHours = option.Exchange.Hours; | ||
| var symbolProperties = (OptionSymbolProperties)option.SymbolProperties; | ||
| Option counterPartyOption = option switch |
There was a problem hiding this comment.
This stand-in has no LocalTimeKeeper, so Security.LocalTime throws InvalidOperationException in any fee model that reads it. Master passed the real option, which has local time, so a user fee model that depends on the time of day or the date now ends the backtest in ProcessAssignmentOrders. Reproduced with a test fee model that reads parameters.Security.LocalTime: it throws here and passes with master's assignment model. Don't call SetLocalTimeKeeper on the stand-in, because that also sets the keeper of the option.Cache it shares.
| public override OrderFee GetOrderFee(OrderFeeParameters parameters) | ||
| { | ||
| // an option exercise or assignment is charged a flat fee, whatever its size | ||
| if (parameters.Order.Type == OrderType.OptionExercise) |
There was a problem hiding this comment.
In a backtest, this runs once for each fill of the exercise order (BacktestingBrokerage.cs:369-379). An ITM exercise with physical delivery fills both the option and the underlying, so it costs $10, not $5. OptionExerciseRegressionAlgorithm with this fee model: Type: OptionExercise; Fee: 5 USD on the option fill and again on the AAPL fill, Total Fees $30 = $20 to open plus $5 + $5.
The Interactive Brokers fee model estimated a market, market on open, market on close or combo market option order's premium from the bid for buys and the ask for sells. Buys execute at the ask and sells at the bid, so when the spread straddles a premium threshold the commission was taken from the wrong tier. Use the ask for buys and the bid for sells, and update the regression statistics whose fees change. Closes #10139 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The default option assignment model compares the counter-party closing its long option position at the bid with exercising it, but estimated that close's fee with a buy order. Now that IB option market buys are priced at the ask, that buy could fall in a higher commission tier and trigger an early assignment the sale does not justify. Estimate the fee with the sale it models. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Tastytrade's fee schedule charges $5 for an option exercise or assignment, whatever its size. The fee model had no case for exercise orders, so it charged them the per-contract opening or closing rate depending on the holdings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The assignment simulator models the counter-party closing or exercising its long contracts, but passed the algorithm's option, holding the short side, to the fee model. Fee models that depend on the position, such as Tastytrade's, then saw a sale as opening a position. Estimate both fees against a stand-in of the same option type that shares the option's prices and holds the counter-party's long contracts. The exercise order now carries the holder's change in position, as Lean's exercise orders do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The backtesting brokerage asked the fee model for every fill of an exercise order without a fee. An exercise of a physically settled option fills both the option and the delivered underlying, and both calls got the option security and the same order, so the exercise was charged twice. Delivering the underlying is part of the exercise: only ask the fee model for the option's fill. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The counter-party option was a new security that never got a local time keeper, so a fee model reading Security.LocalTime threw and stopped the backtest. Copy the option instead, with its own holding of the counter-party's position: it keeps the option's type, local time, prices and models without rewiring the cache it shares. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With the double-counted contract unit removed from the exercise estimate, the test's underlying quote no longer put exercising and selling close enough for the close fee's commission tier to decide the assignment. Move the underlying bid so that it does again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
dc61fd6 to
f563da6
Compare
Closes #10139
Description
InteractiveBrokersFeeModel.GetPotentialOrderPriceestimated the premium of market, market on open, market on close and combo market option orders from the bid for buys and the ask for sells. Buys execute at the ask and sells at the bid. When the spread straddles a commission premium threshold ($0.05 or $0.10 in the default tier), the fee came from the wrong tier: a 10-lot buy at 0.09/0.11 was charged $5.00 instead of $6.50. The change uses the ask for buys and the bid for sells, like Lean's other fee models that price from the quote. Limit, stop and combo limit orders are unchanged.DefaultOptionAssignmentModel.EstimateArbitragePnLmodels the counter-party closing or exercising its long contracts. It estimated those fees with a buy order on the algorithm's option, which holds the short side. That only gave IB the bid because of the reversed mapping above. Fee models that read the position, such as Tastytrade's, can't get both trades right from the short side. The simulator now estimates both fees against a copy of the option (Option.WithHoldings) that holds the counter-party's long contracts. The copy keeps the option's type, local time, prices and models, and the algorithm's holdings are not touched. The close is a sale. The exercise order carries the holder's change in position, as Lean's exercise orders do.TastytradeFeeModelhad no case for exercise orders, so it charged them its per-contract open or close rate. Tastytrade's fee schedule (last updated October 28, 2026) charges $5 per option exercise or assignment, which the model now charges.BacktestingBrokerageasked the fee model for every fill of an exercise order. A physically settled exercise fills both the option and the delivered underlying, and both requests passed the option and the same order, so the exercise was charged twice. Delivering the underlying is part of the exercise, so only the option's fill is charged now. This applies to exercises the algorithm requests. Fills from expiration and assignment notifications are emitted with zero fees and are unchanged.How the simulator's fee estimates differ from master:
QuantConnect/Documentation#2923 updates the IB premium table.
Tests
InteractiveBrokersFeeModelTests.USAOptionMarketFeeUsesExecutableSideOfTheSpread: buys and sells ofMarket,MarketOnOpen,MarketOnCloseandComboMarketwith quotes straddling each premium threshold. All 16 cases fail on master.USAOptionFeenow quotes on the ask, which a buy executes at.TastytradeFeeModelTests.ChargesAFlatFeeForOptionExercisesAndAssignments: exercises and assignments of equity and futures options. They fail without the fee model change.TastytradeFeeModelTests.ChargesTheExerciseFeeOnceForAFullExercise: an in-the-money call exercised through the backtesting brokerage costs $5 on the option fill and $0 on the delivered shares. Before the brokerage change, the delivered shares were also charged $5.DefaultOptionAssignmentModelTests.EstimatesFeesAgainstTheCounterPartyPosition, forOption,IndexOptionandFutureOption: a recording fee model checks it is given 10 long contracts of the same option class, with the option's quotes and local time, for a sale and an exercise of 10. The algorithm's holdings stay at -10. It fails with master's simulator, and the local time check failed with this pull request's previous head.DefaultOptionAssignmentModelTests.DoesNotAssignWhenSellingAtTheBidBeatsExercising, for the IB and Tastytrade fee models. The underlying bid makes exercising $0.001 per share worse than selling, so the close fee's commission tier decides. With master's simulator, the IB case prices the close at the ask and assigns 10 contracts.NullMarginComboOrderRegressionAlgorithm,NullMarginMultipleOrdersRegressionAlgorithm(C# and Python),OptionEquityBearCallSpreadRegressionAlgorithm,OptionEquityBearCallSpreadSetHoldingsRegressionAlgorithmandOptionEquityBullCallSpreadRegressionAlgorithm. Only Total Fees, End Equity and, for two of them, Portfolio Turnover change.Locally, on master with #10233 and a Release build on .NET 10:
DefaultOptionAssignmentModelTests,TastytradeFeeModelTests,InteractiveBrokersFeeModelTests,OptionPortfolioModelTestsand the backtesting brokerage tests: 209 passed.CI runs the full unit and regression suites.
🤖 Generated with Claude Code