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

Adds Futures Options Asset Class w/ IB Support #4928

Conversation

gsalaz98
Copy link
Contributor

Description

Adds Futures Options support to Lean.
We managed to avoid adding a new SecurityType entry to Lean and instead used the existing SecurityType.Option to represent futures options.

The difference however, is that the futures options Symbol will have the underlying contract (not the canonical future) as its underlying, rather than an equity. We make changes to the brokerages and other misc. classes to ensure that the assumption that an option carries an underlying equity is not applied across the code base.

  • Adds related APIs to add Future Options data to QCAlgorithm
  • Adds IB support for Futures Options
  • Fixes bug in options data loading from disk
  • Adjusts various methods in Lean to support Futures Options
  • Adds FutureOptionMarginModel
  • Adds LiveOptionChainProvider path for futures options (CME traded assets only for now)
  • Adds unit tests, regression algorithms, and test data

Note: I think we'll need to add more MHDB entries before we merge this.

Related Issue

N/A

Motivation and Context

Extend Lean asset class support

Requires Documentation Change

Yes

How Has This Been Tested?

Added unit tests, regression tests, IB paper trading, manual backtesting, manual results verification

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • Refactor (non-breaking change which improves implementation)
  • Performance (non-breaking change which improves performance. Please add associated performance test and results)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Non-functional change (xml comments/documentation/etc)

Checklist:

  • My code follows the code style of this project.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.
  • My branch follows the naming convention bug-<issue#>-<description> or feature-<issue#>-<description>

Copy link
Member

@Martin-Molinero Martin-Molinero left a comment

Choose a reason for hiding this comment

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

Awesome work @gsalaz98! 💪 great feature for Lean.
Sweet regression tests too, they really expose the expected behavior for options.

Leaving a range of different comment types nit/concerns/request/etc.

I think if we could use data of a FOP that already expired we can remove AAPL and the date hack from the regression algos.

@gsalaz98 gsalaz98 force-pushed the feature-qcalgorithm-futureoption-api branch from 2a5f77f to cc9d8cc Compare November 17, 2020 01:03
Copy link
Member

@Martin-Molinero Martin-Molinero left a comment

Choose a reason for hiding this comment

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

Nice work! Minor comments, looks good

@gsalaz98 gsalaz98 force-pushed the feature-qcalgorithm-futureoption-api branch from 281ed6f to 863eae0 Compare November 20, 2020 19:17
Copy link
Member

@Martin-Molinero Martin-Molinero left a comment

Choose a reason for hiding this comment

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

Leaving minor finds ✔️, nice work @gsalaz98! 🚀

Engine/DataFeeds/Enumerators/DelistingEventProvider.cs Outdated Show resolved Hide resolved
Data/market-hours/market-hours-database.json Outdated Show resolved Hide resolved
@gsalaz98 gsalaz98 force-pushed the feature-qcalgorithm-futureoption-api branch from 3998774 to 96584e6 Compare November 24, 2020 00:05
Copy link
Member

@jaredbroad jaredbroad left a comment

Choose a reason for hiding this comment

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

Needs a refactor for FutureOptions to be a security type to remove all the branching.

@gsalaz98 gsalaz98 force-pushed the feature-qcalgorithm-futureoption-api branch from 34906b8 to 1208bf2 Compare December 1, 2020 01:37
Copy link
Member

@Martin-Molinero Martin-Molinero left a comment

Choose a reason for hiding this comment

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

Cool! minor comments

Common/Securities/SecurityService.cs Show resolved Hide resolved
Common/Securities/SymbolPropertiesDatabase.cs Outdated Show resolved Hide resolved
Common/SecurityIdentifier.cs Outdated Show resolved Hide resolved
Common/Symbol.cs Outdated Show resolved Hide resolved
Common/Securities/SecurityService.cs Show resolved Hide resolved
Copy link
Member

@jaredbroad jaredbroad left a comment

Choose a reason for hiding this comment

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

Symbol canonicalSymbol;
var alias = "?" + underlying;
var alias = "?" + underlying.Value;
Copy link
Member

Choose a reason for hiding this comment

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

I wonder if we should have a new character for FO vs EO canonical tickers.

tradeBar.High = streamReader.GetDecimal() * _scaleFactor;
tradeBar.Low = streamReader.GetDecimal() * _scaleFactor;
tradeBar.Close = streamReader.GetDecimal() * _scaleFactor;
var scalingFactor = GetScaleFactor(config.Symbol);
Copy link
Member

Choose a reason for hiding this comment

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

Maybe aggressive inlining given its hit 50B times?

@@ -56,9 +56,9 @@ public SubscriptionDataConfigList(Symbol symbol)
/// <param name="normalizationMode"></param>
public void SetDataNormalizationMode(DataNormalizationMode normalizationMode)
{
if (Symbol.SecurityType == SecurityType.Option && normalizationMode != DataNormalizationMode.Raw)
if ((Symbol.SecurityType == SecurityType.Option || Symbol.SecurityType == SecurityType.FutureOption) && normalizationMode != DataNormalizationMode.Raw)
Copy link
Member

Choose a reason for hiding this comment

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

Not sure relevant with futures?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think Futures is default Raw data normalization, no errors being thrown on my end

Common/Global.cs Show resolved Hide resolved
Common/Securities/MarketHoursDatabase.cs Outdated Show resolved Hide resolved
// we also exclude futures and CFD as they are calculated separately
// We can't include forex in this calculation since we would be double accounting with respect to the cash book
// We also exclude futures and CFD as they are calculated separately because they do not impact the account's cash.
// We include futures options as part of this calculation because IB chooses to change our account's cash balance
Copy link
Member

Choose a reason for hiding this comment

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

uf. any idea why?

Copy link
Contributor Author

@gsalaz98 gsalaz98 Dec 2, 2020

Choose a reason for hiding this comment

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

I believe CME says that futures options are cash settled, but call/put writing requires margin and has a initial/maintenance margin

Edit: https://www.cmegroup.com/education/courses/introduction-to-options/introduction-to-options.html

Comment on lines +71 to +76
// We decide to use the ZipDataCacheProvider instead of the SingleEntryDataCacheProvider here
// for resiliency and as a fix for an issue preventing us from reading non-equity options data.
// It has the added benefit of caching any zip files that we request from the filesystem, and reading
// files contained within the zip file, which the SingleEntryDataCacheProvider does not support.
var sourceFactory = request.Configuration.GetBaseDataInstance();

using (var dataCacheProvider = new SingleEntryDataCacheProvider(dataProvider))
using (var dataCacheProvider = new ZipDataCacheProvider(dataProvider))
Copy link
Member

Choose a reason for hiding this comment

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

I think this will have other implications later but I can't remember them precisely. This might have been done to reduce the RAM used?

  * Fixes bug where Equity Symbol was created for an underlying
    non-equity Symbol, resulting in equity data trying to be loaded

  * Adds unit tests covering changes to Tick, QuoteBar, TradeBar and
    LeanData

  * Adds regression test for AddUniverseOption filter contract selection
    for Future Options
  * Adds new AddUniverseOptions method overload
  * Removes and adds a new unit test
  * Misc. modifications to account for new changes
  * Refactors and removes unnecessary work
  * Fixes regression algorithm, which previously made no trades
  * Adds the corresponding underlying data, in this case, futures data
    to enable usage of future options data
  * Extra changes made to remove scaling from writing CSV
  * Added method to map from FOP Globex -> FUT Globex
  * Note: this order type might not be supported by IB or CME.
…nges

2. Address review (partial): Code reuse and cleanup

1.
  * Modifies check in
    `AddFutureOptionShort(Call|Put)ITMExpiryRegressionAlgorithm`
    to ensure no buys have negative quantity

  * Code reuse changes in IB brokerage

  * Bug fix in IB brokerage where we assigned the FOP expiry
    as the futures expiry (requires verification)

  * Doc changes and adds missing summaries/license banners
  * Disposes of HTTP client resources in LiveOptionChainProvider
  * Renames classes and adds FutureOption folder in Common/Securities

2.
  * We revert back to the quotes API for the option chain,
    since the settlement API sometimes had missing strikes.

  * Fixes future option expiry being set as future's expiry
    in LiveOptionChainProvider

  * Fixes bug where wrong option chain was selected because of bad
    expiry lookup in the futures expiries returned from CME

  * Fixes multiple looping bug in LiveOptionChainProvider
  * Adds strike price scaling for LiveOptionChainProvider

  * Reverts IQFeed changes and simplifies interface upgrade changes

  Some additional challenges we'll have to solve as part of FOPs:

    - The `OptionSymbol.IsStandard` method makes the assumption that
      weeklies contracts follow the pattern equities follows, which
      does not apply to Futures Options

    - The Subscription created in:
        `OptionChainUniverseSubscriptionEnumeratorFactory`

      ...adds a Trade config. For illiquid contracts, this
      will delay universe selection for the option symbol
      until we get a trade. However, if we add a quote config,
      the data would instead be loaded based on the first quote
      we received from the brokerage.

      But since we're currently using a trade config, illiquid
      contracts won't start streaming data until it receives a trade.

NOTE: this commit is a WIP to addressing the reviews received in the PR,
but has been committed early for efficiency in the review process
  * Fixes map file lookup for non-equity options
  * Adds extra assertion at end of algorithm to ensure no holdings are
    left when the algorithm ends.

  * Adds FutureOptionSymbol, allowing all contracts through as standard
  * Changes SPDB to allow defaulting to underlying future symbol
    properties if no entry is found for the given FOP

  * Fixes calls to SPDB in SecurityService, IBBrokerage
  * Reverts AAPL daily ZIP file to fix majority of regression algorithms
  * Adds FOPs symbol properties
  * Fixes existing symbol properties for a few futures
  * Adds tests for changes to Symbol Properties Database
  * Updates tests and misc callees of previous method
  * Adds Futures Options Expiry Functions tests
  * Adds required futures data for 2020-01-05
  * Bug fix in MarketHoursDatabase.GetDatabaseSymbolKey() where
    we would use the underlying's Symbol for lookup in the MHDB

  * Adds missing license banner
  * Removes Futures Options entries from MHDB
  * Adds new tests
  * Converts any underlying comparisons and uses SecurityType directly
    instead for FOP specific behavior

  * Extra code modifications to acommodate new SecurityType
  * Additional bug fixes and adding of SecurityType.FutureOption
  * Updates regression algorithms OrderListHash
  * Fixes bug setting the right contract expiration date for FOP
    generated by LiveOptionChainProvider

  * Adds new function to FuturesOptionsExpiryFunctions

  * Clarifies parameter names better in some functions/methods

  * Fixes bugs in IB brokerage for FOPs
  * Remove MappingEventProvider, SplitEventProvider, and
    DividendEventProvider for Futures Options in
    CorporateEventEnumeratorFactory
@gsalaz98 gsalaz98 force-pushed the feature-qcalgorithm-futureoption-api branch from 39ba061 to a8df933 Compare December 3, 2020 00:11
@Martin-Molinero Martin-Molinero merged commit eb1181f into QuantConnect:master Dec 3, 2020
jaredbroad added a commit that referenced this pull request Jan 5, 2021
* Update QCAlgorithm.Plotting.cs

Increased maximum number of series that can be plotted in backtest from 10 to 30

* Market Hours Database Adjustment (#4818)

* Fix Entries

* Fix options dates

* Don't raise IBrokerage.OptionPositionAssigned on exercise (#4801)

* Fix `DirectoryNotFoundException` on linux/mac (#4829)

* Rename QuantConnect.API to QuantConnect.Api (#4830)

Also renames API folders to Api

* Test 4249 fix regression algorithms executed together (#4832)

* Fix for running regressions algorithms together

* Remove unneeded changes

* Refactor OptionExerciseOrder.Quantity to be consistent with other Order types (#4796)

* Improve information tracked in regression's {algorithm}.{lang}.details.log

The details.log file aims at providing a diff-able document that quickly and
easily provides actionable information. Since many regression algorithms use
the algorithm's debug/error messaging facilities to log various pieces of algo
state. This document also support a configuration option: regression-high-fidelity-logging'
that logs EVERY piece of data, again, with the aim of providing an easily diff-able
documenbt to quickly highlight actionable information. I may have missed omse key
pieces of information here, but now that the entire QC knows about this regression
tool, if additional information is required then hopefully it's easy enough at this
point to extend the RegressionResultHandler to suit our needs.

The RegressionResultHandler was initially implemented to provide a concise log of
all orders. This was achieved by simply using the Order.ToString method. While
testing/investigating OptionExerciseOrder behavior, it became evident that more
information was required to properly identify the source of potential failures or
differences between previous regression test runs. This change adds logging for
almost every IResultHandler method and additionally attempts to capture the
actual portfolio impact of every OrderEvent. This is accomplished by logging
the portfolio's TotalPortfolioValue, Cash properties and the security's
SecurityHolding.Quantity property.

This change also standardizes the timestamps used to folloow the ISO-8601 format.

When using the RegressionResultHandler, it is highly recommeded to also disable
'forward-console-message' configuration option to ensure algorithm Debug/Error
message logging is done synchronously to ensure correct ordering with respect to
log messages via Log.Debug/Trace/Error.

* Fix typo in options OrderTests test case name

* Update SymbolRepresentation.GenerationOptionTickerOSI to extension method

Far more convenient as an extension method

* Improve R# default code formatting rules

Many of these rule changes focus on improving the readability of code,
with a particular emphasis on multi-line constructs, chained method calls
and multi-line method invocations/declarations.

* Add braces, use string interpolation and limit long lines

* Refactor OptionExerciseOrder.Quantity to indicate change in #contracts

For all other order types, the Order.Quantity indicates the change in the algorithm's
holdings upon order execution for the order's symbol. For OptionExerciseOrder, this
convention was broken. It appears as though only exercise was initially implemented,
in which case only long positions were supported and a code comment indicated that
only positive values of quantity were acceptable, indicating the number of contracts
to exercise. At a later date, assignment simulation was added and utilized a negative
order quantity. This caused some major inconsistencies in how models view exercise
orders compared to all other order types. This change brings OptionExerciseOrder.Quantity
into alignment with the other order types by making it represent the change in holdings
quantity upon order execution.

This change was originally going to be much larger, but in order to minimize risks and to
make for an easier review experience, the additional changes will be committed separately
and pushed in their own PR. Some of the issues identified include:
* Manual Exercise (especially for OTM) is not covered
* Margin Calculations (in particular taking into account opposing contracts held)
* IBrokerage.OptionPositionAssigned is raised for exercise (later filtered by tx handler)

Fixes OptionPortfolioModelTests to use exercise model to properly model exercise of
non-account quote currency option contract.

* Include Order.Tag/OrderEvent.Message in their ToString, Fix default tag values (#4797)

* Improve information tracked in regression's {algorithm}.{lang}.details.log

The details.log file aims at providing a diff-able document that quickly and
easily provides actionable information. Since many regression algorithms use
the algorithm's debug/error messaging facilities to log various pieces of algo
state. This document also support a configuration option: regression-high-fidelity-logging'
that logs EVERY piece of data, again, with the aim of providing an easily diff-able
documenbt to quickly highlight actionable information. I may have missed omse key
pieces of information here, but now that the entire QC knows about this regression
tool, if additional information is required then hopefully it's easy enough at this
point to extend the RegressionResultHandler to suit our needs.

The RegressionResultHandler was initially implemented to provide a concise log of
all orders. This was achieved by simply using the Order.ToString method. While
testing/investigating OptionExerciseOrder behavior, it became evident that more
information was required to properly identify the source of potential failures or
differences between previous regression test runs. This change adds logging for
almost every IResultHandler method and additionally attempts to capture the
actual portfolio impact of every OrderEvent. This is accomplished by logging
the portfolio's TotalPortfolioValue, Cash properties and the security's
SecurityHolding.Quantity property.

This change also standardizes the timestamps used to folloow the ISO-8601 format.

When using the RegressionResultHandler, it is highly recommeded to also disable
'forward-console-message' configuration option to ensure algorithm Debug/Error
message logging is done synchronously to ensure correct ordering with respect to
log messages via Log.Debug/Trace/Error.

* Fix typo in options OrderTests test case name

* Update SymbolRepresentation.GenerationOptionTickerOSI to extension method

Far more convenient as an extension method

* Improve R# default code formatting rules

Many of these rule changes focus on improving the readability of code,
with a particular emphasis on multi-line constructs, chained method calls
and multi-line method invocations/declarations.

* Add braces, use string interpolation and limit long lines

* Refactor OptionExerciseOrder.Quantity to indicate change in #contracts

For all other order types, the Order.Quantity indicates the change in the algorithm's
holdings upon order execution for the order's symbol. For OptionExerciseOrder, this
convention was broken. It appears as though only exercise was initially implemented,
in which case only long positions were supported and a code comment indicated that
only positive values of quantity were acceptable, indicating the number of contracts
to exercise. At a later date, assignment simulation was added and utilized a negative
order quantity. This caused some major inconsistencies in how models view exercise
orders compared to all other order types. This change brings OptionExerciseOrder.Quantity
into alignment with the other order types by making it represent the change in holdings
quantity upon order execution.

This change was originally going to be much larger, but in order to minimize risks and to
make for an easier review experience, the additional changes will be committed separately
and pushed in their own PR. Some of the issues identified include:
* Manual Exercise (especially for OTM) is not covered
* Margin Calculations (in particular taking into account opposing contracts held)
* IBrokerage.OptionPositionAssigned is raised for exercise (later filtered by tx handler)

Fixes OptionPortfolioModelTests to use exercise model to properly model exercise of
non-account quote currency option contract.

* Include Order.Tag/OrderEvent.Message in their ToString, Fix default tag values

There was inconsistencies in what we were checking for. The order constructors
default the tag parameter to an empty string but Order.CreateOrder checks for
a null string. Additionally, the order constructors (limit,stopmarket,stoplimit)
would check for an empty string and if so, apply a default order tag.

This change cleans these checks up using string.IsNullOrEmpty and also removes the
check from Order.CreateOrder since we're passing the tag into the various order
constructors.

* Set Account Base Currency from Brokerage in Live Mode (#4806)

* Add property IBrokerage.AccountBaseCurrency

* Set AccountCurrency to brokerage AccountBaseCurrency

* Remove USD AccountCurrency check

* Fix Oanda account base currency

* Fix currency symbol in CashBook.ToString()

* Fix unit tests

* Address review

* Add DebugMessage when changing account currency

* Add debug message for brokerage account base currency

* Fix currency symbol in equity chart and runtime statistics

* Update unit tests

* OptionChain and OptionContract improvements (#4804)

* OptionChain and OptionContract improvements

- QCAlgorithm.AddUniverse will return the added Universe instance.
- Adding new OptionChainedUniverseSelectionModel will monitor a Universe changes
  and will spwan new OptionChainUniverse from it's selections. Adding
  regression test Py/C#.
- Adding new OptionContractUniverse that will own option contracts and
  their underlying symbol. Adding regression test
- Fix double notification for security changes, bug seen in updated
  UniverseSelectionRegressionAlgorithm
- Remove UniverseSelection special handling for Option and Future chains
- Fix DataManager not removing SubscriptionDataConfigs for Subscriptions
  which finished before being removed from the universe
- Refactor detection of user added Universe so that they do not get
  removed after calling the UniverseSelectionModel

* Add check for option underlying price is set

* Address reviews

- Adding python regression algorithm for
  `AddOptionContractFromUniverseRegressionAlgorithm`
  and `AddOptionContractExpiresRegressionAlgorithm`
- Rename QCAlgorithm new api method to `AddChainedOptionUniverse`

* Fix universe refresh bug

- Fix bug where a universe selection refresh would cause option or
  future chain universes from being removed. Adding regression algorithm
  reproducing the issue.

* Rename new option universe Algorithm API method

- Rename new option universe Algorith API method from
  AddChainedOptionUniverse to AddUniverseOptions
- Rebase and update regression test order hash because of
  option expiration message changed

* Do not update price scale for fillforward data & IsFillForward flag fix (#4836)

* Do not update price scale for fillforward data

- Do no update price scale for fill forward data. FillForward data
  should keep using the prev scale for which it was created. Adding unit tests
- When cloning do not lose IsFillForward flag state, affects
QuoteBars/Ticks, does not affect TradeBars since they perform a memberwise clone.
Adding unit tests

* Auxiliaries shouldn't really affect on applied price factor scale.

Despite we can receeive FillForward'ed data points, corresponding
Auxiliaries for them are not FillForward so we do meet the condition
and then refresh price factor. As a result all futher FF data points are scaled too.

* Regression algorithm to check that FillForward'ed data points arrived with last real price factor

* Add trade for regression algorithm

- Minot tweaks and adding trade for new regression algorithm.
- Updating AddOptionContractExpiresRegressionAlgorithm because it is
  using the symbol for which new data was added.

Co-authored-by: Adalyat Nazirov <aenazirov@gmail.com>

* Remove internal usages of implicit operator in Indicator code (#4844)

* Convert usages of implicit operator in IndicatorBase and IndicatorDataPoint

* Reverting changes to example code

* Moves cash brokerage/IExecutionModel test to post-init (#4826)

* Remove Oanda API v1 (deprecated) (#4833)

* Fix Bitfinex Liquidate error with AccountType.Cash (#4852)

* Move updating of cashbook for fees out of SecurityPortfolioModel

* Update BitfinexBrokerage to handle fees in base currency

* Fixes Market Simulated Automatic Option Assignment (#4853)

* Add underlying holdings to regression result handler details log

When debugging option exercise/assignment issues it's useful to see the
underlying holdings at the time the option contract fill event is processed.

Also adds the full symbol string to the top of the order event section.
The Symbol.Value was being logged via OrderEvent.ToString(), but it wasn't
the full SecurityIdentifier - by including the full SID string it makes it
easier to correlate fills over symbol rename boundaries.

* Fix automatic option assignment from market simulation

During the recent OptionExerciseOrder.Quantity refactor, this case was missed.
Additionally, it was realized that there were no regression tests covering the
automatic assignment via the market conditions simulation. This change introduces
a regression algorithm that covers the automatic assignment of put/call options.

* Update BasicOptionAssignmentSimulation._rand to be non-static

If this value is static then we reuse the same Random instance for ALL regression
tests, thereby defeating the purpose of using a well known seed number. This means
we get different results based on the order execution of preceding algorithms.
By making this an instance variable each algorithm will start with the same seed
value, ensuring consistent runs between regression tests, either run as a suite or
running a single algorithm in isolation.

* Bug #4839 Docker Bash Script Hotfix (#4861)

* fix IFS issue in bash docker scripts

* Add default image to research config

* Bug 4835 api tests failing (#4838)

* Remove F# Project, Splits, and Dividends Tests

* Separate tests that require external accounts; read from config

* Removal of non supported "prices" endpoint test

* Removal of unsupported API functions

* Address review

* NOP GetLastPrice for removal of Prices endpoint

* Post rebase fix

* Rebase fix 2

* remove /r/n from eof for api tests

* Reflect similar refactors to NodeTests

* Fix for live algorithm API testing

* Address Review

* bug-#4846-Fail on restart investing after liquidation on MaximumDrawdownPercentPortfolio.py (#4847)

* Fail on restart investing after liquidation

I added a line so that the trailing high value could be rebalanced and the investment process won't be stop by high value always more than current value by drawdown percent.

* Update MaximumDrawdownPercentPortfolio.py

* Fix for MaximumDrawdownPercentPortfolio

- Fix C# MaximumDrawdownPercentPortfolio to reset portfolio value after
  liquidation. Only reset once we have actually adjusted some targets.
  Updating regression algorithms.

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>

* Standardize API.cs to use JSON Objects (#4868)

* Standardize API to use JSON Objects

* Address review

* Ignore composer ThreadAbort Exception (#4870)

- Composer inner task will not log exception if it's of type Thread
  abort, which means we are shutting down.

* Create QuantConnect-Platform-2.0.0.yaml

Initial commit of QuantConnect Platform Yaml.

* Make StartDate relative to Algorithm TimeZone in Live mode (#4871)

* Fix Toolbox tickers parsing (#4876)

- Fix ToolBox tickers parsing, adding unit test.

* Allow account currency to be overridden by the algorithm (#4856)

* Allow account currency to be overridden by the algorithm

* Fix failing unit test

* Address review

- Revert removal of call check in SecurityPortfolioManager.SetAccountCurrency
- Revert changes to unit tests
- IBrokerage.AccountBaseCurrency now defaults to null
- BrokerageSetupHandler will not change the algorithm's account currency if the brokerage returns null, allowing the algorithm to call SetAccountCurrency in Initialize

* Adds CustomBuyingPowerModelAlgorithm (#4824)

* Adds CustomBuyingPowerModelAlgorithm

This algorithms is an example on how to implement a custom buying power model.

In this particular case, it shows how to override `HasSufficientBuyingPowerForOrder` in order to place orders without sufficient buying power according to the default model.

* Upgrades CustomModelsAlgorithm to Include CustomBuyingPowerModel

The custom buying power model overrides `HasSufficientBuyingPowerForOrderResult` but it doesn't change the trades and, consequently, the regression statistics.

* Add decimal places as parameters to get dividends with arbitrary precision (#4883)

* Add decimal places as parameters to get dividends with arbitrary precision

 
Also, increase precision when generating strings from factor files rows.

* Add xml documentation entries for new optional arguments.

* feat(ToolBox\IQFeed): prevent unordered ticks to be processed (#4884)

closes #4649

* Feature Notebook Api Support (#4898)

* Modify Notebook scripts to load API instance

* Modify docker to move script to IPython profile

* Fix dockerfile copying of start.py

* Fix break for C# cloud and docker load

* Unnecessary path finding

* Update example notebooks

* Update documentation

* Address review

* Adjust readme

* Poor choice of words

* QB Set Start Date Relative to Data Release (#4894)

* Set start date relative to timezone

* Address Review

* Local Object Store Refactor and Fixes (#4880)

* Store temp files in subdirectory

* Fix Dispose case for new temp dir

* Adjust tests for new temp dir

* Dispose unit tests

* Unit test for issue 4811

* Refactor for not using temp files

* Fix storage checks for saving data, plus tests

* Use Base64 for storing keys and decoding them; handles odd key strings

* Don't allow "?" in a key

* Address review

* Deleted test cases

* PersistData handle deletion of files

* Refactor GetFilePath to use Persist()

* Make PathForKey protected

* Adds DC future contract symbol mapping for IB (#4905)

* Fixes SPDB entry for Class III/IV Milk

* IB Brokerage Updates (#4900)

* Add RequestId to request information logging

* Use unique request id across all request types (orders, subscriptions, data queries)

- Previously we had three separate counters for request types and this was causing request information messages to be overwritten (different request types with same ids)

* Update GetContractDetails to log all contracts found

* Fix issue in TiingoNews converter if tickers contains space (#4908)

Also, if ticker contains pipe ( "|" )  it'll be ignored.

* Add defaults (as comments) to Python.Runtime (#4904)

* Redone defaults for python runtime dll config and readme

* Update Python.Runtime.dll.config

Co-authored-by: Jared <jaredbroad@gmail.com>

* Do not terminate algorithm for exceptions in GDAX Fill Monitor (#4910)

* Do not terminate algorithm for exceptions in GDAX Fill Monitor

* Address review

- Only emit warning for REST API errors, other errors are fatal

* Fix ambiguous future symbol error in IB brokerage (#4912)

* Fix ambiguous future symbol error in IB brokerage

* Address review

- Fix symbol mapping

* Feature 4893 performance improvements (#4895)

* Change GetSubscriptionDataConfigs to return IEnumerable<SubscriptionDataConfig>

* Move localTime outside loop

* Remove legacy code

* Remove unnecessary OrderBy

* Reorder conditions to reduce number of times Contains() is called

* Revert "Remove unnecessary OrderBy"

This reverts commit 85383b062e5ac958ec09231df21e0fa3efd3622d.

* Revert "Change GetSubscriptionDataConfigs to return IEnumerable<SubscriptionDataConfig>"

This reverts commit cbd97c9f36e7ed349f1dea740b417e73837bd42b.

* Implements Equity Fill Model (#4913)

* Implements Equity Fill Model

This commit sets the base to create a new equity fill model and the `EquityFillModel` is just a copy of `FillModel`.

* Adds Summary to FillModelPythonWrapper.GetPricesInternal

Adds summary to FillModelPythonWrapper.GetPricesInternal with remarks that it's a temporarily method to help the refactoring of fill models.

* Expand Filtering of Contracts by type to Futures (#4891)

* Implement future type filter

* Filter weeklys test

* Fix for test, contracts were being filtered out by new type filter

* Share core contract filtering logic in new base class

* Catch Future symbols we don't have Expiry functions for

* Expand tests for new filtering

* Address review

* Small doc change

* Compare Date component for expiry

* Clarifying comment

* Fix FxcmBrokerage GetOpenOrders returning empty (#4917)

* Protobuf will use recyclable memory stream (#4921)

* Protobuf will use recyclable memory stream

- Serialization will reuse recyclable memory streams
- Remove serialization of exchange and sale condition for ticks.
  Updating unit tests.
- There is no need to serialize BaseData.EndTime, covered by unit tests.

* Tick will keep a parsed sale condition property

* Readd tick exchange. Json ignore ParsedSaleCondition

* Fix OutOfRangeException in Bitfinex subscriptions (#4926)

* Fix Base Account Currency message for PaperBrokerage (#4929)

- the displayed message was not showing the default currency (USD)

* DividedEventProvider distribution computation (#4828)

* DividedEventProvider distribution computation

- Update regression algorithm which was using a different reference
  price when calculating the dividend
- Adjust divided event provider to compute distribution using factor
  file reference price, if not 0. Adding unit tests
- For equities, only emit auxiliary data points for
  TradeBar configurations, not for QuoteBars, nor internal.

* Address reviews

- Split and Dividend event provider will throw an exception when there
  is no reference price available. Updating `wm` factor file which was
  missing references price and regression algorithms using WM.
- Updating unit tests asserting new exception

* Bug 4809 Docker Run Script Fixes and Improvements (#4922)

* Refactor and hotfix run script

Removed dependency on `realpath`, notably absent from macOS and some debian distros. Replaced with an equivalent bash function.

Cleaned up prompt response handling, replaced var tests with param expressions.

Removed potentially uneeded calls to sudo (again absent on some systems and most users are part of the docker group anyway). Instead, test if it's needed and get preauth with sudo -v.

Poll for running and stopped Lean containers, and prompt before replacing them. Would fail prior.

Uppercased variabled. Sorry.

* Revert docker output redirection to stderr

* Adjustments to maintain all functionality

* Mimic behavior across run scripts

* Update readme to reflect Docker script changes

* Ignore results storage

* Correct print statement

* Mirror changes on research docker scripts

* Make executable

* Handle already running container and sudo privs

* Fix for issues found in testing

* Address Review

* Small adjustments found in linux testing

* Doc improvement

* Add auto update option for Docker images

* Fix image var reference

Co-authored-by: Peter Kazazes <peter@peterk.co>

* Use new generator to generate stubs and publish to PyPI (#4899)

* Use new generator to generate stubs and publish to PyPI

* Hide twine stdout and stderr to prevent token from leaking

* Enable logging when building and uploading stubs (#4933)

* Enable Twine logging

* Enable setup.py logging

* Support Offset in DateRules MonthStart/End WeekStart/End (#4916)

* Add offset capabilities and related tests

* Add tests for Weekend Offsets on Symbol DateRules

* Unify Iterator Behavior

* Refactor and consolidate functions to reduce duplicate code

* Positive offset values only

* Address review

* Expand Month tests to include Forex and Crypto cases

* Ensure order of days in schedule

* Refactor and unify behavior

* More edge cases and tuning

* Address review + more tests

* Quiver Quantitative Integration (#4869)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Delete QuiverHouseDataDownloader.cs

* Delete QuiverSenateDataDownloader.cs

* Delete QuiverPoliticalBetaDataDownloader.cs

* Add files via upload

* Delete QuiverHouse.cs

* Delete QuiverSenate.cs

* Delete QuiverPoliticalBeta.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Delete QuiverDataAlgorithm.cs

* Add files via upload

* Add files via upload

* Add files via upload

* Addresses self review: Cleans up code and adds new unit tests

  * Adds Quiver* C# files to project
  * Adds new unit test for QuiverCongress
  * Adds Python algorithm example

* Address self reviews

- Adding some missing xml docs
- Removing unrequired imports.
- Minor rename from Date to ReportDate
- Live trading will throw InvalidOperationException

* Fixes for example algorithms

Co-authored-by: Gerardo Salazar <gsalaz9800@gmail.com>
Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>

* Update IBAutomater to v1.0.31 (#4932)

- add window handler for unsupported IBGateway versions

* Wider range of offsets on Month tests (#4935)

* Bug 4815 iex web socket library (#4914)

* Fixes 4815 by loading the requested assembly from different folder.

# Conflicts:
#	ToolBox/Program.cs

* Upgrades System.Collections.Immutable to Version=1.2.5.0

* Creates a prototype for SSE streaming in IEXDataQueueHandler.

* Revert the changes in Tick.cs

* Implements a logic in IEXDataQueueHandler that updates the data-feed subscription after Subscribe/Unsubscribe

* Implements IEXCouldSubscribeMoreThan100Symbols - which fails and other small fixes.

* Implements DoForEach LinqExtensions

* Implements IEXEventSourceCollection that wraps all logic that is SSE-subscriptions and symbol-limits-per-connection concerned.

* Changes:

1) Fixes to address review.
2) Makes IexMarketPercent in QuoteSSE nullable as null values are assigned to in this field in data object received before the traing session start.
3) Deprecates helper Subscribe/Unsubscribe in IEXDataQueueHandler and IEXCouldSubscribe test.

* Fixes:

1) _refreshEvent.Reset() order was not correct - should be called before UpdateSubscription
2) ProcessJsonObject- leaves only the functionality to emit ticks.
3) IEXEventSourceCollection - replaces int counter with CountdownEvent to improve the logic - in particular, need a mechanism that would not allow the repeated call to continue until the first one is completed

* Refines the logic with parsing a data snapshot.

* Fixes few more bugs:

1) Logic in ProcessJsonObject
2) Logic in UpdateSubscription - need to introduce additional ManualResetEvent to implement the intended logic - otherwise the logic is not suitable for general case

* Introduce rate-gate limit in IEXEventSourceCollection:

because when subscribing to a bunch of shares (more than 200 for example)
the violation of rate gate policy may occur, which described in API docs asRequest Limits

IEX Cloud only applies request limits per IP address to ensure system stability.
We limit requests to 100 per second per IP measured in milliseconds, so no more than 1 request per 10 milliseconds.
SSE endpoints are limited to 50 symbols per connection. You can make multiple connections if you need to consume more than 50 symbols.:

* Few additional fixes done after real time testing

* Adds xml-docs in stream response object + renaming a file.

* Fixes:

1) Additional StreamResponseStocksUS parsing issues, that can happen outside of regular exchange hours.
2) Cancel clientUpdateThread by means of CancellationTokenSource
3) Replace BuildSymbolsQuery by string.Join

* Fixes:

1) Changing Log Trace -> Debug
2) Adds ConfigureAwait(false) to async method call
3) Removes direct reference to System.Net.Http

* Removes a task and manual reset event in IEXEventSourceCollection

* Additions:

1) IEXEventSourceCollectionSubscribes test
2) GetSnpStocksArray() helper method
3) Installs packages in QC.tests : HtmlAgilityPack & LaunchDarkly.EventSource

* IEX history provider fixes :

1) Tiny bug in ProcessJsonObject - use continue instead of return as execution is inside the for-each block)
2) Adds period variable for the historical data retrieved
3) Fixing from  if (date.Date < start.Date || date.Date > end.Date)  conditional check -->  if (date < start || date > end)  for more precise sorting.

* Changes:

1) Removes HtmlAgilityPack and SNP scraper
2) Uses hard coded symbols instead

* Bug fix:

 - at certain hours (example: before pre-market open or on holidays) IEX may send no data on subscription - when trying to connect during those hours Message handler may not be fired - need to place the counter signal to client.Opened to be informed of successful connect.

* Implements:

1) IEXEventSourceCollectionSubscriptionThoroughTest and MockedIEXEventSourceCollection
2) Makes changes to IEXEventSourceCollection accordingly to allow the thorough testing.

* Fixes formatting issue in StreamResponseStocksUS

* Small fix for a new tests:

- Change RemovedClientSymbols to keep not clients itself, but symbols array, because clients are being disposed right further

* Enables extended logging in Toolbox.

* Fixing IEX historical data fetcher bugs:

1) Bug in IEXDataDownloader.cs - HistoryRequest not precisely correct.
2) Enables day-by-day daily bar downloading in IEXDataQueueHandler.
Motivation: Suppose we need data for some interval in the past - from-date=20170915-00:00:00 --to-date=20171103-00:00:00.
With current behavior IEX would have to download all the historical data from =20170915-00:00:00  up to this day.
3) Extends SynchronizingHistoryProvider

* Enables async fashion historical data download

* More fixes to IEXCouldGetHistory test.

* Reverts day-by-day daily bar downloading and other fixes.

* Removes needless packages & references

* Fix package reference

* To address review

* Sort out zero price ticks:

after testing on real-time algo 30 min before the market open now - IEX may send updates for many securities with zero lastPrice, lastSize - fix to sort such entries out

* Workaround for missing QuoteTicks timestamps:

Since we don't have a stamp for quote tick updates (only for trades) we calculate the average delay between trade tick's time stamp and local time, and
assuming that delay in average is the same for quote updates - just assign the local machine time adjusted for this average

* Simplifies the things.

* Changes:

1) Deprecates quote updates for IEX stocks.
2) Reduce the stream updates to reduce costs to ->
# Stock Quotes every 1 second (per symbol? )
# Can be up to 54,000 messages per symbol per day
https://iexcloud.io/docs/api/#how-messages-work

* Fixes:

1) IEXDataQueueHandler: give an error message on extended market hours or tick resolution subscription request. As they are not really well supported by IEX.
2) Few small fixes in IEXEventSourceCollection, including additional condition for when the subscription remains irrevocable.

* RoundDown fix for PeriodCountConsolidatorBase (#4940)

* Limit rounding interval to 1 day, add SubtractRoundDown and AddRoundUp functions

* fix error message

* Only subtract round down if period is greater than a day

* Tests

* Comment clarification

* Pivot solution to simple fix

* fix error message

* Remove RoundDown/Up limitations; add remarks

* address review

* run_docker_notebook bat hotfix (#4943)

* Added Quiver API token variable to Config (#4946)

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Add files via upload

* Delete QuiverWikipedia.cs

* Delete QuiverWallStreetBets.cs

* Delete QuiverDataDownloader.cs

* Delete QuiverWallStreetBetsDataDownloader.cs

* Delete QuiverWikipediaDataDownloader.cs

* Delete QuiverDataAlgorithm.cs

* Delete QuiverHouse.cs

* Delete QuiverPoliticalBeta.cs

* Delete QuiverSenate.cs

* Delete QuiverHouseDataDownloader.cs

* Delete QuiverPoliticalBetaDataDownloader.cs

* Delete QuiverSenateDataDownloader.cs

* Update readme.md (#4949)

* Fixes weeklies parsing, causing certain futures to be inaccessible in QCAlgorithm (#4936)

* Fixes weeklies parsing, causing certain futures to be inaccessible in Algorithm

  The FuturesExpiryFunction expects the contract month of the Future,
  not the expiration. As a result, the contract gets filtered as a
  weekly contract, rather than as a standard due to the discrepancy
  between the expiry dates when the contract month differs from the
  expiry date's month.

  A very important fact to note is that futures can and do expire prior
  to the contract month. BZ,(brent crude financial futures) expire two
  months prior to the contract month, CL one month prior, etc.

  There has been an addition that contains a "reverse" futures expiry function
  lookup table. We use this to lookup the contract month to re-calculate
  the Future expiry.

  This PR also fixes dairy and adds extra expiry dates. Dairy can have
  an expiry *after* the contract month, so a new path was added to the
  SymbolRepresentation to ensure that these contracts are loaded
  correctly.

* Address review: Adds tests and fixes bug in SymbolRepresentation

  * Updates SID comment on `Date` property to reflect fact that we use
    future expiry for its value

  * Fixes bug in SymbolRepresentation where expiration day would always
    be 01 when parsing a contract with an expiration after the contract
    month

  * Fixes bug in SybmolRepresentation where expiration year would be
    four digits long when parsing a contract with an expiration after
    the contract month

  * Fixes some bad dairy expiry dates

  * Adds tests for SymbolRepresentation and the futures filtering for
    standard contracts

  * Renames method used to extract delta between contract month and
    expiry date

* Removes GH comment and restores Futures contract month expiry param

* IB Brokerage Updates (#4945)

* Update C# API DLL up to  Oct 30, 2020

- https://github.com/InteractiveBrokers/tws-api/commit/a8e66989e5007e511e9ae94857a7e6ca1880086c

* Add extra account information logging after connect

* Update CoinApi symbol mapping + symbol properties database (#4888)

* Update crypto entries in SPBD

- Update values for GDAX and Bitfinex, with latest values from exchanges
- Update symbols with >3 letters
- [Fix] Remove  same base-quote entries

* Update unit tests

Increment in precision given smaller lot sizes in SPDB crypto entries.

* Add GDAX symbol properties downloader (unit test)

* Update GDAX symbol properties database

* Add BrokerageSymbol to symbol properties database

* Update GDAX symbol properties

* Address review

- Rename BrokerageSymbol to MarketTicker

* Add GDAX symbol mapper

* Update GDAXBrokerage to use symbol mapper

* Fix GDAX brokerage unit tests

* Replace GDAXSymbolMapper with SymbolPropertiesDatabaseSymbolMapper

* Address review

- use Symbol key in dictionaries

* Rename BrokerageSymbol to MarketTicker

* Update unit test

* Add Bitfinex symbol properties downloader (unit test)

* Add Bitfinex symbol market ticker to downloader

* Update Bitfinex symbol properties database

* Update BitfinexBrokerage to use SymbolPropertiesDatabaseSymbolMapper

* Remove Bitfinex test symbols from db

* Update Binance symbol properties database

* Update BinanceBrokerage to use SymbolPropertiesDatabaseSymbolMapper

* Add missing Binance test case

* Update symbol properties database

- gdax, bitfinex, binance

* Update CoinApi symbol mapper for new SPDB

* Exclude Bitfinex BCH pre-2018-fork in CoinApiSymbolMapper

* Remove unused properties

* Add CoinApi mappings

Co-authored-by: JJD <jjdambrosio@gmail.com>

* GDAXDownloader : save data int the right ticker name (#4799)

* Update crypto entries in SPBD

- Update values for GDAX and Bitfinex, with latest values from exchanges
- Update symbols with >3 letters
- [Fix] Remove  same base-quote entries

* Update unit tests

Increment in precision given smaller lot sizes in SPDB crypto entries.

* Add GDAX symbol properties downloader (unit test)

* Update GDAX symbol properties database

* Add BrokerageSymbol to symbol properties database

* Update GDAX symbol properties

* Address review

- Rename BrokerageSymbol to MarketTicker

* Add GDAX symbol mapper

* Update GDAXBrokerage to use symbol mapper

* Fix GDAX brokerage unit tests

* Replace GDAXSymbolMapper with SymbolPropertiesDatabaseSymbolMapper

* Address review

- use Symbol key in dictionaries

* Rename BrokerageSymbol to MarketTicker

* Save GDAX history in the real ticker folder

* rename tickerMapper to symbolMapper

* fix gdaxdownloader help message

* Save GDAX history in the real ticker folder

* rename tickerMapper to symbolMapper

* fix gdaxdownloader help message

* use SymbolPropertiesDatabaseSymbolMapper

* address review

Co-authored-by: JJD <jjdambrosio@gmail.com>
Co-authored-by: Stefano Raggi <stefano.raggi67@gmail.com>
Co-authored-by: Martin-Molinero <martin@quantconnect.com>

* Remove python stubs directory (#4955)

* Remove python stubs directory

- Removing python stubs directory since after https://github.com/QuantConnect/Lean/pull/4899
it was been replaced by a python package `quantconnect-stubs`.
- Reverting IDE settings using the stubs folder PR https://github.com/QuantConnect/Lean/pull/4657

* Revert "Adds Python stubs location definition for PyCharm and Visual Studio Code (#4657)"

This reverts commit aded66ec5bc568b7b5f826a4839a9ab8572be86c.

* Address self-review: Provide list of imports and refactor python readme

Co-authored-by: Gerardo Salazar <gsalaz9800@gmail.com>

* Change Alpaca default to PolygonDataQueueHandler (#4960)

* Bug 4864 Missing Brokerage Live Settings (#4958)

* Support Bitfinex live settings

* Add Alpaca and GDAX and their respective tests

* Address review

* Remove LUNG from blacklisted tickers (#4966)

* Update regression algorithms (#4969)

* Reenable extended market hours sampling (#4967)

* Reenable extended market hours sampling

- Will re enable extended market hours sampling using the last benchmark
  and portfolio value when user exchange were open.

* Add unit test minor tweak

- Improve shutdown latency.
- Setting portfolio initial value
- Adding unit test asserting sample behavior.

* Bug 4809 Additional Docker Run Script Fixes (#4971)

* Fix typo in data dir volume mount permission.

* Change default notebook launch behaviour for Mac systems.

Co-authored-by: Athon Millane <athon@maxkelsen.com>

* IB Brokerage updates (#4957)

* Update IBAutomater to version 1.0.32

* Update IBAutomater to v1.0.33

* Update IBAutomater to v1.0.34

* Implement safe exiting for Lean (#4972)

* Fixes inability to parse negative strike prices in SecurityIdentifier (#4953)

* Fixes inability to parse negative strike prices in SecurityIdentifier

  * Adds new tests ensuring backwards compat and no throwing w/ negative
    strike prices

* Changes strategy used to support negative strike prices

  * We add support for negative strike prices at the cost of
    reducing the maximum allowed precision for the strike price.
    We encode a negative sign into the 20th bit of the strike price
    and set our bounds for precision to a max (exclusive) of 475712.
    This in turn is then used to form a negative strike when rebuilding
    the SID.

  * Adds tests covering changes

* Address review: adds additional tests and refactors code

* Address self-review: remove unused import in SymbolTests

* Address review: adds additional test cases for OptionStyle and OptionRight

  * These tests are to ensure that backwards compatibility is maintained

* Addresses review: Adds option chain <-> master SID hash test

  * Refactors previous tests to reduce on code duplication

* Reduce test duplication

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>

* Bug 4947 OnOrderEvent exceptions (#4974)

* Force algorithm to fail on runtime error

* add comment

* Remove unneeded change

* Update algorithm summary

* Address review

* Fixes issue parsing SI data w/ unknown enum value (#4961)

* Extends tests to cover new additions

* Block SetWarmUp after Algorithm has compeleted initialization (#4975)

* Fix for #4939

* Address review

* Logic fix

* Lean shutdown improvements (#4982)

- Use DisposeSafely instead of dipose.
- Adding some logs to know when handlers are getting disposed.
- Normalize exit procedure

* Update IBAutomater to v1.0.35 (#4984)

* Add OptionStrategyMatcher (#4924)

* Reformat/cleanup OptionStrategies

This file was breaking pretty much every style convention in LEAN.
There are other things that should be addressed in here that weren't,
such as passing non-argument names as argument names for ArgumentException,
as well as preferring constructors over property initializer syntax, but
such changes aren't being made to keep this commit strictly reformatting
instead of refactoring.

Added braces and reformatted long lines to make code more legible.

* Add abstract base class for OptionStrategy Option/UnderlyingLegData

This allows us to create either or and later use the Invoke method to push it
into the appropriate list on OptionStrategy.

* Replace O(n) option contract search with 2 O(1) TryGetValue calls

A better improvement would be resolving the correct symbol in the strategy, but
this immediate change is instead just focused on removing the O(n) search inside
a loop.

* Add BinaryComparison and supporting methods in ExpressionBuilder

We're going to use these binary comparisons to make it possible to create
ad-hoc queries against a collection of symbols. Using these expressions,
along with type supporting composition of these expression, we'll be able
to define predicates that can declaratively define how to match an option
strategy with an algorithms current holdings.

* Make GetValueOrDefault defaultValue optional

Was receiving ambiguous invocations leading to neading to invoke this
method explicitly (LinqExtensions.GetValueOrDefault) instead of being
able to use it as an extension method. Making the default value optional
seems to have resolved this ambiguity, leading to cleaner code in the
OptionPositionCollection (forthcoming)

* Add OptionPosition and OptionPositionCollection

OptionPositionCollection aims to provide a single coherent interface
for querying an algorithm's option contract positions and the underlying
equity's position in a performant, immutable way. The immutability of
the type is necessary for how the options matcher will operate. We need
to recursively evaluate potential matches, each step down the stack removing
positions from the collection consumed by each leg matched. This will enable
parallelism of the solution as well as simplifying the mental model for
understanding due to not needing to track mutations to the collection
instance.

* Add Option test class for easily creating option symbol objects

* Add OptionStrategyLegPredicate and OptionStrategyLegDefinition

The definition is a composition of predicates, and each predicate supports
matching against a set of pre-existing legs and a current position being
checked for the next leg (this leg). In addition to the matching functionality,
it also supports filtering the OptionPositionCollection, which is where much
of the work for resolving potential option strategies is done. By successively
filtering the OptionPositionCollection through successive application of predicates,
we wil end up with a small set of remaining positions that can be individually
evaluated for best margin impacts.

All of this effectively unrolls into a giant evaluation tree. Because of this
inherent structure, common in combinatorial optimization, the OptionPositionCollection
is an immutable type to support concurrent evaluations of different branches of
the tree. For large position collections this will dramatically improve strategy
resolution times. Finally, the interface between the predicate and the positions
collection is purposefully thin and provides a target for future optimizations.

* Add OptionStrategyDefinition and OptionStrategyDefinitions pre-defined definitions

The OptionStrategyDefinition is a definitional object provided a template and functions
used to match algorithm holdings (via OptionPositionCollection) to this definition. The
definition defines a particular way in which option positions can be combined in order to
achieve a more favorable margin requirement, thereby allowing the algorithm to hold more
positions than otherwise possible. This ties into the existing OptionStrategy classes and
the end result of the matching process will be OptionStrategy instances definiing all
strategies matched according to the provided definitions.

* Add OptionStrategyMatcher and Options class, w/ supporting types

OptionStrategyMatcherOptions aims to provide some knobs and dials to control how
the matcher behaves, and more importantly, which positions get prioritized when
matching. Prioritization is controlled via two different enumerators, one controller
which definitions are matched first and the other controller which positions are
matched first. Still unimplemented, is computing multiple solutions and running the
provided objective function to determine the best match. When this gets implemented,
we'll also want to implement the timer. For anyone looking to implement these features,
please talk with Michael Handschuh as there's a particular way of representing these
types of combinatorial solutions (a 3D tree) that can be used as a variation of the
linear simplex method for optimizing combinatorial problems.

* OptionStrategyMatcher: Address PR review comments

* Ensure created OptionStrategy legs all have the same multiplier

Each leg definition match gets it's own multiplier which indicates the
maximum number of times we matched that particular leg. When we finish
matching all legs, we pick the smallest multiplier from all the legs in
the definition and use that as the definition's multiplier. When we go
to create the OptionStrategy object we MUST make sure we're using the
multiplier from the definition and not from the individual legs.

This change fixes this issue and also provides a guard clause to ensure
that we're not trying to use a multiplier larger than what was matched.

* Add XML docs for OptionStrategyDefinitions from OptionStrategies

* Lean Optimization interface in QCAlgorithm (#4923)

* initial commit

* run parametrized algorithm with command line parameters

* skeleton: top level structure

* OptimizationNodePacket scheme

* pass parameters as HashSet

* run Lean and read results

* call method on optimization completion

* refactor public interfaces

- close ParameterSet collection; allow only get operations
- explicit method to start LeanOptimizer

* synchronize RunLean method; the result could come in before the backtest id is set in the collections

* another portion of refactoring and interface changes

* comments

* comments & tests for Extremum, Minimization and Maximization classes

* unify optimization paramater values (min, max, step) & mode GridSearch tests

- swap min&max if necessary
- iterate left => right (negate step value if necessary) & provide default step value if step == 0
- no StackOverflow Exception
- parameterSet Id should be global for current generator and retain between steps
- test signle point boundary (min == max)

* BruteForceStrategy tests

* more comments

* Update Optimizer assembly information

- Update Optimizer projects assembly information to match behavior of
  the other projects

* Tweaks

- Adding comments
- Replace OnComplete for Ended event
- Replace Abort for Dispose
- ConsoleLeanOptimizer will keep track of running processes
- Each backtest will store results in a separated directory, so they
  don't fight for the log.txt file.
- Adding cmdline option for lean to close automatically
- Adding concurrent execution backtest limit
- Console optimizer will start Lean minimized
- Escape spaces in Json path

* remove parameter set generator abstraction layer

we don't need this flexibility now.

* refactor public methods; Step shouldn't be public

* constraints: wip

* define contract

* comparison operators and tests

* specify JsonProperty values

* Move SafeMultiply100 to extensions

* Throw exception on failed Optimizer.Start

* constraints: wip

* change finish & dispose process

* minor fixes

- handle force lean abort
- notify consumer if target has been reached

* target & constraints; adapt unit tests

* Minor Tweaks and fixes

- Some logging improvements
- Remove Public since not required

* Ignore empty ParameterValue

* simplify condition

* avoid reinitialization

* reduce type; force immutable

* unit tests for constraints  and target value

* parse & normalize percent values, i.e. 20% => 0.2

* fixup

* Target & Constraint & OptimizationNodePacket unit tests

* Add more json unit tests

- Adding more json conversion unit tests. Fix bug for Extremum which
  wasn't using the converter.

* LeanOptimizer tests

* Estimation results

* User thread safe counters

* LeanOptimizer unit tests; push OptimizationResult on Ended event

* more unit tests

* Minor tweaks

-Estimate ToString in a single line.
-Typos and missing header file

* Add base SendUpdate method

- Add base SendUpdate method for LeanOptimizer

* fix LeanOptimizer test; rely on internal Update rather than timer

* Add OptimizationStatus

- Add missing commments and OptimizationStatus

* EulerSearch implementation: wip

* OptimizationParameter custom converter

* change the type

* make step optional

* change folder structure

* enumerate optimization parameter using IEnumerable & IEnumerator

* unit tests: parameters & objectives

* unit tests: strategies

* remove redundant TODO

* change Euler search boundaries

* more Euler tests

* prevent race condition

* Add account/read endpoint

- Adding account/read endpoint. Adding unit test

* Add status check before running lean

* Minor self review

- Adding missing comments, minor changes

* remove array parameters

* minor changes

- tidy up config file, rename variable
- accept min less or equal than max

* move OptimizationParameter methods to strategies

* Minor improvements for BaseResultHandler derivates

* minor changes

- strict requirements for Step and MinStep values
- strategy specific settigs

* Add TotalRuntime to estimate

Co-authored-by: Martin Molinero <martin.molinero1@gmail.com>

* Bug 4757 Synchronize Security Additions (#4879)

* Bump time by one tick in adding subscription

* Adjust regressions

* Change removal to immediate

* Use series.AddPoint instead of directly adding it

* Adjust regression

* Add checks for fixed behavior in regressions

* Address review

* Adds Futures Options Asset Class w/ IB Support (#4928)

* Adds preliminary universe selection for Future Options

* Fixes scaling issues with Future Options

* Fixes scaling multiplying by 10000x instead of using _scaleFactor

* Fixes scaling for Tick

* Revert changes to Tick since it divides the scaling factor

* Changes stale method name to new method name after rebase

* Fixes selection bugs, adds new methods, and adds unit tests

  * Fixes bug where Equity Symbol was created for an underlying
    non-equity Symbol, resulting in equity data trying to be loaded

  * Adds unit tests covering changes to Tick, QuoteBar, TradeBar and
    LeanData

  * Adds regression test for AddUniverseOption filter contract selection
    for Future Options

* Addresses review - modifies the AddFutureOption signature

  * Adds new AddUniverseOptions method overload
  * Removes and adds a new unit test
  * Misc. modifications to account for new changes

* Fixes bug where futures were loaded using default SID Date

  * Refactors and removes unnecessary work
  * Fixes regression algorithm, which previously made no trades

* Adds future option data

  * Adds the corresponding underlying data, in this case, futures data
    to enable usage of future options data

* Replaces data with new data (ES18Z20)

  * Improves Future chain filtering and updates regression stats

* Add AddFutureOptionContract API

* Expands regression and unit tests to test in finer detail

* Adds Python regression algorithms for AddFutureOption[Contract] methods

* Adds new unit test for BacktestingOptionChainProvider

  * Fixes bug with BacktesingOptionChainProvider where we
    attempted to load the Trades option chain first, resulting
    in breakage of backwards compatibility and limitation of the
    option chain.

  * Adds new regression algorithms (Py) to Algorithm.Python project

* Adds FutureOptionMarginBuyingPowerModel

  * Modifies code paths used to select margin model
  * Adds related unit tests for margin model

* Fixes issue with unit test and MHDB/SPDB lookup for Future Options

* Preliminary regression algorithm testing ITM call/put option buying

  * Fixes bug where fee model used did not find non-US market
    options fee model. We now use the futures fee model for future
    options because IB charges the same commissions per contract
    between futures and futures options

* Adds proper regression algorithm for ITM future options expiration

* Pushing broken algorithm for review

  * Currently, algorithm does not fill forward, causing
    a single future option to not get exercised when it is delisted.

* Adds FutureOptionPutITMExpiryRegressionAlgorithm

  * Improves existing regression algorithm for call side
  * Fixes bug in existing regression algorithm
  * Adds AAPL daily data to advance enumerator for ^^^ fix

* Adds additional future option regression algorithms

  * Adds Buy OTM expiration regression algorithms
  * Adds Sell ITM/OTM expiration regression algorithms
  * Adds missing Python regression algorithms

* Adds remaining Python regression algorithms and fixes issues

  * Fixes naming issues and statistics
  * Adds short option OTM regression algorithms (Py)

* Add license header and class comments to python algorithms

  * Cleans up comments and docstrings
  * Create Buy/Sell call intraday regression algo

* Redirects future options symbol properties to futures symbol properties

  * Asserts exercise/assignment price and updates stats in regression algos
  * Adds new unit test covering changes to SecurityService

* Adds comments and fixes failing test

* Partially fixes future option mis-calculated profit/loss

* Adjusts portfolio model to calculate FOP as a no upfront pay asset class

  * Updates regression algorithm statistics

* Begin IB FOP support

* Initial support for FOP IB data streaming, live �

  * Adds additional functionality to LiveOptionChainProvider
    - Allows querying CME API to retrieve option chains for CME products
    - Ultimately, it's also the groundwork for the CME
      LiveFutureChainProvider

  * Edits IDataQueueUniverseProvider interface to provide greater
    control to implementors of it

  * Misc. bug fixes required to get FOP data streaming through IB

* Adds comments, adds missing rategate call, and cleans up code

* Force exchange for FOP and Futures when no exchange is provided

* Fixes bug with Portfolio modeling across all asset classes

* Adds LiveOptionChainProvider tests for Future Options

* IB brokerage option symbol bug fixes and improvements

* Fixes contract multiplier lookup bug

  * Fixes issue where we attempted to subscribe to IB data feed with canonical security
  * Adds ES MHDB entry

* Reverts portfolio modeling changes for Futures Options

  * Since IB eats into our account's cash balance when
    a new FOP contract is purchased, we must model by applying funds
    to our cash whenever a new purchase/sell occurs.
    If we choose to model FOPs exactly as we do with futures, we
    will end up with an invalid TotalPortfolioValue on algorithm
    restart. By all means and purposes, FOPs are modeled exactly
    the same as equity options with respect to the portfolio.

  * Adds comments clarifying portfolio modeling and clarifies
    existing portfolio modeling comments with additional context.

* Fixes IB symbol lookup for future options

  * Fixes LiveOptionChainProvider looping 5 times per option chain
    request, even on success

  * Sets OptionChainedUniverseSelectionModel to produce a canonical
    future/future option/option Symbol to avoid creating two Symbols

  * Adds GLOBEX future option symbol mapping from future -> fop

* Fixes LiveOptionChainProvider loading wrong contract option chains

  * Fixes loading of futures options ZIP files when backtesting
  * Adds a string -> decimal JSON converter
  * Additional fixes/refactoring to the LiveOptionChainProvider

* Adds tests for changes to Symbol and LeanData

  * Reverts changes to IB-symbol-map

* Fixes Value for mapped future options tickers

  * Fixes Symbol test

* Changes path of future options to future's expiry date

  * Extra changes made to remove scaling from writing CSV
  * Added method to map from FOP Globex -> FUT Globex

* Fixes MOO and MOC orders for future options

  * Note: this order type might not be supported by IB or CME.

* Bug fixes and updates unit tests

* Update regression tests and data format

* Rebase changes

* 1. Multiple bug fixes for LiveOptionChainProvider, reverts IQFeed changes
2. Address review (partial): Code reuse and cleanup

1.
  * Modifies check in
    `AddFutureOptionShort(Call|Put)ITMExpiryRegressionAlgorithm`
    to ensure no buys have negative quantity

  * Code reuse changes in IB brokerage

  * Bug fix in IB brokerage where we assigned the FOP expiry
    as the futures expiry (requires verification)

  * Doc changes and adds missing summaries/license banners
  * Disposes of HTTP client resources in LiveOptionChainProvider
  * Renames classes and adds FutureOption folder in Common/Securities

2.
  * We revert back to the quotes API for the option chain,
    since the settlement API sometimes had missing strikes.

  * Fixes future option expiry being set as future's expiry
    in LiveOptionChainProvider

  * Fixes bug where wrong option chain was selected because of bad
    expiry lookup in the futures expiries returned from CME

  * Fixes multiple looping bug in LiveOptionChainProvider
  * Adds strike price scaling for LiveOptionChainProvider

  * Reverts IQFeed changes and simplifies interface upgrade changes

  Some additional challenges we'll have to solve as part of FOPs:

    - The `OptionSymbol.IsStandard` method makes the assumption that
      weeklies contracts follow the pattern equities follows, which
      does not apply to Futures Options

    - The Subscription created in:
        `OptionChainUniverseSubscriptionEnumeratorFactory`

      ...adds a Trade config. For illiquid contracts, this
      will delay universe selection for the option symbol
      until we get a trade. However, if we add a quote config,
      the data would instead be loaded based on the first quote
      we received from the brokerage.

      But since we're currently using a trade config, illiquid
      contracts won't start streaming data until it receives a trade.

NOTE: this commit is a WIP to addressing the reviews received in the PR,
but has been committed early for efficiency in the review process

* Fixes regression algorithms and misc. bugs

  * Fixes map file lookup for non-equity options
  * Adds extra assertion at end of algorithm to ensure no holdings are
    left when the algorithm ends.

  * Adds FutureOptionSymbol, allowing all contracts through as standard
  * Changes SPDB to allow defaulting to underlying future symbol
    properties if no entry is found for the given FOP

  * Fixes calls to SPDB in SecurityService, IBBrokerage
  * Reverts AAPL daily ZIP file to fix majority of regression algorithms
  * Adds FOPs symbol properties
  * Fixes existing symbol properties for a few futures
  * Adds tests for changes to Symbol Properties Database

* Removes string SPDB lookup method

  * Updates tests and misc callees of previous method

* Updates all regression tests to use data of already expired contracts

  * Adds Futures Options Expiry Functions tests
  * Adds required futures data for 2020-01-05

* Address review (partial): Expands test coverage and fixes tests

* Set option chain tests parallelism to fixture only

* Fixes broken test for contract month delta for FuturesOptionsExpiryFunctions

* Changes delisting date logic for Futures Options

* Address review: removes duplicate code, misc code fixes

  * Bug fix in MarketHoursDatabase.GetDatabaseSymbolKey() where
    we would use the underlying's Symbol for lookup in the MHDB

  * Adds missing license banner
  * Removes Futures Options entries from MHDB
  * Adds new tests

* Adds SecurityType.FutureOption

  * Converts any underlying comparisons and uses SecurityType directly
    instead for FOP specific behavior

  * Extra code modifications to acommodate new SecurityType

* Addresses review: fixes order fee bug on exercise

  * Additional bug fixes and adding of SecurityType.FutureOption
  * Updates regression algorithms OrderListHash

* Fixes various bugs in IB live implementation

  * Fixes bug setting the right contract expiration date for FOP
    generated by LiveOptionChainProvider

  * Adds new function to FuturesOptionsExpiryFunctions

  * Clarifies parameter names better in some functions/methods

  * Fixes bugs in IB brokerage for FOPs

* Address review - code cleanup and refactor

  * Remove MappingEventProvider, SplitEventProvider, and
    DividendEventProvider for Futures Options in
    CorporateEventEnumeratorFactory

* Address review: Use MHDB key resolver in SPDB

* Makes regression tests pass and adds comment for expiry issue

* Fixes MHDB lookup on string symbol method

* Adds Futures Options greeks regression algorithm (C# only)

* Adds explanitory comment on MHDB FOP lookup

* Remove python from FutureOptionCallITMGreeksExpiryRegressionAlgorithm

* Limit Futures Resolutions in BaseData (#4979)

* Limit futures support resolutions

* Fix broken tests

* Address review

* Fixes Random Length Lumber contract multiplier/min price variation (#4993)

* Fix invalid xml on SafeMultiply100 documentation (#5000)

* Load fine fundamental from data cache folder (#4995)

* Load fine fundamental from data cache folder

* Add daily backwards lookup for live fine

* Adds extra simplified history request method in PortfoliioLooper (#5003)

* Fixes options order crash in ReportGenerator/PortfolioLooper (#4992)

* Update readme.md

* Api Update November 2020 …
var theta = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Theta).ToList();
var vega = data.OptionChains.Values.OrderByDescending(y => y.Contracts.Values.Sum(x => x.Volume)).First().Contracts.Values.Select(x => x.Greeks.Vega).ToList();

// The commented out test cases all return zero.

Choose a reason for hiding this comment

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

@gsalaz98 and @jaredbroad Could you confirm if the Greeks miscalculation is currently a known issue of FOP?

I am a (paying) user of quantconnect and has been puzzled for days on why my algo doesn't work. I narrowed it down to the fact that the Greeks were off. It will be nice if you could confirm it is a known issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants