Commit Graph

105 Commits

Author SHA1 Message Date
Martin Molinero 97c2889cc2 Fix Orders Placed in OnOrderEvent
- The `BacktestingBrokerage` will also verify there are no more pending
orders when deciding if it needs to continue scanning
2019-05-28 14:38:12 -03:00
Martin Molinero 35ca60aa31 Fix duplicate OnOrderEvent invoke
- `BacktestingBrokerage.Scan()` is now reentrant and was causing
duplicate processing and events. To solve this updateing the order
status keeped by the brokerage. Adding unit tests
2019-05-22 15:33:09 -03:00
Stefano Raggi a616bdbea2 Add StalePriceTimeSpan setting for market fill warnings
The market fill warning introduced in #2869 was considering any price older than the fill time as stale (even if only a few seconds older), causing many false alerts.

This is being changed now by adding a new configurable algorithm setting: StalePriceTimeSpan (with a default value of one hour).
2019-03-14 22:03:23 +01:00
Martin Molinero c9e6268cbd Remove OrderFeeParameters.AccountCurrency
- Removing OrderFeeParameters.AccountCurrency. Where required replacing
for constructor parameter defaulting to USD.
- Updating IB fee model to use to correct fee currency
2018-12-28 15:57:53 -03:00
Martin Molinero 8e41371e19 Non-Usd brokerage support
- `GetCashBalance()` will return a `List<CashAmount>`, will not need to
set conversion rates, which requires knowing what the account currency is.
- Removing `Global.Holding` conversion rate field. It wasn't being used
and required knowing what the account currency is.
- Adding equality operators for `CashAmount`. Adding unit tests.
2018-12-27 12:13:43 -03:00
Martin Molinero 0933da9303 Refactor previous commits
- Removing `AccountCurrency` from `Cash` and `Brokerage` classes.
`ICurrencyConverter` will now provide the `AccountCurrency`
- Adding new static `OrderFee.Zero` which will return a 0 order fee in
`NullCurrency`
- Adding static `Currencies.USD` value, replacing all "USD".
- Addin new static `Currencies.NullCurrency`
- Updating Bitfinex `FeeModel` so it return fees in quote currency.
Adding unit tests
2018-12-13 11:30:40 -03:00
Martin Molinero b7bcdbef04 Adding OrderFee to OrderEvent
- Replacing `decimal` for `OrderFee` at the `OrderEvent`.
- Adding `FeeModelNotUsingAccountCurrency` regression test
- Adding unit tests for `CashBuyingPowerModel` and `SecurityMarginModel`
with non account currency fees
2018-12-10 13:18:41 -03:00
Martin Molinero 75ffa300f1 Adding new IAlgorithm.AccountCurrency
- Adding new `IAlgorithm.AccountCurrency { get; }` that will point to the
`Portfolio.CashBook.AccountCurrency`. Setter will be added in a
following PR.
- Base `Brokerage` class will now have a `AccountCurrency { get }`
pointing to the `IAccountCurrencyProvider`. Will be used by the different
brokerages implementations.
2018-12-10 11:59:02 -03:00
Martin Molinero c5daf9ac9a Refactor IFeeModel
- Refactoring `IFeeModel`. *This is a breaking change* for implementations
inheriting directly from the interface. Deleting old and adding a new method
`OrderFee GetOrderFee(OrderFeeParameters parameters)` that will use a parameter
and a result object.
- Refactoring `CashAmount` so it does not embed a `ICurrencyConverter`
instance.
- Updating unit tests
- The `Security.QuoteCurrency`, a `Cash` instance, will provide access
to the `AccountCurrency` as a property.
- Will maintain backwards compatibility with old python custom
FeeModels, Adding unit test.

> Note that for now, consumers will ignore the currency, as before, and
directly consume the amount
2018-12-06 16:20:36 -03:00
Martin Molinero 46baedf858 Refactor FillModels
- Modifying `IFillModel` interface removing old methods and adding new
method `Fill Fill(FillModelParameters)`. This is a breaking change.
- Adding new `PythonWrapper` property for the `FillModel` base class.
This is required due to a limitation in PythonNet:
   - Given C# class T has `virtual` methods A and B. Where method A
   calls method B. And given custom python class L inherits class T.
   And overrides method B. When class L calls
   base method A (of class T). And when method A internally calls method B.
   It will call C# implementation, not the python override. This issue
   is solved going back to the `PythonWrapper`. Adding unit tests.
- Adding new `Parameters` property for the `FillModel` base class that will
be set by the call to `Fill()`. The `Parameters` property will be used by
the modified `XxxxFill()` implementations
- Adding new `Fill` result object for the `Fill(FillModelParameters)`
method
- Adding new check before removing a `SubscriptionDataConfig` due to the FillModels consuming the configuration collection when determining which Price to use. WIll now only remove the `SDC` if the symbol was removed from the selecting `universe`, this will avoid the case where the symbol is never deselected and the subscription ends, which happens at the end of all executions.
- Adding unit tests showcasing retro compatibility.
- Enabling C# `CustomModelsAlgorithm` as a regression test. Python
version returns a different result due to random number generation.
2018-11-29 15:38:46 -03:00
Michael Handschuh c5cc3aa656 Apply dividends in live paper mode
We recently disabled dividend application in live mode because
it was more accurate to rely on the brokerage's daily cash sync
to pick up when the distribution was actually made. Before that
change we were applying dividends on the ex-date, and then it was
un-applied via the cash sync and then re-applied when the funds
finally hit the brokerage account. By making that change we failed
to ensure that dividends were still applied in live paper mode.

Dividends are detected via the PaperBrokerage's Scan method which
is called at least once every time loop. IAlgorithm.CurrenctSlice
is used to check for dividends and then the total distribution is
computed and applied directly to the portfolio's cash book.
2018-10-09 13:27:07 -04:00
Michael Handschuh f6a1bc1683 Prevent overwriting computed fees for backwards compatability
For years IFillModel has been responsibile for computing an order's fee. The
standard way of doing this has always been via invocation of security.FeeModel,
but there was no mechanism preventing an  implementation from directly
computing the fee. As such, this check was added to prevent overwriting an order
fee that has already been computed.
2018-10-02 15:16:00 -04:00
Michael Handschuh 137730a214 Move fee computation outside of fill models
This change aims to reduce the responsibilities of IFillModel implementations
by removing the requirement that they also compute the order fee. Order fees
are now computed by whomever invokes the fill model, namely the BacktestingBrokerage.
2018-10-02 15:11:33 -04:00
Martin Molinero 82c2532a31 Improve performance for backtests with a large amount of trades 2018-06-21 16:59:29 -03:00
Stefano Raggi 4406332046 Make TimeInForce class abstract 2018-05-30 10:00:11 +02:00
Stefano Raggi a85ebe42d5 Rename HasOrderExpired to IsOrderExpired 2018-05-02 21:00:56 +02:00
Stefano Raggi 2d19ab7ead Review TimeInForce handler interface
- removed IAlgorithm dependency from time in force handlers
- renamed GoodTilCancelled to GoodTilCanceled
- added GTC time in force in regression algorithms
- inlined initialization of time in force handler dictionary
2018-05-01 20:53:43 +02:00
Stefano Raggi 1ecf9db692 Initialize time in force handlers in backtesting brokerage constructors 2018-05-01 00:15:46 +02:00
Stefano Raggi ab82d9942a Add message to order event when time in force expired 2018-04-30 18:27:30 +02:00
Stefano Raggi 66d6de1540 Rename ITimeInForceHandler methods 2018-04-30 09:28:04 +02:00
Stefano Raggi f62c04c0b0 Add time in force handler calls in BacktestingBrokerage 2018-04-30 09:28:04 +02:00
Stefano Raggi e034fd3960 Fix buying power error handling bug in BacktestingBrokerage
Fixes #1843
2018-04-09 19:55:12 +02:00
Stefano Raggi 4318c17974 Update buying power model interface for better messaging
The HasSufficientBuyingPowerForOrder method has been updated to return a result object including the reason the order cannot be executed.

The SetHoldings method has also been updated to display a message if CalculateOrderQuantity returns zero.
2018-02-27 11:24:15 +01:00
Stefano Raggi acb5db6cf5 Rename Security.MarginModel to BuyingPowerModel 2018-01-31 11:47:34 +01:00
Stefano Raggi c9542abc42 Rename ISecurityMarginModel.CanExecuteOrder to HasSufficientBuyingPowerForOrder 2018-01-31 11:47:33 +01:00
Stefano Raggi 66b265d890 Move GetSufficientCapitalForOrder to SecurityMarginModel.CanExecuteOrder 2018-01-31 11:47:33 +01:00
Stefano Raggi f37d0cc962 Optimize loops for performance on cashbook and securities 2017-12-20 21:58:59 +01:00
Stefano Raggi c6aba7bfec Reduce full locking on ConcurrentDictionary objects
This PR is an attempt to reduce contention in concurrent dictionaries, replacing method calls using full locks with lock-free equivalents:

- dictionary.Count -> dictionary.Skip(0).Count()
- dictionary.Keys -> dictionary.Select(x => x.Key)
- dictionary.Values -> dictionary.Select(x => x.Value)

The most frequent usages of these methods are: CashBook, SecurityManager, UniverseManager and indirectly, SecurityPortfolioManager.

The reasons for this update are explained very clearly in this article:
https://arbel.net/2013/02/03/best-practices-for-using-concurrentdictionary/
2017-12-20 17:18:54 +01:00
Michael 87075e714f Merge pull request #1394 from QuantConnect/option-assignment-sim-fix
Fix option assignment simulation in backtesting
2017-12-15 15:26:25 -05:00
Stefano Raggi 35acb49056 Update order status check in BacktestingBrokerage.OnOrderEvent
The option assignment could fail for insufficient margin and the order status could be set to Invalid, updated the check to use OrderStatus.IsClosed().
2017-12-15 18:57:39 +01:00
Stefano Raggi 3d99906fa1 Disable order log tracing when backtesting
These logging instructions were only meant to be executed in live mode.
2017-12-15 10:59:19 +01:00
Stefano Raggi 8e0de802f2 Fix option assignment simulation in backtesting
The option assignment simulator used in backtesting was firing assignment events multiple times before expiration, but the actual assignment was not being performed until the expiration date.
2017-12-13 10:37:32 +01:00
Stefano Raggi 1295c91551 Update order event messages for option expiration
The message for short option order events at expiration was "Automatic option assignment on expiration" for both ITM and OTM. It has now been corrected to "Option expiration" for OTM short options.

The same message is now also being reported in QCAlgorithm.OnAssignmentOrderEvent instead of the generic "Option Assignment" message.
2017-12-05 00:49:41 +01:00
Stefano Raggi 9938132edd Add logging to BacktestingBrokerage order methods 2017-11-21 00:01:45 +01:00
Stefano Raggi 2e8a15033e Add extra locks and null check in BacktestingBrokerage 2017-11-21 00:01:44 +01:00
Stefano Raggi e379457757 Refactor option chain providers
- Moved provider implementations out of brokerages into their own classes
- Removed DefaultOptionChainProvider
- Added BacktestingOptionChainProvider and LiveOptionChainProvider
- Moved SetOptionChainProvider call from Engine to setup handlers
2017-08-02 22:43:15 +02:00
Stefano Raggi ac6856a589 BacktestingBrokerage implements IOptionChainProvider 2017-08-02 22:43:11 +02:00
quant1729 c416df6241 Refactored option assignment/exercise:
1. Made sure we treat properly option expiration dates before Feb 2015 and after. Added tests.
2. Refactored expiration delisting, assignments/option exercise to happen in the end of the date, not MOC orders in the beginning of the day. Regression test.
3. Refactored option exercise model to generate proper fills on assignments/option. Those fills are reflected correctly in margins, in stats and correspond to IB model. Still need to run IB real-life live tests.
4. Refactored option symbol related functions into separate module (OptionSymbol.cs)
5. Made sure OnAssignmentEvent arrived to the user algo in regression test. Do we need OnExercise event? Not sure.
6. Tested end-to-end Ray's current code (covered call strat) to see short option legs expire worthless, and stats updated.
2017-02-02 19:35:37 +08:00
quant1729 41bfdbcc9d Updated code according to the discussion in PR 2016-12-30 18:13:07 +01:00
quant1729 1141cd21e6 Merge branch 'futures' into master
Conflicts:
	Algorithm.CSharp/QuantConnect.Algorithm.CSharp.csproj
	Algorithm/QCAlgorithm.cs
	Brokerages/InteractiveBrokers/InteractiveBrokersBrokerage.cs
	Common/QuantConnect.csproj
	Common/Securities/Option/Option.cs
	Data/equity/usa/factor_files/aapl.csv
	Data/symbol-properties/symbol-properties-database.csv
	Engine/DataFeeds/Enumerators/Factories/BaseDataSubscriptionEnumeratorFactory.cs
	Engine/DataFeeds/Enumerators/Factories/OptionChainUniverseSubscriptionEnumeratorFactory.cs
	Engine/DataFeeds/SubscriptionDataReader.cs
	ToolBox/QuantConnect.ToolBox.csproj
2016-11-07 16:18:11 +01:00
quant1729 3a0fbf3d91 Merge branch 'futures' of https://github.com/QuantConnect/Lean into futures
Conflicts:
	Brokerages/Backtesting/BasicOptionAssignmentSimulation.cs
2016-10-03 12:01:39 +02:00
quant1729 43db7f96c9 - Added support for basic initial/maintenance margin (selected contracts). Tests.
- Fixed symbol properties file for IR contracts
- Added VIX index to futures symbol nomenclature (futures.cs)
2016-10-02 18:18:07 +02:00
quant1729 3f51b23524 Backtesting market simulator: fixed random gen seed 2016-09-30 16:52:26 +02:00
quant1729 2dce74e26d - Extended Option security and Option holding classes
- Updated IB fee model to support option exercise
- Added support for splits for options. Not tested on real data yet.
- Added option exercise functionality for long positions. Unit Tests. Not tested on real data yet.
- Added option assignment functionality for short positions. Assignment event. Unit Tests.
- Added basic option assignment simulator for backtesting brokerage. Simulates assignments for deep ITM short positions close to expiration. Unit Tests.
2016-08-31 18:00:00 +02:00
devalkeralia a535b1733c Minor change to the constructor for the factories and fixed typo for config 2016-07-21 14:05:03 -04:00
devalkeralia 3cc8928a0a removed the IResultHandler from the constructor for DefaultBrokerageMessageHandler 2016-07-20 19:31:14 -04:00
devalkeralia 35d5c5029c Updated the base class for Backtesting and Paper BrokerageFactory from IBrokerageFactory to BrokerageFactory 2016-07-20 19:23:38 -04:00
Stefano Raggi dcd139a45b In BacktestingBrokerage.Scan pending orders are now processed in the correct order (FIFO) 2016-04-01 01:00:42 +02:00
Michael Handschuh 7a7b77cae1 Update Order.GetValue to take a Security
Previously the get value functions were not respecting various conversion rates and contract multipliers
2016-02-04 19:56:26 -05:00
Michael Handschuh 1d07e5d31a Move IBrokerageFactory.DefaultMarkets to IBrokerageModel 2016-02-04 13:27:53 -05:00