/*
* 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 NodaTime;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using System.Collections.Concurrent;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
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;
}
///
/// 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 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.
///
/// Not currently used but preserved for API integrity
string Name
{
get;
set;
}
///
/// 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;
}
///
/// 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;
}
///
/// 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;
}
///
/// 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 the parameter with the specified name. If a parameter
/// with the specified name does not exist, null is returned
///
/// The name of the parameter to get
/// The value of the specified parameter, or null if not found
string GetParameter(string name);
///
/// Sets the parameters from the dictionary
///
/// Dictionary containing the parameter names to values
void SetParameters(Dictionary parameters);
///
/// 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);
//
// v1.0 Handler for Tick Events [DEPRECATED June-2014]
//
// Tick Data Packet
//void OnTick(Dictionary> ticks);
//
// v1.0 Handler for TradeBar Events [DEPRECATED June-2014]
//
// TradeBar Data Packet
//void OnTradeBar(Dictionary tradebars);
//
// v2.0 Handler for Generic Data Events
//
//void OnData(Ticks ticks);
//void OnData(TradeBars tradebars);
///
/// 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 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)")]
void OnEndOfDay();
///
/// Call this method at the end of each day of data.
///
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);
///
/// 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 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
List 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
Security AddSecurity(SecurityType securityType, string symbol, Resolution resolution, string market, bool fillDataForward, decimal leverage, bool extendedMarketHours);
///
/// 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
/// The new security
Future AddFutureContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 0m);
///
/// 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
/// The new security
Option AddOptionContract(Symbol symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, decimal leverage = 0m);
///
/// 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.
///
/// Has to be called during before
/// calling or adding any
/// The account currency cash symbol to set
void SetAccountCurrency(string accountCurrency);
///
/// 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.
/// Custom tag to know who is calling this.
/// list of order ids
List Liquidate(Symbol symbolToLiquidate = null, string tag = "Liquidated");
///
/// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode.
///
/// Bool live mode flag
void SetLiveMode(bool live);
///
/// Sets to false to indicate this algorithm has finished its warm up
///
void SetFinishedWarmingUp();
///
/// Gets the date/time warmup should begin
///
///
IEnumerable GetWarmupHistoryRequests();
///
/// Set the maximum number of orders the algortihm 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);
///
/// 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 order event provider
///
/// The order event provider
/// Will be called before the
void SetOrderEventProvider(IOrderEventProvider newOrderEvent);
}
}