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 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions Algorithm.CSharp/InteractiveBrokersTieredFeeModelAlgorithm.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
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 InteractiveBrokersTieredFeeModel _feeModel = new InteractiveBrokersTieredFeeModel();
private decimal _monthlyTradedVolume = 0m;

/// <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)
{
SetHoldings(_spy, 0.1m);
MarketOnOpenOrder(_aig, 30000);
MarketOnOpenOrder(_bac, 30000);
}
else if (slice.Time.Hour == 10 && slice.Time.Minute == 0)
{
SetHoldings(_spy, 0.2m);
MarketOrder(_aig, 30000);
MarketOrder(_bac, 30000);
}
else if (slice.Time.Hour == 15 && slice.Time.Minute == 30)
{
SetHoldings(_spy, 0m);
MarketOnCloseOrder(_aig, -60000);
MarketOnCloseOrder(_bac, -60000);
}
}

public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status == OrderStatus.Filled)
{
// Assert if the monthly traded volume is correct in the fee model.
_monthlyTradedVolume += orderEvent.AbsoluteFillQuantity;
// Month volume will update only at the next scan, so we add this fill quantity.
var modelTradedVolume = _feeModel.MonthTradedVolume[SecurityType.Equity] + orderEvent.AbsoluteFillQuantity;
if (_monthlyTradedVolume != modelTradedVolume)
{
throw new Exception($"Monthly traded volume is incorrect - Actual: {_monthlyTradedVolume} - Model: {modelTradedVolume}");
}
}
}

/// <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.02%"},
{"Average Loss", "-0.05%"},
{"Compounding Annual Return", "-26.786%"},
{"Drawdown", "0.600%"},
{"Expectancy", "-0.658"},
{"Start Equity", "1000000000"},
{"End Equity", "996730872.35"},
{"Net Profit", "-0.327%"},
{"Sharpe Ratio", "-7.559"},
{"Sortino Ratio", "-9.624"},
{"Probabilistic Sharpe Ratio", "0%"},
{"Loss Rate", "75%"},
{"Win Rate", "25%"},
{"Profit-Loss Ratio", "0.37"},
{"Alpha", "-0.358"},
{"Beta", "0.098"},
{"Annual Standard Deviation", "0.027"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-7.11"},
{"Tracking Error", "0.245"},
{"Treynor Ratio", "-2.105"},
{"Total Fees", "$4126697.73"},
{"Estimated Strategy Capacity", "$180000000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Portfolio Turnover", "40.56%"},
{"OrderListHash", "bd43a7c7f61e734a7dbc06180af8fc36"}
};
}
}
59 changes: 59 additions & 0 deletions Algorithm.Python/InteractiveBrokersTieredFeeModelAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# 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 *
from Orders.Fees.InteractiveBrokersTieredFeeModel import InteractiveBrokersTieredFeeModel

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

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.set_holdings(self.spy, 0.1)
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.set_holdings(self.spy, 0.2)
self.market_order(self.aig, 30000)
self.market_order(self.bac, 30000)
elif slice.time.hour == 15 and slice.time.minute == 30:
self.set_holdings(self.spy, 0)
self.market_on_close_order(self.aig, -60000)
self.market_on_close_order(self.bac, -60000)

def on_order_event(self, order_event: OrderEvent) -> None:
if order_event.status == OrderStatus.FILLED:
# Assert if the monthly traded volume is correct in the fee model.
self.monthly_traded_volume += order_event.absolute_fill_quantity
# Month volume will update only at the next scan, so we add this fill quantity.
model_traded_volume = self.fee_model.monthly_trade_volume[SecurityType.EQUITY] + order_event.absolute_fill_quantity
if self.monthly_traded_volume != model_traded_volume:
raise Exception(f"Monthly traded volume is incorrect - Actual: {self.monthly_traded_volume} - Model: {model_traded_volume}")
Loading