Skip to content
6 changes: 3 additions & 3 deletions Algorithm.CSharp/NullMarginComboOrderRegressionAlgorithm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ protected override void PlaceTrades(OptionContract optionContract)
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "10000"},
{"End Equity", "10658.5"},
{"End Equity", "10662.5"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
Expand All @@ -70,10 +70,10 @@ protected override void PlaceTrades(OptionContract optionContract)
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$11.50"},
{"Total Fees", "$7.50"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "7580.62%"},
{"Portfolio Turnover", "7577.77%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "06de8022dfcb44c5eb0a2199bd7a7232"}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ protected virtual void AssertState(OrderTicket ticket, int expectedGroupCount, i
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "10000"},
{"End Equity", "10658.5"},
{"End Equity", "10662.5"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
Expand All @@ -158,10 +158,10 @@ protected virtual void AssertState(OrderTicket ticket, int expectedGroupCount, i
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$11.50"},
{"Total Fees", "$7.50"},
{"Estimated Strategy Capacity", "$13000000.00"},
{"Lowest Capacity Asset", "GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "7580.62%"},
{"Portfolio Turnover", "7577.77%"},
{"Drawdown Recovery", "0"},
{"OrderListHash", "4b36a135ed647a66c1ef3f1d9439cf02"}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public override void OnData(Slice slice)
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "200000"},
{"End Equity", "200093.5"},
{"End Equity", "200095.5"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
Expand All @@ -118,7 +118,7 @@ public override void OnData(Slice slice)
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$6.50"},
{"Total Fees", "$4.50"},
{"Estimated Strategy Capacity", "$5400000.00"},
{"Lowest Capacity Asset", "GOOCV WBGM95TALCX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "28.44%"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ public override void OnData(Slice slice)
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "1000000"},
{"End Equity", "998807.85"},
{"End Equity", "998808.15"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
Expand All @@ -117,7 +117,7 @@ public override void OnData(Slice slice)
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$7.15"},
{"Total Fees", "$6.85"},
{"Estimated Strategy Capacity", "$45000000.00"},
{"Lowest Capacity Asset", "GOOCV WBGM95TALCX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "6.17%"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public override void OnData(Slice slice)
{"Drawdown", "0%"},
{"Expectancy", "0"},
{"Start Equity", "200000"},
{"End Equity", "199145.5"},
{"End Equity", "199143.5"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "0"},
{"Sortino Ratio", "0"},
Expand All @@ -114,7 +114,7 @@ public override void OnData(Slice slice)
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$4.50"},
{"Total Fees", "$6.50"},
{"Estimated Strategy Capacity", "$5400000.00"},
{"Lowest Capacity Asset", "GOOCV WBGM95TALCX2|GOOCV VP83T1ZUHROL"},
{"Portfolio Turnover", "28.20%"},
Expand Down
6 changes: 6 additions & 0 deletions Brokerages/Backtesting/BacktestingBrokerage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,12 @@ public virtual void Scan()
// invoke fee models for completely filled order events
foreach (var fill in fills)
{
// an exercise is charged once, on the option's fill: delivering the underlying is part of it
if (order.Type == OrderType.OptionExercise && fill.Symbol != order.Symbol)
{
continue;
}

if (fill.Status == OrderStatus.Filled)
{
// this check is provided for backwards compatibility of older user-defined fill models
Expand Down
4 changes: 2 additions & 2 deletions Common/Orders/Fees/InteractiveBrokersFeeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,11 +237,11 @@ protected static decimal GetPotentialOrderPrice(Order order, Security security)
case OrderType.Market:
if (order.Direction == OrderDirection.Buy)
{
price = security.BidPrice;
price = security.AskPrice;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

}
else
{
price = security.AskPrice;
price = security.BidPrice;
}
break;
case OrderType.ComboLimit:
Expand Down
11 changes: 11 additions & 0 deletions Common/Orders/Fees/TastytradeFeeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ public class TastytradeFeeModel : FeeModel
/// </summary>
private const decimal _optionFeeOpen = 1m;

/// <summary>
/// The fee associated with an option exercise or assignment (per transaction).
/// </summary>
private const decimal _optionExerciseFee = 5m;

/// <summary>
/// The fee associated with futures transactions (per contract).
/// </summary>
Expand All @@ -51,6 +56,12 @@ public class TastytradeFeeModel : FeeModel
/// </returns>
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

{
return new OrderFee(new CashAmount(_optionExerciseFee, Currencies.USD));
}

var feeRate = default(decimal);
switch (parameters.Security.Type)
{
Expand Down
16 changes: 10 additions & 6 deletions Common/Securities/Option/DefaultOptionAssignmentModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,20 +108,24 @@ private static decimal EstimateArbitragePnL(Option option, OptionHolding holding
// it's negative THEIR holdings. holding.Quantity is negative, so if counter-party exercises, they would reduce holdings
var underlyingQuantity = option.GetExerciseQuantity(holding.Quantity);

// Scenario 1 (base): we just close option position
var marketOrder1 = new MarketOrder(option.Symbol, -holding.Quantity, option.LocalTime.ConvertToUtc(option.Exchange.TimeZone));
// fee models that depend on the position have to see the counter-party's long contracts, not the algorithm's short ones
var counterPartyOption = option.WithHoldings(holding.AveragePrice, -holding.Quantity);

// Scenario 1 (base): we just close option position, selling the counter-party's long contracts
var marketOrder1 = new MarketOrder(option.Symbol, holding.Quantity, option.LocalTime.ConvertToUtc(option.Exchange.TimeZone));
Comment thread
quantconnect-kronos-reviewer[bot] marked this conversation as resolved.
Resolved
var orderFee1 = option.FeeModel.GetOrderFee(
new OrderFeeParameters(option, marketOrder1)).Value.Amount * option.QuoteCurrency.ConversionRate;
new OrderFeeParameters(counterPartyOption, marketOrder1)).Value.Amount * option.QuoteCurrency.ConversionRate;

var basePnL = (optionPrice - holding.AveragePrice) * -holding.Quantity
* option.QuoteCurrency.ConversionRate
* option.SymbolProperties.ContractMultiplier
- orderFee1;

// Scenario 2 (alternative): we exercise option and then close underlying position
var optionExerciseOrder2 = new OptionExerciseOrder(option.Symbol, (int)holding.AbsoluteQuantity, option.LocalTime.ConvertToUtc(option.Exchange.TimeZone));
// Scenario 2 (alternative): we exercise option and then close underlying position.
// An exercise order's quantity is the change in the holder's position, so exercising the counter-party's long contracts is negative
var optionExerciseOrder2 = new OptionExerciseOrder(option.Symbol, holding.Quantity, option.LocalTime.ConvertToUtc(option.Exchange.TimeZone));
var optionOrderFee2 = option.FeeModel.GetOrderFee(
new OrderFeeParameters(option, optionExerciseOrder2)).Value.Amount * option.QuoteCurrency.ConversionRate;
new OrderFeeParameters(counterPartyOption, optionExerciseOrder2)).Value.Amount * option.QuoteCurrency.ConversionRate;

var underlyingOrderFee2Amount = 0m;

Expand Down
14 changes: 14 additions & 0 deletions Common/Securities/Option/Option.cs
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,20 @@ public decimal GetExerciseQuantity(decimal exerciseOrderQuantity)
return sign * exerciseOrderQuantity * ContractUnitOfTrade;
}

/// <summary>
/// Creates a copy of this option that holds the given position and shares everything else with it,
/// such as its prices, local time and models
/// </summary>
/// <param name="averagePrice">The average price of the position</param>
/// <param name="quantity">The quantity of the position</param>
internal Option WithHoldings(decimal averagePrice, decimal quantity)
{
var copy = (Option)MemberwiseClone();
copy.Holdings = new OptionHolding(copy, Holdings.CurrencyConverter);
copy.Holdings.SetHoldings(averagePrice, quantity);
return copy;
}

/// <summary>
/// Checks if option is eligible for automatic exercise on expiration
/// </summary>
Expand Down
83 changes: 74 additions & 9 deletions Tests/Brokerages/Tastytrade/TastytradeFeeModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,17 @@
*/

using System;
using System.Linq;
using NUnit.Framework;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Orders.Fees;
using QuantConnect.Data.Market;
using System.Collections.Generic;
using QuantConnect.Tests.Engine;
using QuantConnect.Brokerages.Backtesting;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Tests.Engine.BrokerageTransactionHandlerTests;

namespace QuantConnect.Tests.Brokerages.Tastytrade
{
Expand Down Expand Up @@ -78,7 +84,7 @@ private static IEnumerable<TestCaseData> FeeTestParameters
[Test, TestCaseSource(nameof(FeeTestParameters))]
public void CalculateRightOrderFeeBasedOnSecurity(Symbol symbol, decimal orderQuantity, decimal symbolHoldingQuantity, decimal expectedFeeQuantity)
{
var parameters = GetOrderFeeParameters(symbol, orderQuantity, symbolHoldingQuantity);
var parameters = GetOrderFeeParameters(new MarketOrder(symbol, orderQuantity, DateTime.UtcNow), symbolHoldingQuantity);

var fee = _feeModel.GetOrderFee(parameters);

Expand All @@ -87,20 +93,79 @@ public void CalculateRightOrderFeeBasedOnSecurity(Symbol symbol, decimal orderQu
}

/// <summary>
/// Creates <see cref="OrderFeeParameters"/> using a <see cref="MarketOrder"/> and given
/// symbol and holding quantity.
/// Provides option exercises and assignments of different sizes, as the change in the holder's position.
/// </summary>
/// <param name="symbol">The symbol of the security being ordered.</param>
/// <param name="orderQuantity">The order quantity.</param>
private static IEnumerable<TestCaseData> OptionExerciseTestParameters
{
get
{
var aaplOptionContract = Symbol.CreateOption(Symbols.AAPL, Market.USA, SecurityType.Option.DefaultOptionStyle(), OptionRight.Call, 200m, new DateTime(2025, 06, 20));
yield return new(aaplOptionContract, -1m, 1m);
yield return new(aaplOptionContract, -10m, 10m);
yield return new(aaplOptionContract, 10m, -10m);
var SP500EMini = Symbol.CreateFuture(Futures.Indices.SP500EMini, Market.CME, new DateTime(2025, 06, 20));
var SP500EMini_OptionContract = Symbol.CreateOption(SP500EMini, SP500EMini.ID.Market, SecurityType.FutureOption.DefaultOptionStyle(), OptionRight.Put, 900m, new DateTime(2025, 09, 19));
yield return new(SP500EMini_OptionContract, -10m, 10m);
yield return new(SP500EMini_OptionContract, 10m, -10m);
}
}

[Test, TestCaseSource(nameof(OptionExerciseTestParameters))]
public void ChargesAFlatFeeForOptionExercisesAndAssignments(Symbol symbol, decimal orderQuantity, decimal symbolHoldingQuantity)
{
var parameters = GetOrderFeeParameters(new OptionExerciseOrder(symbol, orderQuantity, DateTime.UtcNow), symbolHoldingQuantity);

var fee = _feeModel.GetOrderFee(parameters);

Assert.AreEqual(5m, fee.Value.Amount);
Assert.AreEqual(Currencies.USD, fee.Value.Currency);
}

[Test]
public void ChargesTheExerciseFeeOnceForAFullExercise()
{
var algorithm = new BrokerageTransactionHandlerTests.TestAlgorithm();
var exerciseTime = new DateTime(2024, 01, 25, 15, 0, 0);
algorithm.SetDateTime(exerciseTime);
var equity = algorithm.AddEquity("SPY");
var option = algorithm.AddOptionContract(Symbol.CreateOption("SPY", Market.USA, OptionStyle.American, OptionRight.Call, 300, exerciseTime.AddDays(4).Date));
option.FeeModel = new TastytradeFeeModel();
option.Holdings.SetHoldings(1m, 10);
equity.SetMarketPrice(new Tick(exerciseTime.ConvertFromUtc(equity.Exchange.TimeZone), equity.Symbol, 400, 400));

var transactionHandler = new BacktestingTransactionHandler();
using var brokerage = new BacktestingBrokerage(algorithm);
transactionHandler.Initialize(algorithm, brokerage, new TestResultHandler());
try
{
algorithm.Transactions.SetOrderProcessor(transactionHandler);
algorithm.Transactions.AddOrder(new SubmitOrderRequest(OrderType.OptionExercise, SecurityType.Option, option.Symbol, -10, 0, 0, exerciseTime, ""));
transactionHandler.ProcessSynchronousEvents();
}
finally
{
transactionHandler.Exit();
}

// the exercise is charged once, on the option's fill, and delivering the shares is part of it
var fills = algorithm.OrderEvents.Where(orderEvent => orderEvent.Status == OrderStatus.Filled).ToList();
Assert.AreEqual(2, fills.Count);
Assert.AreEqual(5m, fills.Single(fill => fill.Symbol == option.Symbol).OrderFee.Value.Amount);
Assert.AreEqual(0m, fills.Single(fill => fill.Symbol == equity.Symbol).OrderFee.Value.Amount);
}

/// <summary>
/// Creates <see cref="OrderFeeParameters"/> for the given order and holding quantity.
/// </summary>
/// <param name="order">The order to get the fee of.</param>
/// <param name="symbolHoldingQuantity">The current holding quantity.</param>
/// <returns>A populated <see cref="OrderFeeParameters"/> object.</returns>
private static OrderFeeParameters GetOrderFeeParameters(Symbol symbol, decimal orderQuantity, decimal symbolHoldingQuantity)
private static OrderFeeParameters GetOrderFeeParameters(Order order, decimal symbolHoldingQuantity)
{
var security = new Security(symbol, null, new Cash("USD", 0m, 1m), SymbolProperties.GetDefault("USD"), null, null, new SecurityCache());
var security = new Security(order.Symbol, null, new Cash("USD", 0m, 1m), SymbolProperties.GetDefault("USD"), null, null, new SecurityCache());
security.Holdings.SetHoldings(100, symbolHoldingQuantity);

var marketOrder = new MarketOrder(symbol, orderQuantity, DateTime.UtcNow);
return new OrderFeeParameters(security, marketOrder);
return new OrderFeeParameters(security, order);
}
}
}
45 changes: 44 additions & 1 deletion Tests/Common/Orders/Fees/InteractiveBrokersFeeModelTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ public void USAOptionFee(OrderType orderType, double price, double expectedFees)
new SecurityCache(),
null
);
security.SetMarketPrice(new Tick(DateTime.UtcNow, security.Symbol, optionPrice, 0));
security.SetMarketPrice(new Tick(DateTime.UtcNow, security.Symbol, 0, optionPrice));
var order = (new Mock<Order>()).Object;
var groupOrderManager = new GroupOrderManager(0, 2, 10);

Expand Down Expand Up @@ -404,6 +404,49 @@ public void USAOptionFee(OrderType orderType, double price, double expectedFees)
Assert.AreEqual((decimal)expectedFees, fee.Value.Amount);
}

[TestCase(OrderType.Market, 10, 0.09, 0.11, 6.5)]
[TestCase(OrderType.Market, -10, 0.09, 0.11, 5)]
[TestCase(OrderType.Market, 10, 0.04, 0.06, 5)]
[TestCase(OrderType.Market, -10, 0.04, 0.06, 2.5)]
[TestCase(OrderType.MarketOnOpen, 10, 0.09, 0.11, 6.5)]
[TestCase(OrderType.MarketOnOpen, -10, 0.09, 0.11, 5)]
[TestCase(OrderType.MarketOnOpen, 10, 0.04, 0.06, 5)]
[TestCase(OrderType.MarketOnOpen, -10, 0.04, 0.06, 2.5)]
[TestCase(OrderType.MarketOnClose, 10, 0.09, 0.11, 6.5)]
[TestCase(OrderType.MarketOnClose, -10, 0.09, 0.11, 5)]
[TestCase(OrderType.MarketOnClose, 10, 0.04, 0.06, 5)]
[TestCase(OrderType.MarketOnClose, -10, 0.04, 0.06, 2.5)]
[TestCase(OrderType.ComboMarket, 10, 0.09, 0.11, 6.5)]
[TestCase(OrderType.ComboMarket, -10, 0.09, 0.11, 5)]
[TestCase(OrderType.ComboMarket, 10, 0.04, 0.06, 5)]
[TestCase(OrderType.ComboMarket, -10, 0.04, 0.06, 2.5)]
public void USAOptionMarketFeeUsesExecutableSideOfTheSpread(OrderType orderType, int quantity, double bidPrice, double askPrice, double expectedFee)
{
var security = new Option(Symbols.SPY_C_192_Feb19_2016,
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
new Cash("USD", 0, 0),
new OptionSymbolProperties(SymbolProperties.GetDefault("USD")),
ErrorCurrencyConverter.Instance,
RegisteredSecurityDataTypesProvider.Null,
new SecurityCache(),
null
);
security.SetMarketPrice(new Tick(DateTime.UtcNow, security.Symbol, (decimal)bidPrice, (decimal)askPrice));

Order order = orderType switch
{
OrderType.MarketOnOpen => new MarketOnOpenOrder(security.Symbol, quantity, DateTime.UtcNow),
OrderType.MarketOnClose => new MarketOnCloseOrder(security.Symbol, quantity, DateTime.UtcNow),
OrderType.ComboMarket => new ComboMarketOrder(security.Symbol, quantity, DateTime.UtcNow, new GroupOrderManager(0, 1, quantity)),
_ => new MarketOrder(security.Symbol, quantity, DateTime.UtcNow)
};

var fee = _feeModel.GetOrderFee(new OrderFeeParameters(security, order));

Assert.AreEqual(Currencies.USD, fee.Value.Currency);
Assert.AreEqual((decimal)expectedFee, fee.Value.Amount);
}

[Test]
public void USAOptionMinimumFee()
{
Expand Down
Loading
Loading