/*
* 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 NodaTime;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Storage;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Statistics;
using QuantConnect.Data.Market;
using QuantConnect.Notifications;
using System.Collections.Generic;
using System.Collections.Concurrent;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Alphas.Analysis;
using QuantConnect.Commands;
namespace QuantConnect.Interfaces
{
///
/// Defines an event fired from within an algorithm instance.
///
/// The event type
/// The algorithm that fired the event
/// The event data
public delegate void AlgorithmEvent(IAlgorithm algorithm, T eventData);
///
/// Interface for QuantConnect algorithm implementations. All algorithms must implement these
/// basic members to allow interaction with the Lean Backtesting Engine.
///
public interface IAlgorithm : ISecurityInitializerProvider, IAccountCurrencyProvider
{
///
/// Event fired when an algorithm generates a insight
///
event AlgorithmEvent InsightsGenerated;
///
/// Gets the time keeper instance
///
ITimeKeeper TimeKeeper
{
get;
}
///
/// Data subscription manager controls the information and subscriptions the algorithms recieves.
/// Subscription configurations can be added through the Subscription Manager.
///
SubscriptionManager SubscriptionManager
{
get;
}
///
/// The project id associated with this algorithm if any
///
int ProjectId
{
get;
set;
}
///
/// Security object collection class stores an array of objects representing representing each security/asset
/// we have a subscription for.
///
/// It is an IDictionary implementation and can be indexed by symbol
SecurityManager Securities
{
get;
}
///
/// Gets the collection of universes for the algorithm
///
UniverseManager UniverseManager
{
get;
}
///
/// Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as
/// IsLong, IsShort, TotalProfit
///
/// Portfolio is a wrapper and helper class encapsulating the Securities[].Holdings objects
SecurityPortfolioManager Portfolio
{
get;
}
///
/// Security transaction manager class controls the store and processing of orders.
///
/// The orders and their associated events are accessible here. When a new OrderEvent is recieved the algorithm portfolio is updated.
SecurityTransactionManager Transactions
{
get;
}
///
/// Gets the brokerage model used to emulate a real brokerage
///
IBrokerageModel BrokerageModel
{
get;
}
///
/// Gets the brokerage name.
///
BrokerageName BrokerageName
{
get;
}
///
/// Gets the risk free interest rate model used to get the interest rates
///
IRiskFreeInterestRateModel RiskFreeInterestRateModel
{
get;
}
///
/// Gets the brokerage message handler used to decide what to do
/// with each message sent from the brokerage
///
IBrokerageMessageHandler BrokerageMessageHandler
{
get;
set;
}
///
/// Notification manager for storing and processing live event messages
///
NotificationManager Notify
{
get;
}
///
/// Gets schedule manager for adding/removing scheduled events
///
ScheduleManager Schedule
{
get;
}
///
/// Gets or sets the history provider for the algorithm
///
IHistoryProvider HistoryProvider
{
get;
set;
}
///
/// Gets or sets the current status of the algorithm
///
AlgorithmStatus Status
{
get;
set;
}
///
/// Gets whether or not this algorithm is still warming up
///
bool IsWarmingUp
{
get;
}
///
/// Public name for the algorithm.
///
string Name
{
get;
set;
}
///
/// A list of tags associated with the algorithm or the backtest, useful for categorization
///
HashSet Tags
{
get;
set;
}
///
/// Event fired algorithm's name is changed
///
event AlgorithmEvent NameUpdated;
///
/// Event fired when the tag collection is updated
///
event AlgorithmEvent> TagsUpdated;
///
/// Current date/time in the algorithm's local time zone
///
DateTime Time
{
get;
}
///
/// Gets the time zone of the algorithm
///
DateTimeZone TimeZone
{
get;
}
///
/// Current date/time in UTC.
///
DateTime UtcTime
{
get;
}
///
/// Algorithm start date for backtesting, set by the SetStartDate methods.
///
DateTime StartDate
{
get;
}
///
/// Get Requested Backtest End Date
///
DateTime EndDate
{
get;
}
///
/// AlgorithmId for the backtest
///
string AlgorithmId
{
get;
}
///
/// Algorithm is running on a live server.
///
bool LiveMode
{
get;
}
///
/// Algorithm running mode.
///
AlgorithmMode AlgorithmMode
{
get;
}
///
/// Deployment target, either local or cloud.
///
DeploymentTarget DeploymentTarget
{
get;
}
///
/// Gets the subscription settings to be used when adding securities via universe selection
///
UniverseSettings UniverseSettings
{
get;
}
///
/// Debug messages from the strategy:
///
ConcurrentQueue DebugMessages
{
get;
}
///
/// Error messages from the strategy:
///
ConcurrentQueue ErrorMessages
{
get;
}
///
/// Log messages from the strategy:
///
ConcurrentQueue LogMessages
{
get;
}
///
/// Gets the run time error from the algorithm, or null if none was encountered.
///
Exception RunTimeError
{
get;
set;
}
///
/// Customizable dynamic statistics displayed during live trading:
///
ConcurrentDictionary RuntimeStatistics
{
get;
}
///
/// The current algorithm statistics for the running algorithm.
///
StatisticsResults Statistics
{
get;
}
///
/// Gets the function used to define the benchmark. This function will return
/// the value of the benchmark at a requested date/time
///
IBenchmark Benchmark
{
get;
}
///
/// Gets the Trade Builder to generate trades from executions
///
ITradeBuilder TradeBuilder
{
get;
}
///
/// Gets the user settings for the algorithm
///
IAlgorithmSettings Settings
{
get;
}
///
/// Gets the option chain provider, used to get the list of option contracts for an underlying symbol
///
IOptionChainProvider OptionChainProvider
{
get;
}
///
/// Gets the future chain provider, used to get the list of future contracts for an underlying symbol
///
IFutureChainProvider FutureChainProvider
{
get;
}
///
/// Gets the insight manager
///
InsightManager Insights
{
get;
}
///
/// Gets the object store, used for persistence
///
ObjectStore ObjectStore { get; }
///
/// Returns the current Slice object
///
Slice CurrentSlice { get; }
///
/// Initialise the Algorithm and Prepare Required Data:
///
void Initialize();
///
/// Called by setup handlers after Initialize and allows the algorithm a chance to organize
/// the data gather in the Initialize method
///
void PostInitialize();
///
/// Called when the algorithm has completed initialization and warm up.
///
void OnWarmupFinished();
///
/// Gets a read-only dictionary with all current parameters
///
IReadOnlyDictionary GetParameters();
///
/// Gets the parameter with the specified name. If a parameter with the specified name does not exist,
/// the given default value is returned if any, else null
///
/// The name of the parameter to get
/// The default value to return
/// The value of the specified parameter, or defaultValue if not found or null if there's no default value
string GetParameter(string name, string defaultValue = null);
///
/// Gets the parameter with the specified name parsed as an integer. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
///
/// The name of the parameter to get
/// The default value to return
/// The value of the specified parameter, or defaultValue if not found or null if there's no default value
int GetParameter(string name, int defaultValue);
///
/// Gets the parameter with the specified name parsed as a double. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
///
/// The name of the parameter to get
/// The default value to return
/// The value of the specified parameter, or defaultValue if not found or null if there's no default value
double GetParameter(string name, double defaultValue);
///
/// Gets the parameter with the specified name parsed as a decimal. If a parameter with the specified name does not exist,
/// or the conversion is not possible, the given default value is returned
///
/// The name of the parameter to get
/// The default value to return
/// The value of the specified parameter, or defaultValue if not found or null if there's no default value
decimal GetParameter(string name, decimal defaultValue);
///
/// Sets the parameters from the dictionary
///
/// Dictionary containing the parameter names to values
void SetParameters(Dictionary parameters);
///
/// Determines if the Symbol is shortable at the brokerage
///
/// Symbol to check if shortable
/// Order's quantity to check if it is currently shortable, taking into account current holdings and open orders
/// Optionally the id of the order being updated. When updating an order
/// we want to ignore it's submitted short quantity and use the new provided quantity to determine if we
/// can perform the update
/// True if the symbol can be shorted by the requested quantity
bool Shortable(Symbol symbol, decimal shortQuantity, int? updateOrderId = null);
///
/// Gets the quantity shortable for the given asset
///
///
/// Quantity shortable for the given asset. Zero if not
/// shortable, or a number greater than zero if shortable.
///
long ShortableQuantity(Symbol symbol);
///
/// Sets the brokerage model used to resolve transaction models, settlement models,
/// and brokerage specified ordering behaviors.
///
/// The brokerage model used to emulate the real
/// brokerage
void SetBrokerageModel(IBrokerageModel brokerageModel);
///
/// v3.0 Handler for all data types
///
/// The current slice of data
void OnData(Slice slice);
///
/// Used to send data updates to algorithm framework models
///
/// The current data slice
void OnFrameworkData(Slice slice);
///
/// Event handler to be called when there's been a split event
///
/// The current time slice splits
void OnSplits(Splits splits);
///
/// Event handler to be called when there's been a dividend event
///
/// The current time slice dividends
void OnDividends(Dividends dividends);
///
/// Event handler to be called when there's been a delistings event
///
/// The current time slice delistings
void OnDelistings(Delistings delistings);
///
/// Event handler to be called when there's been a symbol changed event
///
/// The current time slice symbol changed events
void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged);
///
/// Event fired each time that we add/remove securities from the data feed
///
/// Security additions/removals for this time step
void OnSecuritiesChanged(SecurityChanges changes);
///
/// Used to send security changes to algorithm framework models
///
/// Security additions/removals for this time step
void OnFrameworkSecuritiesChanged(SecurityChanges changes);
///
/// Invoked at the end of every time step. This allows the algorithm
/// to process events before advancing to the next time step.
///
void OnEndOfTimeStep();
///
/// Send debug message
///
///
void Debug(string message);
///
/// Save entry to the Log
///
/// String message
void Log(string message);
///
/// Send an error message for the algorithm
///
/// String message
void Error(string message);
///
/// Margin call event handler. This method is called right before the margin call orders are placed in the market.
///
/// The orders to be executed to bring this algorithm within margin limits
void OnMarginCall(List requests);
///
/// Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue
///
void OnMarginCallWarning();
///
/// Call this method at the end of each day of data.
///
/// Deprecated because different assets have different market close times,
/// and because Python does not support two methods with the same name
[Obsolete("This method is deprecated. Please use this overload: OnEndOfDay(Symbol symbol)")]
[StubsIgnore]
void OnEndOfDay();
///
/// Call this method at the end of each day of data.
///
[StubsAvoidImplicits]
void OnEndOfDay(Symbol symbol);
///
/// Call this event at the end of the algorithm running.
///
void OnEndOfAlgorithm();
///
/// EXPERTS ONLY:: [-!-Async Code-!-]
/// New order event handler: on order status changes (filled, partially filled, cancelled etc).
///
/// Event information
void OnOrderEvent(OrderEvent newEvent);
///
/// Generic untyped command call handler
///
/// The associated data
/// True if success, false otherwise. Returning null will disable command feedback
bool? OnCommand(dynamic data);
///
/// Will submit an order request to the algorithm
///
/// The request to submit
/// Will run order prechecks, which include making sure the algorithm is not warming up, security is added and has data among others
/// The order ticket
OrderTicket SubmitOrderRequest(SubmitOrderRequest request);
///
/// Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method.
///
/// Option exercise event details containing details of the assignment
/// This method can be called asynchronously and so should only be used by seasoned C# experts. Ensure you use proper locks on thread-unsafe objects
void OnAssignmentOrderEvent(OrderEvent assignmentEvent);
///
/// Brokerage message event handler. This method is called for all types of brokerage messages.
///
void OnBrokerageMessage(BrokerageMessageEvent messageEvent);
///
/// Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
///
void OnBrokerageDisconnect();
///
/// Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
///
void OnBrokerageReconnect();
///
/// Set the DateTime Frontier: This is the master time and is
///
///
void SetDateTime(DateTime time);
///
/// Set the start date for the backtest
///
/// Datetime Start date for backtest
/// Must be less than end date and within data available
void SetStartDate(DateTime start);
///
/// Set the end date for a backtest.
///
/// Datetime value for end date
/// Must be greater than the start date
void SetEndDate(DateTime end);
///
/// Set the algorithm Id for this backtest or live run. This can be used to identify the order and equity records.
///
/// unique 32 character identifier for backtest or live server
void SetAlgorithmId(string algorithmId);
///
/// Set the algorithm as initialized and locked. No more cash or security changes.
///
void SetLocked();
///
/// Gets whether or not this algorithm has been locked and fully initialized
///
bool GetLocked();
///
/// Add a Chart object to algorithm collection
///
/// Chart object to add to collection.
void AddChart(Chart chart);
///
/// Get the chart updates since the last request:
///
///
/// List of Chart Updates
IEnumerable GetChartUpdates(bool clearChartData = false);
///
/// Set a required SecurityType-symbol and resolution for algorithm
///
/// SecurityType Enum: Equity, Commodity, FOREX or Future
/// Symbol Representation of the MarketType, e.g. AAPL
/// Resolution of the MarketType required: MarketData, Second or Minute
/// The market the requested security belongs to, such as 'usa' or 'fxcm'
/// If true, returns the last available data even if none in that timeslice.
/// leverage for this security
/// ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX
/// The contract mapping mode to use for the security
/// The price scaling mode to use for the security
Security AddSecurity(SecurityType securityType, string symbol, Resolution? resolution, string market, bool fillForward, decimal leverage, bool extendedMarketHours,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null);
///
/// Set a required SecurityType-symbol and resolution for algorithm
///
/// The security Symbol
/// Resolution of the MarketType required: MarketData, Second or Minute
/// If true, returns the last available data even if none in that timeslice.
/// leverage for this security
/// Use extended market hours data
/// The contract mapping mode to use for the security
/// The price scaling mode to use for the security
/// The continuous contract desired offset from the current front month.
/// For example, 0 (default) will use the front month, 1 will use the back month contract
/// The new Security that was added to the algorithm
Security AddSecurity(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = Security.NullLeverage, bool extendedMarketHours = false,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int contractDepthOffset = 0);
///
/// Creates and adds a new single contract to the algorithm
///
/// The futures contract symbol
/// The of market data, Tick, Second, Minute, Hour, or Daily. Default is
/// If true, returns the last available data even if none in that timeslice. Default is true
/// The requested leverage for this equity. Default is set by
/// Show the after market data as well
/// The new security
Future AddFutureContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m, bool extendedMarketHours = false);
///
/// Creates and adds a new single contract to the algorithm
///
/// The option contract symbol
/// The of market data, Tick, Second, Minute, Hour, or Daily. Default is
/// If true, returns the last available data even if none in that timeslice. Default is true
/// The requested leverage for this equity. Default is set by
/// Show the after market data as well
/// The new security
Option AddOptionContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m, bool extendedMarketHours = false);
///
/// Removes the security with the specified symbol. This will cancel all
/// open orders and then liquidate any existing holdings
///
/// The symbol of the security to be removed
bool RemoveSecurity(Symbol symbol);
///
/// Sets the account currency cash symbol this algorithm is to manage, as well as
/// the starting cash in this currency if given
///
/// Has to be called during before
/// calling or adding any
/// The account currency cash symbol to set
/// The account currency starting cash to set
void SetAccountCurrency(string accountCurrency, decimal? startingCash = null);
///
/// Set the starting capital for the strategy
///
/// decimal starting capital, default $100,000
void SetCash(decimal startingCash);
///
/// Set the cash for the specified symbol
///
/// The cash symbol to set
/// Decimal cash value of portfolio
/// The current conversion rate for the
void SetCash(string symbol, decimal startingCash, decimal conversionRate = 0);
///
/// Liquidate your portfolio holdings
///
/// Specific asset to liquidate, defaults to all.
/// Flag to indicate if the symbols should be liquidated asynchronously
/// Custom tag to know who is calling this
/// Order properties to use
List Liquidate(Symbol symbol = null, bool asynchronous = false, string tag = "Liquidated", IOrderProperties orderProperties = null);
///
/// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode.
///
/// Bool live mode flag
void SetLiveMode(bool live);
///
/// Sets the algorithm running mode
///
/// Algorithm mode
void SetAlgorithmMode(AlgorithmMode algorithmMode);
///
/// Sets the algorithm deployment target
///
/// Deployment target
void SetDeploymentTarget(DeploymentTarget deploymentTarget);
///
/// Sets to false to indicate this algorithm has finished its warm up
///
void SetFinishedWarmingUp();
///
/// Set the maximum number of orders the algorithm is allowed to process.
///
/// Maximum order count int
void SetMaximumOrders(int max);
///
/// Sets the implementation used to handle messages from the brokerage.
/// The default implementation will forward messages to debug or error
/// and when a occurs, the algorithm
/// is stopped.
///
/// The message handler to use
void SetBrokerageMessageHandler(IBrokerageMessageHandler handler);
///
/// Set the historical data provider
///
/// Historical data provider
void SetHistoryProvider(IHistoryProvider historyProvider);
///
/// Get the last known price using the history provider.
/// Useful for seeding securities with the correct price
///
/// object for which to retrieve historical data
/// A single object with the last known price
BaseData GetLastKnownPrice(Security security);
///
/// Set the runtime error
///
/// Represents error that occur during execution
void SetRunTimeError(Exception exception);
///
/// Set the state of a live deployment
///
/// Live deployment status
void SetStatus(AlgorithmStatus status);
///
/// Set the available supported by each in
///
/// >The different each supports
void SetAvailableDataTypes(Dictionary> availableDataTypes);
///
/// Sets the option chain provider, used to get the list of option contracts for an underlying symbol
///
/// The option chain provider
void SetOptionChainProvider(IOptionChainProvider optionChainProvider);
///
/// Sets the future chain provider, used to get the list of future contracts for an underlying symbol
///
/// The future chain provider
void SetFutureChainProvider(IFutureChainProvider futureChainProvider);
///
/// Sets the current slice
///
/// The Slice object
void SetCurrentSlice(Slice slice);
///
/// Provide the API for the algorithm.
///
/// Initiated API
void SetApi(IApi api);
///
/// Sets the object store
///
/// The object store
void SetObjectStore(IObjectStore objectStore);
///
/// Converts the string 'ticker' symbol into a full object
/// This requires that the string 'ticker' has been added to the algorithm
///
/// The ticker symbol. This should be the ticker symbol
/// as it was added to the algorithm
/// The symbol object mapped to the specified ticker
Symbol Symbol(string ticker);
///
/// For the given symbol will resolve the ticker it used at the current algorithm date
///
/// The symbol to get the ticker for
/// The mapped ticker for a symbol
string Ticker(Symbol symbol);
///
/// Sets the statistics service instance to be used by the algorithm
///
/// The statistics service instance
void SetStatisticsService(IStatisticsService statisticsService);
///
/// Sets name to the currently running backtest
///
/// The name for the backtest
void SetName(string name);
///
/// Adds a tag to the algorithm
///
/// The tag to add
void AddTag(string tag);
///
/// Sets the tags for the algorithm
///
/// The tags
void SetTags(HashSet tags);
///
/// Run a callback command instance
///
/// The callback command instance
/// The command result
CommandResultPacket RunCommand(CallbackCommand command);
}
}