/* * 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.Concurrent; using System.Collections.Generic; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Notifications; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Interfaces { /// /// Interface for QuantConnect algorithm implementations. All algorithms must implement these /// basic members to allow interaction with the Lean Backtesting Engine. /// public interface IAlgorithm { /// /// Data subscription manager controls the information and subscriptions the algorithms recieves. /// Subscription configurations can be added through the Subscription Manager. /// SubscriptionManager SubscriptionManager { 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; set; } /// /// 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; set; } /// /// 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; set; } /// /// Gets the brokerage model used to emulate a real brokerage /// IBrokerageModel BrokerageModel { get; } /// /// Notification manager for storing and processing live event messages /// NotificationManager Notify { get; set; } /// /// Public name for the algorithm. /// /// Not currently used but preserved for API integrity string Name { get; set; } /// /// Property indicating the transaction handler is currently processing an order and the algorithm should wait (syncrhonous order processing). /// bool ProcessingOrder { get; set; } /// /// Current date/time. /// DateTime Time { 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; } /// /// Accessor for Filled Orders: /// ConcurrentDictionary Orders { get; } /// /// Run Backtest Mode for the algorithm: Automatic, Parallel or Series. /// RunMode RunMode { get; } /// /// Algorithm is running on a live server. /// bool LiveMode { get; } /// /// Debug messages from the strategy: /// List DebugMessages { get; set; } /// /// Error messages from the strategy: /// List ErrorMessages { get; set; } /// /// Log messages from the strategy: /// List LogMessages { get; set; } /// /// 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: /// Dictionary RuntimeStatistics { get; } /// /// Initialise the Algorithm and Prepare Required Data: /// void Initialize(); // // 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); /// /// 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 orders); /// /// Margin call warning event handler. This method is called when Portoflio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue /// void OnMarginCallWarning(); /// /// Call this method at the end of each day of data. /// void OnEndOfDay(); /// /// Call this method at the end of each day of data. /// void OnEndOfDay(string 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); /// /// Set the DateTime Frontier: This is the master time and is /// /// void SetDateTime(DateTime time); /// /// Set the run mode of the algorithm: series, parallel or automatic. /// /// Run mode to select, default automatic /// The set runmode method is now obsolete and all algorithms are run in series mode. void SetRunMode(RunMode mode = RunMode.Automatic); /// /// Set the start date of the backtest period. This must be within available data. /// void SetStartDate(int year, int month, int day); /// /// Alias for SetStartDate() which accepts DateTime Class /// /// DateTime Object to Start the Algorithm void SetStartDate(DateTime start); /// /// Set the end Backtest date for the algorithm. This must be within available data. /// void SetEndDate(int year, int month, int day); /// /// Alias for SetStartDate() which accepts DateTime Object /// /// DateTime End Date for Analysis 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(); /// /// Get the chart updates since the last request: /// /// /// List of Chart Updates List GetChartUpdates(bool clearChartData = false); /// /// Add a chart to the internal algorithm list. /// /// Chart object to add void AddChart(Chart chart); /// /// 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 /// 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 void AddSecurity(SecurityType securityType, string symbol, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours); /// /// AddData-typeparam name="T"- a new user defined data source, requiring only the minimum config options: /// /// Key/Symbol for data /// Resolution of the data /// Set to true if this data has Open, High, Low, and Close properties /// Set to true if this data has a Volume property void AddData(string symbol, Resolution resolution = Resolution.Second, bool isTradeBar = false, bool hasVolume = false); /// /// 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); /// /// Send an order to the transaction manager. /// /// Symbol we want to purchase /// Quantity to buy, + is long, - short. /// Don't wait for the response, just submit order and move on. /// Custom data for this order /// Integer Order ID. int Order(string symbol, int quantity, bool asynchronous = false, string tag = ""); /// /// Liquidate your portfolio holdings: /// /// Specific asset to liquidate, defaults to all. /// list of order ids List Liquidate(string symbolToLiquidate = ""); /// /// Terminate the algorithm on exiting the current event processor. /// If have holdings at the end of the algorithm/day they will be liquidated at market prices. /// If running a series analysis this command skips the current day (and doesn't liquidate). /// /// Exit message void Quit(string message = ""); /// /// Set the quit flag true / false. /// /// When true quits the algorithm event loop for this day void SetQuit(bool quit); /// /// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode. /// /// Bool live mode flag void SetLiveMode(bool live); /// /// Set the maximum number of orders the algortihm is allowed to process. /// /// Maximum order count int void SetMaximumOrders(int max); /// /// Set the maximum number of assets allowable to ensure good memory usage / avoid linux killing job. /// /// Maximum number of minute level assets the live mode can support with selected server /// Maximum number of second level assets the live mode can support with selected server /// /// Maximum number of tick level assets the live mode can support with selected server /// Sets the live behaviour of the algorithm including the selected server (ram) limits. void SetAssetLimits(int minuteLimit = 50, int secondLimit = 10, int tickLimit = 5); /// /// Set a runtime statistic for your algorithm- these are displayed on the IDE during live runmode. /// /// Key name for the statistic /// String value for statistic void SetRuntimeStatistic(string name, string value); /// /// Get the quit flag state. /// /// Boolean quit flag bool GetQuit(); } }