eb1181f5f7
* 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
563 lines
26 KiB
C#
563 lines
26 KiB
C#
/*
|
|
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
|
|
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
|
|
*
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*/
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using Fasterflect;
|
|
using Newtonsoft.Json;
|
|
using QuantConnect.AlgorithmFactory;
|
|
using QuantConnect.Brokerages;
|
|
using QuantConnect.Brokerages.InteractiveBrokers;
|
|
using QuantConnect.Configuration;
|
|
using QuantConnect.Data.Market;
|
|
using QuantConnect.Interfaces;
|
|
using QuantConnect.Lean.Engine.DataFeeds;
|
|
using QuantConnect.Lean.Engine.Results;
|
|
using QuantConnect.Lean.Engine.TransactionHandlers;
|
|
using QuantConnect.Logging;
|
|
using QuantConnect.Packets;
|
|
using QuantConnect.Securities;
|
|
using QuantConnect.Util;
|
|
|
|
namespace QuantConnect.Lean.Engine.Setup
|
|
{
|
|
/// <summary>
|
|
/// Defines a set up handler that initializes the algorithm instance using values retrieved from the user's brokerage account
|
|
/// </summary>
|
|
public class BrokerageSetupHandler : ISetupHandler
|
|
{
|
|
/// <summary>
|
|
/// The worker thread instance the setup handler should use
|
|
/// </summary>
|
|
public WorkerThread WorkerThread { get; set; }
|
|
|
|
/// <summary>
|
|
/// Any errors from the initialization stored here:
|
|
/// </summary>
|
|
public List<Exception> Errors { get; set; }
|
|
|
|
/// <summary>
|
|
/// Get the maximum runtime for this algorithm job.
|
|
/// </summary>
|
|
public TimeSpan MaximumRuntime { get; }
|
|
|
|
/// <summary>
|
|
/// Algorithm starting capital for statistics calculations
|
|
/// </summary>
|
|
public decimal StartingPortfolioValue { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Start date for analysis loops to search for data.
|
|
/// </summary>
|
|
public DateTime StartingDate { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Maximum number of orders for the algorithm run -- applicable for backtests only.
|
|
/// </summary>
|
|
public int MaxOrders { get; }
|
|
|
|
// saves ref to algo so we can call quit if runtime error encountered
|
|
private IBrokerageFactory _factory;
|
|
private IBrokerage _dataQueueHandlerBrokerage;
|
|
|
|
/// <summary>
|
|
/// Initializes a new BrokerageSetupHandler
|
|
/// </summary>
|
|
public BrokerageSetupHandler()
|
|
{
|
|
Errors = new List<Exception>();
|
|
MaximumRuntime = TimeSpan.FromDays(10*365);
|
|
MaxOrders = int.MaxValue;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create a new instance of an algorithm from a physical dll path.
|
|
/// </summary>
|
|
/// <param name="assemblyPath">The path to the assembly's location</param>
|
|
/// <param name="algorithmNodePacket">Details of the task required</param>
|
|
/// <returns>A new instance of IAlgorithm, or throws an exception if there was an error</returns>
|
|
public IAlgorithm CreateAlgorithmInstance(AlgorithmNodePacket algorithmNodePacket, string assemblyPath)
|
|
{
|
|
string error;
|
|
IAlgorithm algorithm;
|
|
|
|
// limit load times to 10 seconds and force the assembly to have exactly one derived type
|
|
var loader = new Loader(false, algorithmNodePacket.Language, TimeSpan.FromSeconds(60), names => names.SingleOrAlgorithmTypeName(Config.Get("algorithm-type-name")), WorkerThread);
|
|
var complete = loader.TryCreateAlgorithmInstanceWithIsolator(assemblyPath, algorithmNodePacket.RamAllocation, out algorithm, out error);
|
|
if (!complete) throw new AlgorithmSetupException($"During the algorithm initialization, the following exception has occurred: {error}");
|
|
|
|
return algorithm;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Creates the brokerage as specified by the job packet
|
|
/// </summary>
|
|
/// <param name="algorithmNodePacket">Job packet</param>
|
|
/// <param name="uninitializedAlgorithm">The algorithm instance before Initialize has been called</param>
|
|
/// <param name="factory">The brokerage factory</param>
|
|
/// <returns>The brokerage instance, or throws if error creating instance</returns>
|
|
public IBrokerage CreateBrokerage(AlgorithmNodePacket algorithmNodePacket, IAlgorithm uninitializedAlgorithm, out IBrokerageFactory factory)
|
|
{
|
|
var liveJob = algorithmNodePacket as LiveNodePacket;
|
|
if (liveJob == null)
|
|
{
|
|
throw new ArgumentException("BrokerageSetupHandler.CreateBrokerage requires a live node packet");
|
|
}
|
|
|
|
// find the correct brokerage factory based on the specified brokerage in the live job packet
|
|
_factory = Composer.Instance.Single<IBrokerageFactory>(brokerageFactory => brokerageFactory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
|
|
factory = _factory;
|
|
|
|
PreloadDataQueueHandler(liveJob, uninitializedAlgorithm, factory);
|
|
|
|
// initialize the correct brokerage using the resolved factory
|
|
var brokerage = _factory.CreateBrokerage(liveJob, uninitializedAlgorithm);
|
|
|
|
return brokerage;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Primary entry point to setup a new algorithm
|
|
/// </summary>
|
|
/// <param name="parameters">The parameters object to use</param>
|
|
/// <returns>True on successfully setting up the algorithm state, or false on error.</returns>
|
|
public bool Setup(SetupHandlerParameters parameters)
|
|
{
|
|
var algorithm = parameters.Algorithm;
|
|
var brokerage = parameters.Brokerage;
|
|
// verify we were given the correct job packet type
|
|
var liveJob = parameters.AlgorithmNodePacket as LiveNodePacket;
|
|
if (liveJob == null)
|
|
{
|
|
AddInitializationError("BrokerageSetupHandler requires a LiveNodePacket");
|
|
return false;
|
|
}
|
|
|
|
algorithm.Name = liveJob.GetAlgorithmName();
|
|
|
|
// verify the brokerage was specified
|
|
if (string.IsNullOrWhiteSpace(liveJob.Brokerage))
|
|
{
|
|
AddInitializationError("A brokerage must be specified");
|
|
return false;
|
|
}
|
|
|
|
|
|
// attach to the message event to relay brokerage specific initialization messages
|
|
EventHandler<BrokerageMessageEvent> brokerageOnMessage = (sender, args) =>
|
|
{
|
|
if (args.Type == BrokerageMessageType.Error)
|
|
{
|
|
AddInitializationError($"Brokerage Error Code: {args.Code} - {args.Message}");
|
|
}
|
|
};
|
|
|
|
try
|
|
{
|
|
// let the world know what we're doing since logging in can take a minute
|
|
parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.LoggingIn, "Logging into brokerage...");
|
|
|
|
brokerage.Message += brokerageOnMessage;
|
|
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Connecting to brokerage...");
|
|
try
|
|
{
|
|
// this can fail for various reasons, such as already being logged in somewhere else
|
|
brokerage.Connect();
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
Log.Error(err);
|
|
AddInitializationError(
|
|
$"Error connecting to brokerage: {err.Message}. " +
|
|
"This may be caused by incorrect login credentials or an unsupported account type.", err);
|
|
return false;
|
|
}
|
|
|
|
if (!brokerage.IsConnected)
|
|
{
|
|
// if we're reporting that we're not connected, bail
|
|
AddInitializationError("Unable to connect to brokerage.");
|
|
return false;
|
|
}
|
|
|
|
var message = $"{brokerage.Name} account base currency: {brokerage.AccountBaseCurrency ?? algorithm.AccountCurrency}";
|
|
|
|
Log.Trace($"BrokerageSetupHandler.Setup(): {message}");
|
|
|
|
algorithm.Debug(message);
|
|
|
|
if (brokerage.AccountBaseCurrency != null && brokerage.AccountBaseCurrency != algorithm.AccountCurrency)
|
|
{
|
|
algorithm.SetAccountCurrency(brokerage.AccountBaseCurrency);
|
|
}
|
|
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Initializing algorithm...");
|
|
|
|
parameters.ResultHandler.SendStatusUpdate(AlgorithmStatus.Initializing, "Initializing algorithm...");
|
|
|
|
//Execute the initialize code:
|
|
var controls = liveJob.Controls;
|
|
var isolator = new Isolator();
|
|
var initializeComplete = isolator.ExecuteWithTimeLimit(TimeSpan.FromSeconds(300), () =>
|
|
{
|
|
try
|
|
{
|
|
//Set the default brokerage model before initialize
|
|
algorithm.SetBrokerageModel(_factory.GetBrokerageModel(algorithm.Transactions));
|
|
|
|
//Margin calls are disabled by default in live mode
|
|
algorithm.Portfolio.MarginCallModel = MarginCallModel.Null;
|
|
|
|
//Set our parameters
|
|
algorithm.SetParameters(liveJob.Parameters);
|
|
algorithm.SetAvailableDataTypes(GetConfiguredDataFeeds());
|
|
|
|
//Algorithm is live, not backtesting:
|
|
algorithm.SetLiveMode(true);
|
|
|
|
//Initialize the algorithm's starting date
|
|
algorithm.SetDateTime(DateTime.UtcNow);
|
|
|
|
//Set the source impl for the event scheduling
|
|
algorithm.Schedule.SetEventSchedule(parameters.RealTimeHandler);
|
|
|
|
// set the option chain provider
|
|
algorithm.SetOptionChainProvider(new CachingOptionChainProvider(new LiveOptionChainProvider()));
|
|
|
|
// set the future chain provider
|
|
algorithm.SetFutureChainProvider(new CachingFutureChainProvider(new LiveFutureChainProvider()));
|
|
|
|
// set the object store
|
|
algorithm.SetObjectStore(parameters.ObjectStore);
|
|
|
|
// If we're going to receive market data from IB,
|
|
// set the default subscription limit to 100,
|
|
// algorithms can override this setting in the Initialize method
|
|
if (brokerage is InteractiveBrokersBrokerage &&
|
|
liveJob.DataQueueHandler.EndsWith("InteractiveBrokersBrokerage"))
|
|
{
|
|
algorithm.Settings.DataSubscriptionLimit = 100;
|
|
}
|
|
|
|
//Initialise the algorithm, get the required data:
|
|
algorithm.Initialize();
|
|
|
|
if (liveJob.Brokerage != "PaperBrokerage")
|
|
{
|
|
//Zero the CashBook - we'll populate directly from brokerage
|
|
foreach (var kvp in algorithm.Portfolio.CashBook)
|
|
{
|
|
kvp.Value.SetAmount(0);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
AddInitializationError(err.ToString(), err);
|
|
}
|
|
}, controls.RamAllocation,
|
|
sleepIntervalMillis: 50); // entire system is waiting on this, so be as fast as possible
|
|
|
|
if (!initializeComplete)
|
|
{
|
|
AddInitializationError("Initialization timed out.");
|
|
return false;
|
|
}
|
|
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Fetching cash balance from brokerage...");
|
|
try
|
|
{
|
|
// set the algorithm's cash balance for each currency
|
|
var cashBalance = brokerage.GetCashBalance();
|
|
foreach (var cash in cashBalance)
|
|
{
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Setting " + cash.Currency + " cash to " + cash.Amount);
|
|
|
|
algorithm.Portfolio.SetCash(cash.Currency, cash.Amount, 0);
|
|
}
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
Log.Error(err);
|
|
AddInitializationError("Error getting cash balance from brokerage: " + err.Message, err);
|
|
return false;
|
|
}
|
|
|
|
var supportedSecurityTypes = new HashSet<SecurityType>
|
|
{
|
|
SecurityType.Equity, SecurityType.Forex, SecurityType.Cfd, SecurityType.Option, SecurityType.Future, SecurityType.FutureOption, SecurityType.Crypto
|
|
};
|
|
var minResolution = new Lazy<Resolution>(() => algorithm.Securities.Select(x => x.Value.Resolution).DefaultIfEmpty(Resolution.Second).Min());
|
|
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Fetching open orders from brokerage...");
|
|
try
|
|
{
|
|
GetOpenOrders(algorithm, parameters.ResultHandler, parameters.TransactionHandler, brokerage, supportedSecurityTypes, minResolution.Value);
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
Log.Error(err);
|
|
AddInitializationError("Error getting open orders from brokerage: " + err.Message, err);
|
|
return false;
|
|
}
|
|
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Fetching holdings from brokerage...");
|
|
try
|
|
{
|
|
var utcNow = DateTime.UtcNow;
|
|
|
|
// populate the algorithm with the account's current holdings
|
|
var holdings = brokerage.GetAccountHoldings();
|
|
|
|
// add options first to ensure raw data normalization mode is set on the equity underlyings
|
|
foreach (var holding in holdings.OrderByDescending(x => x.Type))
|
|
{
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Has existing holding: " + holding);
|
|
|
|
// verify existing holding security type
|
|
if (!supportedSecurityTypes.Contains(holding.Type))
|
|
{
|
|
Log.Error("BrokerageSetupHandler.Setup(): Unsupported security type: " + holding.Type + "-" + holding.Symbol.Value);
|
|
AddInitializationError("Found unsupported security type in existing brokerage holdings: " + holding.Type + ". " +
|
|
"QuantConnect currently supports the following security types: " + string.Join(",", supportedSecurityTypes));
|
|
|
|
// keep aggregating these errors
|
|
continue;
|
|
}
|
|
|
|
AddUnrequestedSecurity(algorithm, holding.Symbol, minResolution.Value);
|
|
|
|
var security = algorithm.Securities[holding.Symbol];
|
|
var exchangeTime = utcNow.ConvertFromUtc(security.Exchange.TimeZone);
|
|
|
|
security.Holdings.SetHoldings(holding.AveragePrice, holding.Quantity);
|
|
security.SetMarketPrice(new TradeBar
|
|
{
|
|
Time = exchangeTime,
|
|
Open = holding.MarketPrice,
|
|
High = holding.MarketPrice,
|
|
Low = holding.MarketPrice,
|
|
Close = holding.MarketPrice,
|
|
Volume = 0,
|
|
Symbol = holding.Symbol,
|
|
DataType = MarketDataType.TradeBar
|
|
});
|
|
}
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
Log.Error(err);
|
|
AddInitializationError("Error getting account holdings from brokerage: " + err.Message, err);
|
|
return false;
|
|
}
|
|
|
|
//Finalize Initialization
|
|
algorithm.PostInitialize();
|
|
|
|
BaseSetupHandler.SetupCurrencyConversions(algorithm, parameters.UniverseSelection);
|
|
|
|
if (algorithm.Portfolio.TotalPortfolioValue == 0)
|
|
{
|
|
algorithm.Debug("Warning: No cash balances or holdings were found in the brokerage account.");
|
|
}
|
|
|
|
//Set the starting portfolio value for the strategy to calculate performance:
|
|
StartingPortfolioValue = algorithm.Portfolio.TotalPortfolioValue;
|
|
StartingDate = DateTime.Now;
|
|
|
|
// we set the free portfolio value based on the initial total value and the free percentage value
|
|
algorithm.Settings.FreePortfolioValue =
|
|
algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage;
|
|
}
|
|
catch (Exception err)
|
|
{
|
|
AddInitializationError(err.ToString(), err);
|
|
}
|
|
finally
|
|
{
|
|
if (brokerage != null)
|
|
{
|
|
brokerage.Message -= brokerageOnMessage;
|
|
}
|
|
}
|
|
|
|
return Errors.Count == 0;
|
|
}
|
|
|
|
private static void AddUnrequestedSecurity(IAlgorithm algorithm, Symbol symbol, Resolution minResolution)
|
|
{
|
|
if (!algorithm.Portfolio.ContainsKey(symbol))
|
|
{
|
|
Log.Trace("BrokerageSetupHandler.Setup(): Adding unrequested security: " + symbol.Value);
|
|
|
|
if (symbol.SecurityType == SecurityType.Option || symbol.SecurityType == SecurityType.FutureOption)
|
|
{
|
|
// add current option contract to the system
|
|
algorithm.AddOptionContract(symbol, minResolution, true, 1.0m);
|
|
}
|
|
else if (symbol.SecurityType == SecurityType.Future)
|
|
{
|
|
// add current future contract to the system
|
|
algorithm.AddFutureContract(symbol, minResolution, true, 1.0m);
|
|
}
|
|
else
|
|
{
|
|
// for items not directly requested set leverage to 1 and at the min resolution
|
|
algorithm.AddSecurity(symbol.SecurityType, symbol.Value, minResolution, symbol.ID.Market, true, 1.0m, false);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get the open orders from a brokerage. Adds <see cref="Orders.Order"/> and <see cref="Orders.OrderTicket"/> to the transaction handler
|
|
/// </summary>
|
|
/// <param name="algorithm">Algorithm instance</param>
|
|
/// <param name="resultHandler">The configured result handler</param>
|
|
/// <param name="transactionHandler">The configurated transaction handler</param>
|
|
/// <param name="brokerage">Brokerage output instance</param>
|
|
/// <param name="supportedSecurityTypes">The list of supported security types</param>
|
|
/// <param name="minResolution">The resolution for the security to add, if required</param>
|
|
protected void GetOpenOrders(IAlgorithm algorithm, IResultHandler resultHandler, ITransactionHandler transactionHandler, IBrokerage brokerage,
|
|
HashSet<SecurityType> supportedSecurityTypes, Resolution minResolution)
|
|
{
|
|
// populate the algorithm with the account's outstanding orders
|
|
var openOrders = brokerage.GetOpenOrders();
|
|
|
|
// add options first to ensure raw data normalization mode is set on the equity underlyings
|
|
foreach (var order in openOrders.OrderByDescending(x => x.SecurityType))
|
|
{
|
|
// be sure to assign order IDs such that we increment from the SecurityTransactionManager to avoid ID collisions
|
|
order.Id = algorithm.Transactions.GetIncrementOrderId();
|
|
|
|
Log.Trace($"BrokerageSetupHandler.Setup(): Has open order: {order}");
|
|
resultHandler.DebugMessage($"BrokerageSetupHandler.Setup(): Open order detected. Creating order tickets for open order {order.Symbol.Value} with quantity {order.Quantity}. Beware that this order ticket may not accurately reflect the quantity of the order if the open order is partially filled.");
|
|
|
|
transactionHandler.AddOpenOrder(order, order.ToOrderTicket(algorithm.Transactions));
|
|
|
|
// verify existing holding security type
|
|
if (!supportedSecurityTypes.Contains(order.SecurityType))
|
|
{
|
|
Log.Error("BrokerageSetupHandler.Setup(): Unsupported security type: " + order.SecurityType + "-" + order.Symbol.Value);
|
|
AddInitializationError("Found unsupported security type in existing brokerage open orders: " + order.SecurityType + ". " +
|
|
"QuantConnect currently supports the following security types: " + string.Join(",", supportedSecurityTypes));
|
|
|
|
// keep aggregating these errors
|
|
continue;
|
|
}
|
|
|
|
AddUnrequestedSecurity(algorithm, order.Symbol, minResolution);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get the available data feeds from config.json,
|
|
/// If none available, throw an error
|
|
/// </summary>
|
|
private static Dictionary<SecurityType, List<TickType>> GetConfiguredDataFeeds()
|
|
{
|
|
var dataFeedsConfigString = Config.Get("security-data-feeds");
|
|
|
|
Dictionary<SecurityType, List<TickType>> dataFeeds = new Dictionary<SecurityType, List<TickType>>();
|
|
if (dataFeedsConfigString != string.Empty)
|
|
{
|
|
dataFeeds = JsonConvert.DeserializeObject<Dictionary<SecurityType, List<TickType>>>(dataFeedsConfigString);
|
|
}
|
|
|
|
return dataFeeds;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds initialization error to the Errors list
|
|
/// </summary>
|
|
/// <param name="message">The error message to be added</param>
|
|
/// <param name="inner">The inner exception being wrapped</param>
|
|
private void AddInitializationError(string message, Exception inner = null)
|
|
{
|
|
Errors.Add(new AlgorithmSetupException("During the algorithm initialization, the following exception has occurred: " + message, inner));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
|
|
/// </summary>
|
|
/// <filterpriority>2</filterpriority>
|
|
public void Dispose()
|
|
{
|
|
_factory?.DisposeSafely();
|
|
|
|
if (_dataQueueHandlerBrokerage != null)
|
|
{
|
|
if (_dataQueueHandlerBrokerage.IsConnected)
|
|
{
|
|
_dataQueueHandlerBrokerage.Disconnect();
|
|
}
|
|
_dataQueueHandlerBrokerage.DisposeSafely();
|
|
}
|
|
else
|
|
{
|
|
var dataQueueHandler = Composer.Instance.GetPart<IDataQueueHandler>();
|
|
if (dataQueueHandler != null)
|
|
{
|
|
Log.Trace($"BrokerageSetupHandler.Setup(): Found data queue handler to dispose: {dataQueueHandler.GetType()}");
|
|
dataQueueHandler.DisposeSafely();
|
|
}
|
|
else
|
|
{
|
|
Log.Trace("BrokerageSetupHandler.Setup(): did not find any data queue handler to dispose");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void PreloadDataQueueHandler(LiveNodePacket liveJob, IAlgorithm algorithm, IBrokerageFactory factory)
|
|
{
|
|
// preload the data queue handler using custom BrokerageFactory attribute
|
|
var dataQueueHandlerType = Assembly.GetAssembly(typeof(Brokerage))
|
|
.GetTypes()
|
|
.FirstOrDefault(x =>
|
|
x.FullName != null &&
|
|
x.FullName.EndsWith(liveJob.DataQueueHandler) &&
|
|
x.HasAttribute(typeof(BrokerageFactoryAttribute)));
|
|
|
|
if (dataQueueHandlerType != null)
|
|
{
|
|
var attribute = dataQueueHandlerType.GetCustomAttribute<BrokerageFactoryAttribute>();
|
|
|
|
// only load the data queue handler if the factory is different from our brokerage factory
|
|
if (attribute.Type != factory.GetType())
|
|
{
|
|
var brokerageFactory = (BrokerageFactory)Activator.CreateInstance(attribute.Type);
|
|
|
|
// copy the brokerage data (usually credentials)
|
|
foreach (var kvp in brokerageFactory.BrokerageData)
|
|
{
|
|
if (!liveJob.BrokerageData.ContainsKey(kvp.Key))
|
|
{
|
|
liveJob.BrokerageData.Add(kvp.Key, kvp.Value);
|
|
}
|
|
}
|
|
|
|
// create the data queue handler and add it to composer
|
|
_dataQueueHandlerBrokerage = brokerageFactory.CreateBrokerage(liveJob, algorithm);
|
|
|
|
// open connection for subscriptions
|
|
_dataQueueHandlerBrokerage.Connect();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|