Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add IB Tiered Fee Model #8446

Open
wants to merge 17 commits into
base: master
Choose a base branch
from
Open
130 changes: 130 additions & 0 deletions Algorithm.CSharp/InteractiveBrokersTieredFeeModelAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/*
* 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.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders.Fees;

namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Test algorithm using <see cref="InteractiveBrokersTieredFeeModel"/>
/// </summary>
public class InteractiveBrokersTieredFeeModelAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy, _aig, _bac;
private IFeeModel _feeModel = new InteractiveBrokersTieredFeeModel();

/// <summary>
/// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.
/// </summary>
public override void Initialize()
{
SetStartDate(2013, 10, 7); //Set Start Date
SetEndDate(2013, 10, 10); //Set End Date
SetCash(1000000000); //Set Strategy Cash

// Set the fee model to be shared by all securities to accurately track the volume/value traded to select the correct tiered fee structure.
SetSecurityInitializer((security) => security.SetFeeModel(_feeModel));

_spy = AddEquity("SPY", Resolution.Minute, extendedMarketHours: true).Symbol;
_aig = AddEquity("AIG", Resolution.Minute, extendedMarketHours: true).Symbol;
_bac = AddEquity("BAC", Resolution.Minute, extendedMarketHours: true).Symbol;
}

public override void OnData(Slice slice)
{
// Order at different time for various order type to elicit different fee structure.
if (slice.Time.Hour == 9 && slice.Time.Minute == 0)
{
MarketOnOpenOrder(_spy, 30000);
MarketOnOpenOrder(_aig, 30000);
MarketOnOpenOrder(_bac, 30000);
Comment on lines +53 to +55
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are these orders filled on the next day or right away? If the latest, might as well use MarketOrder? Same for the MarketOnClose ones

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

They should be filled right away at 9:30am, same for market on close at 4pm

}
else if (slice.Time.Hour == 10 && slice.Time.Minute == 0)
{
MarketOrder(_spy, 30000);
MarketOrder(_aig, 30000);
MarketOrder(_bac, 30000);
}
else if (slice.Time.Hour == 15 && slice.Time.Minute == 30)
{
MarketOnCloseOrder(_spy, -60000);
MarketOnCloseOrder(_aig, -60000);
MarketOnCloseOrder(_bac, -60000);
}
}

/// <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, Language.Python };

/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
public long DataPoints => 23076;

/// <summary>
/// Data Points count of the algorithm history
/// </summary>
public int AlgorithmHistoryDataPoints => 0;

/// <summary>
/// Final status of the algorithm
/// </summary>
public 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 Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Orders", "36"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-2.237%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-0.486"},
{"Start Equity", "1000000000"},
{"End Equity", "999762433.94"},
{"Net Profit", "-0.024%"},
{"Sharpe Ratio", "-8.397"},
{"Sortino Ratio", "-11.384"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "75%"},
{"Win Rate", "25%"},
{"Profit-Loss Ratio", "1.06"},
{"Alpha", "-0.035"},
{"Beta", "0.009"},
{"Annual Standard Deviation", "0.003"},
{"Annual Variance", "0"},
{"Information Ratio", "-5.78"},
{"Tracking Error", "0.269"},
{"Treynor Ratio", "-2.319"},
{"Total Fees", "$185772.29"},
{"Estimated Strategy Capacity", "$11000000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Portfolio Turnover", "2.37%"},
{"OrderListHash", "d35a4e91c145a100d4bffb7c0fc0ff35"}
};
}
}
48 changes: 48 additions & 0 deletions Algorithm.Python/InteractiveBrokersTieredFeeModelAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# 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.

from AlgorithmImports import *

### <summary>
### Test algorithm using "InteractiveBrokersTieredFeeModel"
### </summary>
class InteractiveBrokersTieredFeeModelAlgorithm(QCAlgorithm):
fee_model = InteractiveBrokersTieredFeeModel()

def initialize(self):
''' Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''
self.set_start_date(2013, 10, 7) #Set Start Date
self.set_end_date(2013, 10, 10) #Set End Date
self.set_cash(1000000000) #Set Strategy Cash

# Set the fee model to be shared by all securities to accurately track the volume/value traded to select the correct tiered fee structure.
self.set_security_initializer(lambda security: security.set_fee_model(self.fee_model))

self.spy = self.add_equity("SPY", Resolution.MINUTE, extended_market_hours=True).symbol
self.aig = self.add_equity("AIG", Resolution.MINUTE, extended_market_hours=True).symbol
self.bac = self.add_equity("BAC", Resolution.MINUTE, extended_market_hours=True).symbol

def on_data(self, slice: Slice) -> None:
# Order at different time for various order type to elicit different fee structure.
if slice.time.hour == 9 and slice.time.minute == 0:
self.market_on_open_order(self.spy, 30000)
self.market_on_open_order(self.aig, 30000)
self.market_on_open_order(self.bac, 30000)
elif slice.time.hour == 10 and slice.time.minute == 0:
self.market_order(self.spy, 30000)
self.market_order(self.aig, 30000)
self.market_order(self.bac, 30000)
elif slice.time.hour == 15 and slice.time.minute == 30:
self.market_on_close_order(self.spy, -60000)
self.market_on_close_order(self.aig, -60000)
self.market_on_close_order(self.bac, -60000)
61 changes: 56 additions & 5 deletions Common/Orders/Fees/InteractiveBrokersFeeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@ namespace QuantConnect.Orders.Fees
/// </summary>
public class InteractiveBrokersFeeModel : FeeModel
{
private const decimal CryptoMinimumOrderFee = 1.75m;
private readonly decimal _forexCommissionRate;
private readonly decimal _forexMinimumOrderFee;
private readonly decimal _cryptoCommissionRate;

// option commission function takes number of contracts and the size of the option premium and returns total commission
private readonly Dictionary<string, Func<decimal, decimal, CashAmount>> _optionFee =
new Dictionary<string, Func<decimal, decimal, CashAmount>>();
// List of Option exchanges susceptible to pay ORF regulatory fee.
private readonly List<string> _optionExchangesOrfFee = new() { Market.CBOE, Market.USA };

#pragma warning disable CS1570
/// <summary>
Expand All @@ -51,13 +55,15 @@ public class InteractiveBrokersFeeModel : FeeModel
/// </summary>
/// <param name="monthlyForexTradeAmountInUSDollars">Monthly FX dollar volume traded</param>
/// <param name="monthlyOptionsTradeAmountInContracts">Monthly options contracts traded</param>
public InteractiveBrokersFeeModel(decimal monthlyForexTradeAmountInUSDollars = 0, decimal monthlyOptionsTradeAmountInContracts = 0)
/// <param name="monthlyCryptoTradeAmountInUSDollars">Monthly Crypto dollar volume traded (in USD)</param>
public InteractiveBrokersFeeModel(decimal monthlyForexTradeAmountInUSDollars = 0, decimal monthlyOptionsTradeAmountInContracts = 0, decimal monthlyCryptoTradeAmountInUSDollars = 0)
{
ProcessForexRateSchedule(monthlyForexTradeAmountInUSDollars, out _forexCommissionRate, out _forexMinimumOrderFee);
Func<decimal, decimal, CashAmount> optionsCommissionFunc;
ProcessOptionsRateSchedule(monthlyOptionsTradeAmountInContracts, out optionsCommissionFunc);
// only USA for now
_optionFee.Add(Market.USA, optionsCommissionFunc);
ProcessCryptoRateSchedule(monthlyCryptoTradeAmountInUSDollars, out _cryptoCommissionRate);
}

/// <summary>
Expand Down Expand Up @@ -109,7 +115,15 @@ public override OrderFee GetOrderFee(OrderFeeParameters parameters)
}
// applying commission function to the order
var optionFee = optionsCommissionFunc(quantity, GetPotentialOrderPrice(order, security));
feeResult = optionFee.Amount;
// Regulatory Fee: Options Regulatory Fee (ORF) + FINRA Consolidated Audit Trail Fees
var regulatory = _optionExchangesOrfFee.Contains(market) ?
(0.01915m + 0.0048m) * quantity :
0.0048m * quantity;
// Transaction Fees: SEC Transaction Fee + FINRA Trading Activity Fee (only charge on sell)
var transaction = order.Quantity < 0 ? 0.0000278m * Math.Abs(order.GetValue(security)) + 0.00279m * quantity : 0m;
// Clearing Fee
var clearing = Math.Min(0.02m * quantity, 55m);
feeResult = optionFee.Amount + regulatory + transaction + clearing;
feeCurrency = optionFee.Currency;
break;

Expand Down Expand Up @@ -165,9 +179,16 @@ public override OrderFee GetOrderFee(OrderFeeParameters parameters)
tradeFee = maximumPerOrder;
}

// FINRA Trading Activity Fee only applies to sale of security.
var finraTradingActivityFee = order.Quantity < 0 ? Math.Min(8.3m, quantity * 0.000166m) : 0m;
// Regulatory Fees.
var regulatoryFee = tradeValue * 0.0000278m // SEC Transaction Fee
+ finraTradingActivityFee // FINRA Trading Activity Fee
+ quantity * 0.000048m; // FINRA Consolidated Audit Trail Fees

feeCurrency = equityFee.Currency;
//Always return a positive fee.
feeResult = Math.Abs(tradeFee);
feeResult = Math.Abs(tradeFee + regulatoryFee);
break;

case SecurityType.Cfd:
Expand All @@ -183,6 +204,16 @@ public override OrderFee GetOrderFee(OrderFeeParameters parameters)
};
feeResult = Math.Max(feeResult, minimumFee);
break;

case SecurityType.Crypto:
// get the total trade value in the USD
var totalTradeValue = order.GetValue(security);
var cryptoFee = Math.Abs(_cryptoCommissionRate*totalTradeValue);
// 1% maximum fee
feeResult = Math.Max(Math.Min(totalTradeValue * 0.01m, CryptoMinimumOrderFee), cryptoFee);
// IB Crypto fees are all in USD
feeCurrency = Currencies.USD;
break;

default:
// unsupported security type
Expand Down Expand Up @@ -343,8 +374,8 @@ private static CashAmount UnitedStatesFutureFees(Security security)
exchangeFeePerContract = 1.60m;
}

// Add exchange fees + IBKR regulatory fee (0.02)
return new CashAmount(ibFeePerContract + exchangeFeePerContract + 0.02m, Currencies.USD);
// Add exchange fees
return new CashAmount(ibFeePerContract + exchangeFeePerContract, Currencies.USD);
}

/// <summary>
Expand Down Expand Up @@ -498,5 +529,25 @@ public EquityFee(string currency,
MaximumFeeRate = maximumFeeRate;
}
}

/// <summary>
/// Determines which tier an account falls into based on the monthly trading volume of cryptos
/// </summary>
/// <remarks>https://www.interactivebrokers.com/en/pricing/commissions-cryptocurrencies.php?re=amer</remarks>
private static void ProcessCryptoRateSchedule(decimal monthlyCryptoTradeAmountInUSDollars, out decimal commissionRate)
{
if (monthlyCryptoTradeAmountInUSDollars <= 100000)
{
commissionRate = 0.0018m;
}
else if (monthlyCryptoTradeAmountInUSDollars <= 1000000)
{
commissionRate = 0.0015m;
}
else
{
commissionRate = 0.0012m;
}
}
}
}
Loading