chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:02:50 +08:00
commit 0fc60fdcb1
5008 changed files with 910633 additions and 0 deletions
@@ -0,0 +1,53 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Event arguments for the <see cref="IDataProvider.NewDataRequest"/> event
/// </summary>
public class DataProviderNewDataRequestEventArgs : EventArgs
{
/// <summary>
/// Path to the fetched data
/// </summary>
public string Path { get; }
/// <summary>
/// Whether the data was fetched successfully
/// </summary>
public bool Succeeded { get; }
/// <summary>
/// Any error message that occurred during the fetch
/// </summary>
public string ErrorMessage { get; }
/// <summary>
/// Initializes a new instance of the <see cref="DataProviderNewDataRequestEventArgs"/> class
/// </summary>
/// <param name="path">The path to the fetched data</param>
/// <param name="succeeded">Whether the data was fetched successfully</param>
/// <param name="errorMessage">Any error message that occured during the fetch</param>
public DataProviderNewDataRequestEventArgs(string path, bool succeeded, string errorMessage)
{
Path = path;
Succeeded = succeeded;
ErrorMessage = errorMessage;
}
}
}
@@ -0,0 +1,28 @@
/*
* 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.
*/
namespace QuantConnect.Interfaces
{
/// <summary>
/// A reduced interface for an account currency provider
/// </summary>
public interface IAccountCurrencyProvider
{
/// <summary>
/// Gets the account currency
/// </summary>
string AccountCurrency { get; }
}
}
+961
View File
@@ -0,0 +1,961 @@
/*
* 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;
using Common.Util;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines an event fired from within an algorithm instance.
/// </summary>
/// <typeparam name="T">The event type</typeparam>
/// <param name="algorithm">The algorithm that fired the event</param>
/// <param name="eventData">The event data</param>
public delegate void AlgorithmEvent<in T>(IAlgorithm algorithm, T eventData);
/// <summary>
/// Interface for QuantConnect algorithm implementations. All algorithms must implement these
/// basic members to allow interaction with the Lean Backtesting Engine.
/// </summary>
public interface IAlgorithm : ISecurityInitializerProvider, IAccountCurrencyProvider
{
/// <summary>
/// Event fired when an algorithm generates a insight
/// </summary>
event AlgorithmEvent<GeneratedInsightsCollection> InsightsGenerated;
/// <summary>
/// Gets the time keeper instance
/// </summary>
ITimeKeeper TimeKeeper
{
get;
}
/// <summary>
/// Data subscription manager controls the information and subscriptions the algorithms recieves.
/// Subscription configurations can be added through the Subscription Manager.
/// </summary>
SubscriptionManager SubscriptionManager
{
get;
}
/// <summary>
/// The project id associated with this algorithm if any
/// </summary>
int ProjectId
{
get;
set;
}
/// <summary>
/// Security object collection class stores an array of objects representing representing each security/asset
/// we have a subscription for.
/// </summary>
/// <remarks>It is an IDictionary implementation and can be indexed by symbol</remarks>
SecurityManager Securities
{
get;
}
/// <summary>
/// Gets the collection of universes for the algorithm
/// </summary>
UniverseManager UniverseManager
{
get;
}
/// <summary>
/// Security portfolio management class provides wrapper and helper methods for the Security.Holdings class such as
/// IsLong, IsShort, TotalProfit
/// </summary>
/// <remarks>Portfolio is a wrapper and helper class encapsulating the Securities[].Holdings objects</remarks>
SecurityPortfolioManager Portfolio
{
get;
}
/// <summary>
/// Security transaction manager class controls the store and processing of orders.
/// </summary>
/// <remarks>The orders and their associated events are accessible here. When a new OrderEvent is recieved the algorithm portfolio is updated.</remarks>
SecurityTransactionManager Transactions
{
get;
}
/// <summary>
/// Gets the brokerage model used to emulate a real brokerage
/// </summary>
IBrokerageModel BrokerageModel
{
get;
}
/// <summary>
/// Gets the brokerage name.
/// </summary>
BrokerageName BrokerageName
{
get;
}
/// <summary>
/// Gets the risk free interest rate model used to get the interest rates
/// </summary>
IRiskFreeInterestRateModel RiskFreeInterestRateModel
{
get;
}
/// <summary>
/// Gets the brokerage message handler used to decide what to do
/// with each message sent from the brokerage
/// </summary>
IBrokerageMessageHandler BrokerageMessageHandler
{
get;
set;
}
/// <summary>
/// Notification manager for storing and processing live event messages
/// </summary>
NotificationManager Notify
{
get;
}
/// <summary>
/// Gets schedule manager for adding/removing scheduled events
/// </summary>
ScheduleManager Schedule
{
get;
}
/// <summary>
/// Gets or sets the history provider for the algorithm
/// </summary>
IHistoryProvider HistoryProvider
{
get;
set;
}
/// <summary>
/// Gets or sets the current status of the algorithm
/// </summary>
AlgorithmStatus Status
{
get;
set;
}
/// <summary>
/// Gets whether or not this algorithm is still warming up
/// </summary>
bool IsWarmingUp
{
get;
}
/// <summary>
/// Public name for the algorithm.
/// </summary>
string Name
{
get;
set;
}
/// <summary>
/// A list of tags associated with the algorithm or the backtest, useful for categorization
/// </summary>
HashSet<string> Tags
{
get;
set;
}
/// <summary>
/// Event fired algorithm's name is changed
/// </summary>
event AlgorithmEvent<string> NameUpdated;
/// <summary>
/// Event fired when the tag collection is updated
/// </summary>
event AlgorithmEvent<HashSet<string>> TagsUpdated;
/// <summary>
/// Current date/time in the algorithm's local time zone
/// </summary>
DateTime Time
{
get;
}
/// <summary>
/// Gets the time zone of the algorithm
/// </summary>
DateTimeZone TimeZone
{
get;
}
/// <summary>
/// Current date/time in UTC.
/// </summary>
DateTime UtcTime
{
get;
}
/// <summary>
/// Algorithm start date for backtesting, set by the SetStartDate methods.
/// </summary>
DateTime StartDate
{
get;
}
/// <summary>
/// Get Requested Backtest End Date
/// </summary>
DateTime EndDate
{
get;
}
/// <summary>
/// AlgorithmId for the backtest
/// </summary>
string AlgorithmId
{
get;
}
/// <summary>
/// Algorithm is running on a live server.
/// </summary>
bool LiveMode
{
get;
}
/// <summary>
/// Algorithm running mode.
/// </summary>
AlgorithmMode AlgorithmMode
{
get;
}
/// <summary>
/// Deployment target, either local or cloud.
/// </summary>
DeploymentTarget DeploymentTarget
{
get;
}
/// <summary>
/// Gets the subscription settings to be used when adding securities via universe selection
/// </summary>
UniverseSettings UniverseSettings
{
get;
}
/// <summary>
/// Debug messages from the strategy:
/// </summary>
ConcurrentQueue<string> DebugMessages
{
get;
}
/// <summary>
/// Error messages from the strategy:
/// </summary>
ConcurrentQueue<string> ErrorMessages
{
get;
}
/// <summary>
/// Log messages from the strategy:
/// </summary>
ConcurrentQueue<string> LogMessages
{
get;
}
/// <summary>
/// Gets the run time error from the algorithm, or null if none was encountered.
/// </summary>
Exception RunTimeError
{
get;
set;
}
/// <summary>
/// Customizable dynamic statistics displayed during live trading:
/// </summary>
ConcurrentDictionary<string, string> RuntimeStatistics
{
get;
}
/// <summary>
/// The current algorithm statistics for the running algorithm.
/// </summary>
StatisticsResults Statistics
{
get;
}
/// <summary>
/// Gets the function used to define the benchmark. This function will return
/// the value of the benchmark at a requested date/time
/// </summary>
IBenchmark Benchmark
{
get;
}
/// <summary>
/// Gets the Trade Builder to generate trades from executions
/// </summary>
ITradeBuilder TradeBuilder
{
get;
}
/// <summary>
/// Gets the user settings for the algorithm
/// </summary>
IAlgorithmSettings Settings
{
get;
}
/// <summary>
/// Gets the option chain provider, used to get the list of option contracts for an underlying symbol
/// </summary>
IOptionChainProvider OptionChainProvider
{
get;
}
/// <summary>
/// Gets the future chain provider, used to get the list of future contracts for an underlying symbol
/// </summary>
IFutureChainProvider FutureChainProvider
{
get;
}
/// <summary>
/// Gets the insight manager
/// </summary>
InsightManager Insights
{
get;
}
/// <summary>
/// Gets the object store, used for persistence
/// </summary>
ObjectStore ObjectStore { get; }
/// <summary>
/// Returns the current Slice object
/// </summary>
Slice CurrentSlice { get; }
/// <summary>
/// Initialise the Algorithm and Prepare Required Data:
/// </summary>
void Initialize();
/// <summary>
/// Called by setup handlers after Initialize and allows the algorithm a chance to organize
/// the data gather in the Initialize method
/// </summary>
void PostInitialize();
/// <summary>
/// Called when the algorithm has completed initialization and warm up.
/// </summary>
void OnWarmupFinished();
/// <summary>
/// Gets a read-only dictionary with all current parameters
/// </summary>
ReadOnlyExtendedDictionary<string, string> GetParameters();
/// <summary>
/// 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
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
string GetParameter(string name, string defaultValue = null);
/// <summary>
/// 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
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
int GetParameter(string name, int defaultValue);
/// <summary>
/// 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
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
double GetParameter(string name, double defaultValue);
/// <summary>
/// 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
/// </summary>
/// <param name="name">The name of the parameter to get</param>
/// <param name="defaultValue">The default value to return</param>
/// <returns>The value of the specified parameter, or defaultValue if not found or null if there's no default value</returns>
decimal GetParameter(string name, decimal defaultValue);
/// <summary>
/// Sets the parameters from the dictionary
/// </summary>
/// <param name="parameters">Dictionary containing the parameter names to values</param>
void SetParameters(Dictionary<string, string> parameters);
/// <summary>
/// Determines if the Symbol is shortable at the brokerage
/// </summary>
/// <param name="symbol">Symbol to check if shortable</param>
/// <param name="shortQuantity">Order's quantity to check if it is currently shortable, taking into account current holdings and open orders</param>
/// <param name="updateOrderId">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</param>
/// <returns>True if the symbol can be shorted by the requested quantity</returns>
bool Shortable(Symbol symbol, decimal shortQuantity, int? updateOrderId = null);
/// <summary>
/// Gets the quantity shortable for the given asset
/// </summary>
/// <returns>
/// Quantity shortable for the given asset. Zero if not
/// shortable, or a number greater than zero if shortable.
/// </returns>
long ShortableQuantity(Symbol symbol);
/// <summary>
/// Sets the brokerage model used to resolve transaction models, settlement models,
/// and brokerage specified ordering behaviors.
/// </summary>
/// <param name="brokerageModel">The brokerage model used to emulate the real
/// brokerage</param>
void SetBrokerageModel(IBrokerageModel brokerageModel);
/// <summary>
/// v3.0 Handler for all data types
/// </summary>
/// <param name="slice">The current slice of data</param>
void OnData(Slice slice);
/// <summary>
/// Used to send data updates to algorithm framework models
/// </summary>
/// <param name="slice">The current data slice</param>
void OnFrameworkData(Slice slice);
/// <summary>
/// Event handler to be called when there's been a split event
/// </summary>
/// <param name="splits">The current time slice splits</param>
void OnSplits(Splits splits);
/// <summary>
/// Event handler to be called when there's been a dividend event
/// </summary>
/// <param name="dividends">The current time slice dividends</param>
void OnDividends(Dividends dividends);
/// <summary>
/// Event handler to be called when there's been a delistings event
/// </summary>
/// <param name="delistings">The current time slice delistings</param>
void OnDelistings(Delistings delistings);
/// <summary>
/// Event handler to be called when there's been a symbol changed event
/// </summary>
/// <param name="symbolsChanged">The current time slice symbol changed events</param>
void OnSymbolChangedEvents(SymbolChangedEvents symbolsChanged);
/// <summary>
/// Event fired each time that we add/remove securities from the data feed
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
void OnSecuritiesChanged(SecurityChanges changes);
/// <summary>
/// Used to send security changes to algorithm framework models
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
void OnFrameworkSecuritiesChanged(SecurityChanges changes);
/// <summary>
/// Invoked at the end of every time step. This allows the algorithm
/// to process events before advancing to the next time step.
/// </summary>
void OnEndOfTimeStep();
/// <summary>
/// Send debug message
/// </summary>
/// <param name="message"></param>
void Debug(string message);
/// <summary>
/// Save entry to the Log
/// </summary>
/// <param name="message">String message</param>
void Log(string message);
/// <summary>
/// Send an error message for the algorithm
/// </summary>
/// <param name="message">String message</param>
void Error(string message);
/// <summary>
/// Margin call event handler. This method is called right before the margin call orders are placed in the market.
/// </summary>
/// <param name="requests">The orders to be executed to bring this algorithm within margin limits</param>
void OnMarginCall(List<SubmitOrderRequest> requests);
/// <summary>
/// Margin call warning event handler. This method is called when Portfolio.MarginRemaining is under 5% of your Portfolio.TotalPortfolioValue
/// </summary>
void OnMarginCallWarning();
/// <summary>
/// Call this method at the end of each day of data.
/// </summary>
/// <remarks>Deprecated because different assets have different market close times,
/// and because Python does not support two methods with the same name</remarks>
[Obsolete("This method is deprecated. Please use this overload: OnEndOfDay(Symbol symbol)")]
[StubsIgnore]
void OnEndOfDay();
/// <summary>
/// Call this method at the end of each day of data.
/// </summary>
[StubsAvoidImplicits]
void OnEndOfDay(Symbol symbol);
/// <summary>
/// Call this event at the end of the algorithm running.
/// </summary>
void OnEndOfAlgorithm();
/// <summary>
/// EXPERTS ONLY:: [-!-Async Code-!-]
/// New order event handler: on order status changes (filled, partially filled, cancelled etc).
/// </summary>
/// <param name="newEvent">Event information</param>
void OnOrderEvent(OrderEvent newEvent);
/// <summary>
/// Generic untyped command call handler
/// </summary>
/// <param name="data">The associated data</param>
/// <returns>True if success, false otherwise. Returning null will disable command feedback</returns>
bool? OnCommand(dynamic data);
/// <summary>
/// Will submit an order request to the algorithm
/// </summary>
/// <param name="request">The request to submit</param>
/// <remarks>Will run order prechecks, which include making sure the algorithm is not warming up, security is added and has data among others</remarks>
/// <returns>The order ticket</returns>
OrderTicket SubmitOrderRequest(SubmitOrderRequest request);
/// <summary>
/// Option assignment event handler. On an option assignment event for short legs the resulting information is passed to this method.
/// </summary>
/// <param name="assignmentEvent">Option exercise event details containing details of the assignment</param>
/// <remarks>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</remarks>
void OnAssignmentOrderEvent(OrderEvent assignmentEvent);
/// <summary>
/// Brokerage message event handler. This method is called for all types of brokerage messages.
/// </summary>
void OnBrokerageMessage(BrokerageMessageEvent messageEvent);
/// <summary>
/// Brokerage disconnected event handler. This method is called when the brokerage connection is lost.
/// </summary>
void OnBrokerageDisconnect();
/// <summary>
/// Brokerage reconnected event handler. This method is called when the brokerage connection is restored after a disconnection.
/// </summary>
void OnBrokerageReconnect();
/// <summary>
/// Set the DateTime Frontier: This is the master time and is
/// </summary>
/// <param name="time"></param>
void SetDateTime(DateTime time);
/// <summary>
/// Set the start date for the backtest
/// </summary>
/// <param name="start">Datetime Start date for backtest</param>
/// <remarks>Must be less than end date and within data available</remarks>
void SetStartDate(DateTime start);
/// <summary>
/// Set the end date for a backtest.
/// </summary>
/// <param name="end">Datetime value for end date</param>
/// <remarks>Must be greater than the start date</remarks>
void SetEndDate(DateTime end);
/// <summary>
/// Set the algorithm Id for this backtest or live run. This can be used to identify the order and equity records.
/// </summary>
/// <param name="algorithmId">unique 32 character identifier for backtest or live server</param>
void SetAlgorithmId(string algorithmId);
/// <summary>
/// Set the algorithm as initialized and locked. No more cash or security changes.
/// </summary>
void SetLocked();
/// <summary>
/// Gets whether or not this algorithm has been locked and fully initialized
/// </summary>
bool GetLocked();
/// <summary>
/// Add a Chart object to algorithm collection
/// </summary>
/// <param name="chart">Chart object to add to collection.</param>
void AddChart(Chart chart);
/// <summary>
/// Get the chart updates since the last request:
/// </summary>
/// <param name="clearChartData"></param>
/// <returns>List of Chart Updates</returns>
IEnumerable<Chart> GetChartUpdates(bool clearChartData = false);
/// <summary>
/// Set a required SecurityType-symbol and resolution for algorithm
/// </summary>
/// <param name="securityType">SecurityType Enum: Equity, Commodity, FOREX or Future</param>
/// <param name="symbol">Symbol Representation of the MarketType, e.g. AAPL</param>
/// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param>
/// <param name="market">The market the requested security belongs to, such as 'usa' or 'fxcm'</param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice.</param>
/// <param name="leverage">leverage for this security</param>
/// <param name="extendedMarketHours">ExtendedMarketHours send in data from 4am - 8pm, not used for FOREX</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the security</param>
Security AddSecurity(SecurityType securityType, string symbol, Resolution? resolution, string market, bool? fillForward, decimal leverage, bool? extendedMarketHours,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null);
/// <summary>
/// Set a required SecurityType-symbol and resolution for algorithm
/// </summary>
/// <param name="symbol">The security Symbol</param>
/// <param name="resolution">Resolution of the MarketType required: MarketData, Second or Minute</param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice.</param>
/// <param name="leverage">leverage for this security</param>
/// <param name="extendedMarketHours">Use extended market hours data</param>
/// <param name="dataMappingMode">The contract mapping mode to use for the security</param>
/// <param name="dataNormalizationMode">The price scaling mode to use for the security</param>
/// <param name="contractDepthOffset">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</param>
/// <returns>The new Security that was added to the algorithm</returns>
Security AddSecurity(Symbol symbol, Resolution? resolution = null, bool? fillForward = null, decimal leverage = Security.NullLeverage, bool? extendedMarketHours = null,
DataMappingMode? dataMappingMode = null, DataNormalizationMode? dataNormalizationMode = null, int contractDepthOffset = 0);
/// <summary>
/// Creates and adds a new single <see cref="Future"/> contract to the algorithm
/// </summary>
/// <param name="symbol">The futures contract symbol</param>
/// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <param name="extendedMarketHours">Show the after market data as well</param>
/// <returns>The new <see cref="Future"/> security</returns>
Future AddFutureContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m, bool extendedMarketHours = false);
/// <summary>
/// Creates and adds a new single <see cref="Option"/> contract to the algorithm
/// </summary>
/// <param name="symbol">The option contract symbol</param>
/// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param>
/// <param name="fillForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
/// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
/// <param name="extendedMarketHours">Show the after market data as well</param>
/// <returns>The new <see cref="Option"/> security</returns>
Option AddOptionContract(Symbol symbol, Resolution? resolution = null, bool fillForward = true, decimal leverage = 0m, bool extendedMarketHours = false);
/// <summary>
/// Removes the security with the specified symbol. This will cancel all
/// open orders and then liquidate any existing holdings
/// </summary>
/// <param name="symbol">The symbol of the security to be removed</param>
/// <param name="tag">Optional tag to indicate the cause of removal</param>
bool RemoveSecurity(Symbol symbol, string tag = null);
/// <summary>
/// Sets the account currency cash symbol this algorithm is to manage, as well as
/// the starting cash in this currency if given
/// </summary>
/// <remarks>Has to be called during <see cref="Initialize"/> before
/// calling <see cref="SetCash(decimal)"/> or adding any <see cref="Security"/></remarks>
/// <param name="accountCurrency">The account currency cash symbol to set</param>
/// <param name="startingCash">The account currency starting cash to set</param>
void SetAccountCurrency(string accountCurrency, decimal? startingCash = null);
/// <summary>
/// Set the starting capital for the strategy
/// </summary>
/// <param name="startingCash">decimal starting capital, default $100,000</param>
void SetCash(decimal startingCash);
/// <summary>
/// Set the cash for the specified symbol
/// </summary>
/// <param name="symbol">The cash symbol to set</param>
/// <param name="startingCash">Decimal cash value of portfolio</param>
/// <param name="conversionRate">The current conversion rate for the</param>
void SetCash(string symbol, decimal startingCash, decimal conversionRate = 0);
/// <summary>
/// Liquidate your portfolio holdings
/// </summary>
/// <param name="symbol">Specific asset to liquidate, defaults to all.</param>
/// <param name="asynchronous">Flag to indicate if the symbols should be liquidated asynchronously</param>
/// <param name="tag">Custom tag to know who is calling this</param>
/// <param name="orderProperties">Order properties to use</param>
List<OrderTicket> Liquidate(Symbol symbol = null, bool asynchronous = false, string tag = "Liquidated", IOrderProperties orderProperties = null);
/// <summary>
/// Set live mode state of the algorithm run: Public setter for the algorithm property LiveMode.
/// </summary>
/// <param name="live">Bool live mode flag</param>
void SetLiveMode(bool live);
/// <summary>
/// Sets the algorithm running mode
/// </summary>
/// <param name="algorithmMode">Algorithm mode</param>
void SetAlgorithmMode(AlgorithmMode algorithmMode);
/// <summary>
/// Sets the algorithm deployment target
/// </summary>
/// <param name="deploymentTarget">Deployment target</param>
void SetDeploymentTarget(DeploymentTarget deploymentTarget);
/// <summary>
/// Sets <see cref="IsWarmingUp"/> to false to indicate this algorithm has finished its warm up
/// </summary>
void SetFinishedWarmingUp();
/// <summary>
/// Set the maximum number of orders the algorithm is allowed to process.
/// </summary>
/// <param name="max">Maximum order count int</param>
void SetMaximumOrders(int max);
/// <summary>
/// Sets the implementation used to handle messages from the brokerage.
/// The default implementation will forward messages to debug or error
/// and when a <see cref="BrokerageMessageType.Error"/> occurs, the algorithm
/// is stopped.
/// </summary>
/// <param name="handler">The message handler to use</param>
void SetBrokerageMessageHandler(IBrokerageMessageHandler handler);
/// <summary>
/// Set the historical data provider
/// </summary>
/// <param name="historyProvider">Historical data provider</param>
void SetHistoryProvider(IHistoryProvider historyProvider);
/// <summary>
/// Get the last known price using the history provider.
/// Useful for seeding securities with the correct price
/// </summary>
/// <param name="symbol">The symbol for which to retrieve historical data</param>
/// <returns>A single <see cref="BaseData"/> object with the last known price</returns>
BaseData GetLastKnownPrice(Symbol symbol);
/// <summary>
/// Yields data to warmup a security for all it's subscribed data types
/// </summary>
/// <param name="symbol">The symbol for which to retrieve historical data</param>
/// <returns>Securities historical data</returns>
IEnumerable<BaseData> GetLastKnownPrices(Symbol symbol);
/// <summary>
/// Yields data to warm up multiple securities for all their subscribed data types
/// </summary>
/// <param name="symbols">The symbols we want to get seed data for</param>
/// <returns>Securities historical data</returns>
DataDictionary<IEnumerable<BaseData>> GetLastKnownPrices(IEnumerable<Symbol> symbols);
/// <summary>
/// Set the runtime error
/// </summary>
/// <param name="exception">Represents error that occur during execution</param>
void SetRunTimeError(Exception exception);
/// <summary>
/// Set the state of a live deployment
/// </summary>
/// <param name="status">Live deployment status</param>
void SetStatus(AlgorithmStatus status);
/// <summary>
/// Set the available <see cref="TickType"/> supported by each <see cref="SecurityType"/> in <see cref="SecurityManager"/>
/// </summary>
/// <param name="availableDataTypes">>The different <see cref="TickType"/> each <see cref="Security"/> supports</param>
void SetAvailableDataTypes(Dictionary<SecurityType, List<TickType>> availableDataTypes);
/// <summary>
/// Sets the option chain provider, used to get the list of option contracts for an underlying symbol
/// </summary>
/// <param name="optionChainProvider">The option chain provider</param>
void SetOptionChainProvider(IOptionChainProvider optionChainProvider);
/// <summary>
/// Sets the future chain provider, used to get the list of future contracts for an underlying symbol
/// </summary>
/// <param name="futureChainProvider">The future chain provider</param>
void SetFutureChainProvider(IFutureChainProvider futureChainProvider);
/// <summary>
/// Sets the current slice
/// </summary>
/// <param name="slice">The Slice object</param>
void SetCurrentSlice(Slice slice);
/// <summary>
/// Provide the API for the algorithm.
/// </summary>
/// <param name="api">Initiated API</param>
void SetApi(IApi api);
/// <summary>
/// Sets the object store
/// </summary>
/// <param name="objectStore">The object store</param>
void SetObjectStore(IObjectStore objectStore);
/// <summary>
/// Converts the string 'ticker' symbol into a full <see cref="Symbol"/> object
/// This requires that the string 'ticker' has been added to the algorithm
/// </summary>
/// <param name="ticker">The ticker symbol. This should be the ticker symbol
/// as it was added to the algorithm</param>
/// <returns>The symbol object mapped to the specified ticker</returns>
Symbol Symbol(string ticker);
/// <summary>
/// For the given symbol will resolve the ticker it used at the current algorithm date
/// </summary>
/// <param name="symbol">The symbol to get the ticker for</param>
/// <returns>The mapped ticker for a symbol</returns>
string Ticker(Symbol symbol);
/// <summary>
/// Sets the statistics service instance to be used by the algorithm
/// </summary>
/// <param name="statisticsService">The statistics service instance</param>
void SetStatisticsService(IStatisticsService statisticsService);
/// <summary>
/// Sets name to the currently running backtest
/// </summary>
/// <param name="name">The name for the backtest</param>
void SetName(string name);
/// <summary>
/// Adds a tag to the algorithm
/// </summary>
/// <param name="tag">The tag to add</param>
void AddTag(string tag);
/// <summary>
/// Sets the tags for the algorithm
/// </summary>
/// <param name="tags">The tags</param>
void SetTags(HashSet<string> tags);
/// <summary>
/// Run a callback command instance
/// </summary>
/// <param name="command">The callback command instance</param>
/// <returns>The command result</returns>
CommandResultPacket RunCommand(CallbackCommand command);
/// <summary>
/// Gets the default order properties
/// </summary>
IOrderProperties DefaultOrderProperties { get; }
}
}
+159
View File
@@ -0,0 +1,159 @@
/*
* 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 QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// User settings for the algorithm which can be changed in the <see cref="IAlgorithm.Initialize"/> method
/// </summary>
public interface IAlgorithmSettings
{
/// <summary>
/// Gets whether or not WarmUpIndicator is allowed to warm up indicators
/// </summary>
bool AutomaticIndicatorWarmUp { get; set; }
/// <summary>
/// True if should rebalance portfolio on security changes. True by default
/// </summary>
bool? RebalancePortfolioOnSecurityChanges { get; set; }
/// <summary>
/// True if should rebalance portfolio on new insights or expiration of insights. True by default
/// </summary>
bool? RebalancePortfolioOnInsightChanges { get; set; }
/// <summary>
/// The absolute maximum valid total portfolio value target percentage
/// </summary>
/// <remarks>This setting is currently being used to filter out undesired target percent values,
/// caused by the IPortfolioConstructionModel implementation being used.
/// For example rounding errors, math operations</remarks>
decimal MaxAbsolutePortfolioTargetPercentage { get; set; }
/// <summary>
/// The absolute minimum valid total portfolio value target percentage
/// </summary>
/// <remarks>This setting is currently being used to filter out undesired target percent values,
/// caused by the IPortfolioConstructionModel implementation being used.
/// For example rounding errors, math operations</remarks>
decimal MinAbsolutePortfolioTargetPercentage { get; set; }
/// <summary>
/// Configurable minimum order margin portfolio percentage to ignore bad orders, or orders with unrealistic sizes
/// </summary>
/// <remarks>Default minimum order size is $0 value</remarks>
decimal MinimumOrderMarginPortfolioPercentage { get; set; }
/// <summary>
/// Gets/sets the SetHoldings buffers value.
/// The buffer is used for orders not to be rejected due to volatility when using SetHoldings and CalculateOrderQuantity
/// </summary>
decimal? FreePortfolioValue { get; set; }
/// <summary>
/// Gets/sets the SetHoldings buffers value percentage.
/// This percentage will be used to set the <see cref="FreePortfolioValue"/>
/// based on the <see cref="SecurityPortfolioManager.TotalPortfolioValue"/>
/// </summary>
decimal FreePortfolioValuePercentage { get; set; }
/// <summary>
/// Gets/sets if Liquidate() is enabled
/// </summary>
bool LiquidateEnabled { get; set; }
/// <summary>
/// True if daily strict end times are enabled
/// </summary>
bool DailyPreciseEndTime { get; set; }
/// <summary>
/// True if extended market hours should be used for daily consolidation, when extended market hours is enabled
/// </summary>
bool DailyConsolidationUseExtendedMarketHours { get; set; }
/// <summary>
/// Gets/sets the maximum number of concurrent market data subscriptions available
/// </summary>
/// <remarks>
/// All securities added with <see cref="IAlgorithm.AddSecurity"/> are counted as one,
/// with the exception of options and futures where every single contract in a chain counts as one.
/// </remarks>
[Obsolete("This property is deprecated. Please observe data subscription limits set by your brokerage to avoid runtime errors.")]
int DataSubscriptionLimit { get; set; }
/// <summary>
/// Gets/sets the minimum time span elapsed to consider a market fill price as stale (defaults to one hour)
/// </summary>
/// <remarks>
/// In the default fill models, a market order on an hour or daily resolution subscription is not filled on
/// data older than this time span; instead it waits for fresh data (e.g. the next bar), avoiding a
/// fill at the stale previous close. Market orders on minute/second/tick subscriptions still fill on stale
/// data, only adding a warning message. Tighten it (e.g. to one minute) to make hour/daily orders wait for
/// the next bar more aggressively.
/// </remarks>
TimeSpan StalePriceTimeSpan { get; set; }
/// <summary>
/// The warmup resolution to use if any
/// </summary>
/// <remarks>This allows improving the warmup speed by setting it to a lower resolution than the one added in the algorithm</remarks>
Resolution? WarmupResolution { get; set; }
/// <summary>
/// Gets or sets the number of trading days per year for this Algorithm's portfolio statistics.
/// </summary>
/// <remarks>
/// This property affects the calculation of various portfolio statistics, including:
/// - <see cref="Statistics.PortfolioStatistics.AnnualVariance"/>
/// - <seealso cref="Statistics.PortfolioStatistics.AnnualStandardDeviation"/>
/// - <seealso cref="Statistics.PortfolioStatistics.SharpeRatio"/>
/// - <seealso cref="Statistics.PortfolioStatistics.SortinoRatio"/>
/// - <seealso cref="Statistics.PortfolioStatistics.TrackingError"/>
/// - <seealso cref="Statistics.PortfolioStatistics.InformationRatio"/>.
///
/// The default values are:
/// - Cryptocurrency Exchanges: 365 days
/// - Traditional Stock Exchanges: 252 days
///
/// Users can also set a custom value for this property.
/// </remarks>
int? TradingDaysPerYear { get; set; }
/// <summary>
/// Gets the time span used to refresh the market hours and symbol properties databases
/// </summary>
TimeSpan DatabasesRefreshPeriod { get; set; }
/// <summary>
/// Determines whether to terminate the algorithm when an asset is not supported by Lean or the brokerage
/// </summary>
bool IgnoreUnknownAssetHoldings { get; set; }
/// <summary>
/// Performance tracking sample period to use if any, useful to debug performance issues
/// </summary>
TimeSpan PerformanceSamplePeriod { get; set; }
/// <summary>
/// Determines whether to seed initial prices for all selected and manually added securities.
/// </summary>
bool SeedInitialPrices { get; set; }
}
}
@@ -0,0 +1,37 @@
/*
* 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.Collections.Generic;
using QuantConnect.Data;
namespace QuantConnect.Interfaces
{
/// <summary>
/// AlgorithmSubscriptionManager interface will manage the subscriptions for the SubscriptionManager
/// </summary>
public interface IAlgorithmSubscriptionManager : ISubscriptionDataConfigService
{
/// <summary>
/// Gets all the current data config subscriptions that are being processed for the SubscriptionManager
/// </summary>
IEnumerable<SubscriptionDataConfig> SubscriptionManagerSubscriptions { get; }
/// <summary>
/// Returns the amount of data config subscriptions processed for the SubscriptionManager
/// </summary>
int SubscriptionManagerCount();
}
}
+543
View File
@@ -0,0 +1,543 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Api;
using QuantConnect.Notifications;
using QuantConnect.Optimizer.Objectives;
using QuantConnect.Optimizer.Parameters;
using QuantConnect.Statistics;
namespace QuantConnect.Interfaces
{
/// <summary>
/// API for QuantConnect.com
/// </summary>
[InheritedExport(typeof(IApi))]
public interface IApi : IDisposable
{
/// <summary>
/// Initialize the control system
/// </summary>
void Initialize(int userId, string token, string dataFolder);
/// <summary>
/// Create a project with the specified name and language via QuantConnect.com API
/// </summary>
/// <param name="name">Project name</param>
/// <param name="language">Programming language to use</param>
/// <param name="organizationId">Organization to create this project under</param>
/// <returns><see cref="ProjectResponse"/> that includes information about the newly created project</returns>
ProjectResponse CreateProject(string name, Language language, string organizationId = null);
/// <summary>
/// Read in a project from the QuantConnect.com API.
/// </summary>
/// <param name="projectId">Project id you own</param>
/// <returns><see cref="ProjectResponse"/> about a specific project</returns>
ProjectResponse ReadProject(int projectId);
/// <summary>
/// Add a file to a project
/// </summary>
/// <param name="projectId">The project to which the file should be added</param>
/// <param name="name">The name of the new file</param>
/// <param name="content">The content of the new file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes information about the newly created file</returns>
RestResponse AddProjectFile(int projectId, string name, string content);
/// <summary>
/// Update the name of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="oldFileName">The current name of the file</param>
/// <param name="newFileName">The new name for the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
RestResponse UpdateProjectFileName(int projectId, string oldFileName, string newFileName);
/// <summary>
/// Update the contents of a file
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file that should be updated</param>
/// <param name="newFileContents">The new contents of the file</param>
/// <returns><see cref="RestResponse"/> indicating success</returns>
RestResponse UpdateProjectFileContent(int projectId, string fileName, string newFileContents);
/// <summary>
/// Read a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="fileName">The name of the file</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the file information</returns>
ProjectFilesResponse ReadProjectFile(int projectId, string fileName);
/// <summary>
/// Read all files in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
ProjectFilesResponse ReadProjectFiles(int projectId);
/// <summary>
/// Read all nodes in a project.
/// </summary>
/// <param name="projectId">Project id to which the nodes refer</param>
/// <returns><see cref="ProjectNodesResponse"/> that includes the information about all nodes in the project</returns>
ProjectNodesResponse ReadProjectNodes(int projectId);
/// <summary>
/// Update the active state of some nodes to true.
/// If you don't provide any nodes, all the nodes become inactive and AutoSelectNode is true.
/// </summary>
/// <param name="projectId">Project id to which the nodes refer</param>
/// <param name="nodes">List of node ids to update</param>
/// <returns><see cref="ProjectNodesResponse"/> that includes the information about all nodes in the project</returns>
ProjectNodesResponse UpdateProjectNodes(int projectId, string[] nodes);
/// <summary>
/// Delete a file in a project
/// </summary>
/// <param name="projectId">Project id to which the file belongs</param>
/// <param name="name">The name of the file that should be deleted</param>
/// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns>
RestResponse DeleteProjectFile(int projectId, string name);
/// <summary>
/// Delete a specific project owned by the user from QuantConnect.com
/// </summary>
/// <param name="projectId">Project id we own and wish to delete</param>
/// <returns>RestResponse indicating success</returns>
RestResponse DeleteProject(int projectId);
/// <summary>
/// Read back a list of all projects on the account for a user.
/// </summary>
/// <returns>Container for list of projects</returns>
ProjectResponse ListProjects();
/// <summary>
/// Create a new compile job request for this project id.
/// </summary>
/// <param name="projectId">Project id we wish to compile.</param>
/// <returns>Compile object result</returns>
Compile CreateCompile(int projectId);
/// <summary>
/// Read a compile packet job result.
/// </summary>
/// <param name="projectId">Project id we sent for compile</param>
/// <param name="compileId">Compile id return from the creation request</param>
/// <returns>Compile object result</returns>
Compile ReadCompile(int projectId, string compileId);
/// <summary>
/// Create a new backtest from a specified projectId and compileId
/// </summary>
/// <param name="projectId"></param>
/// <param name="compileId"></param>
/// <param name="backtestName"></param>
/// <returns></returns>
Backtest CreateBacktest(int projectId, string compileId, string backtestName);
/// <summary>
/// Read out the full result of a specific backtest
/// </summary>
/// <param name="projectId">Project id for the backtest we'd like to read</param>
/// <param name="backtestId">Backtest id for the backtest we'd like to read</param>
/// <param name="getCharts">True will return backtest charts</param>
/// <returns>Backtest result object</returns>
Backtest ReadBacktest(int projectId, string backtestId, bool getCharts = true);
/// <summary>
/// Update the backtest name
/// </summary>
/// <param name="projectId">Project id to update</param>
/// <param name="backtestId">Backtest id to update</param>
/// <param name="name">New backtest name to set</param>
/// <param name="note">Note attached to the backtest</param>
/// <returns>Rest response on success</returns>
RestResponse UpdateBacktest(int projectId, string backtestId, string name = "", string note = "");
/// <summary>
/// Delete a backtest from the specified project and backtestId.
/// </summary>
/// <param name="projectId">Project for the backtest we want to delete</param>
/// <param name="backtestId">Backtest id we want to delete</param>
/// <returns>RestResponse on success</returns>
RestResponse DeleteBacktest(int projectId, string backtestId);
/// <summary>
/// Get a list of backtest summaries for a specific project id
/// </summary>
/// <param name="projectId">Project id to search</param>
/// <param name="includeStatistics">True for include statistics in the response, false otherwise</param>
/// <returns>BacktestList container for list of backtests</returns>
BacktestSummaryList ListBacktests(int projectId, bool includeStatistics = false);
/// <summary>
/// Read out the insights of a backtest
/// </summary>
/// <param name="projectId">Id of the project from which to read the backtest</param>
/// <param name="backtestId">Backtest id from which we want to get the insights</param>
/// <param name="start">Starting index of the insights to be fetched</param>
/// <param name="end">Last index of the insights to be fetched. Note that end - start must be less than 100</param>
/// <returns><see cref="InsightResponse"/></returns>
/// <exception cref="ArgumentException"></exception>
public InsightResponse ReadBacktestInsights(int projectId, string backtestId, int start = 0, int end = 0);
#pragma warning disable CS1574
/// <summary>
/// Estimate optimization with the specified parameters via QuantConnect.com API
/// </summary>
/// <param name="projectId">Project ID of the project the optimization belongs to</param>
/// <param name="name">Name of the optimization</param>
/// <param name="target">Target of the optimization, see examples in <see cref="PortfolioStatistics"/></param>
/// <param name="targetTo">Target extremum of the optimization, for example "max" or "min"</param>
/// <param name="targetValue">Optimization target value</param>
/// <param name="strategy">Optimization strategy, <see cref="GridSearchOptimizationStrategy"/></param>
/// <param name="compileId">Optimization compile ID</param>
/// <param name="parameters">Optimization parameters</param>
/// <param name="constraints">Optimization constraints</param>
/// <returns>Estimate object from the API.</returns>
#pragma warning restore CS1574
public Estimate EstimateOptimization(
int projectId,
string name,
string target,
string targetTo,
decimal? targetValue,
string strategy,
string compileId,
HashSet<OptimizationParameter> parameters,
IReadOnlyList<Constraint> constraints);
#pragma warning disable CS1574
/// <summary>
/// Create an optimization with the specified parameters via QuantConnect.com API
/// </summary>
/// <param name="projectId">Project ID of the project the optimization belongs to</param>
/// <param name="name">Name of the optimization</param>
/// <param name="target">Target of the optimization, see examples in <see cref="PortfolioStatistics"/></param>
/// <param name="targetTo">Target extremum of the optimization, for example "max" or "min"</param>
/// <param name="targetValue">Optimization target value</param>
/// <param name="strategy">Optimization strategy, <see cref="GridSearchOptimizationStrategy"/></param>
/// <param name="compileId">Optimization compile ID</param>
/// <param name="parameters">Optimization parameters</param>
/// <param name="constraints">Optimization constraints</param>
/// <param name="estimatedCost">Estimated cost for optimization</param>
/// <param name="nodeType">Optimization node type</param>
/// <param name="parallelNodes">Number of parallel nodes for optimization</param>
/// <returns>BaseOptimization object from the API.</returns>
#pragma warning restore CS1574
public OptimizationSummary CreateOptimization(
int projectId,
string name,
string target,
string targetTo,
decimal? targetValue,
string strategy,
string compileId,
HashSet<OptimizationParameter> parameters,
IReadOnlyList<Constraint> constraints,
decimal estimatedCost,
string nodeType,
int parallelNodes);
/// <summary>
/// List all the optimizations for a project
/// </summary>
/// <param name="projectId">Project id we'd like to get a list of optimizations for</param>
/// <returns>A list of BaseOptimization objects, <see cref="BaseOptimization"/></returns>
public List<OptimizationSummary> ListOptimizations(int projectId);
/// <summary>
/// Read an optimization
/// </summary>
/// <param name="optimizationId">Optimization id for the optimization we want to read</param>
/// <returns><see cref="Optimization"/></returns>
public Optimization ReadOptimization(string optimizationId);
/// <summary>
/// Abort an optimization
/// </summary>
/// <param name="optimizationId">Optimization id for the optimization we want to abort</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse AbortOptimization(string optimizationId);
/// <summary>
/// Update an optimization
/// </summary>
/// <param name="optimizationId">Optimization id we want to update</param>
/// <param name="name">Name we'd like to assign to the optimization</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse UpdateOptimization(string optimizationId, string name = null);
/// <summary>
/// Delete an optimization
/// </summary>
/// <param name="optimizationId">Optimization id for the optimization we want to delete</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse DeleteOptimization(string optimizationId);
/// <summary>
/// Gets the logs of a specific live algorithm
/// </summary>
/// <param name="projectId">Project Id of the live running algorithm</param>
/// <param name="algorithmId">Algorithm Id of the live running algorithm</param>
/// <param name="startLine">Start line of logs to read</param>
/// <param name="endLine">End line of logs to read</param>
/// <returns>List of strings that represent the logs of the algorithm</returns>
LiveLog ReadLiveLogs(int projectId, string algorithmId, int startLine, int endLine);
/// <summary>
/// Returns a chart object from a live algorithm
/// </summary>
/// <param name="projectId">Project ID of the request</param>
/// <param name="name">The requested chart name</param>
/// <param name="start">The Utc start seconds timestamp of the request</param>
/// <param name="end">The Utc end seconds timestamp of the request</param>
/// <param name="count">The number of data points to request</param>
/// <returns></returns>
public ReadChartResponse ReadLiveChart(int projectId, string name, int start, int end, uint count);
/// <summary>
/// Read out the portfolio state of a live algorithm
/// </summary>
/// <param name="projectId">Id of the project from which to read the live algorithm</param>
/// <returns><see cref="PortfolioResponse"/></returns>
public PortfolioResponse ReadLivePortfolio(int projectId);
/// <summary>
/// Read out the insights of a live algorithm
/// </summary>
/// <param name="projectId">Id of the project from which to read the live algorithm</param>
/// <param name="start">Starting index of the insights to be fetched</param>
/// <param name="end">Last index of the insights to be fetched. Note that end - start must be less than 100</param>
/// <returns><see cref="InsightResponse"/></returns>
/// <exception cref="ArgumentException"></exception>
public InsightResponse ReadLiveInsights(int projectId, int start = 0, int end = 0);
/// <summary>
/// Gets the link to the downloadable data.
/// </summary>
/// <param name="filePath">File path representing the data requested</param>
/// <param name="organizationId">Organization to purchase this data with</param>
/// <returns>Link to the downloadable data.</returns>
DataLink ReadDataLink(string filePath, string organizationId);
/// <summary>
/// Get valid data entries for a given filepath from data/list
/// </summary>
/// <returns></returns>
DataList ReadDataDirectory(string filePath);
/// <summary>
/// Gets data prices from data/prices
/// </summary>
public DataPricesList ReadDataPrices(string organizationId);
/// <summary>
/// Read out the report of a backtest in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="backtestId">Specific backtest id to read</param>
/// <returns><see cref="BacktestReport"/></returns>
public BacktestReport ReadBacktestReport(int projectId, string backtestId);
/// <summary>
/// Returns a requested chart object from a backtest
/// </summary>
/// <param name="projectId">Project ID of the request</param>
/// <param name="name">The requested chart name</param>
/// <param name="start">The Utc start seconds timestamp of the request</param>
/// <param name="end">The Utc end seconds timestamp of the request</param>
/// <param name="count">The number of data points to request</param>
/// <param name="backtestId">Associated Backtest ID for this chart request</param>
/// <returns></returns>
public ReadChartResponse ReadBacktestChart(int projectId, string name, int start, int end, uint count, string backtestId);
/// <summary>
/// Method to download and save the data purchased through QuantConnect
/// </summary>
/// <param name="filePath">File path representing the data requested</param>
/// <returns>A bool indicating whether the data was successfully downloaded or not.</returns>
bool DownloadData(string filePath, string organizationId);
/// <summary>
/// Will read the organization account status
/// </summary>
/// <param name="organizationId">The target organization id, if null will return default organization</param>
public Account ReadAccount(string organizationId = null);
/// <summary>
/// Fetch organization data from web API
/// </summary>
/// <param name="organizationId"></param>
/// <returns></returns>
public Organization ReadOrganization(string organizationId = null);
/// <summary>
/// Create a new live algorithm for a logged in user.
/// </summary>
/// <param name="projectId">Id of the project on QuantConnect</param>
/// <param name="compileId">Id of the compilation on QuantConnect</param>
/// <param name="nodeId">Id of the node that will run the algorithm</param>
/// <param name="brokerageSettings">Dictionary with Brokerage specific settings</param>
/// <param name="versionId">The version identifier</param>
/// <param name="dataProviders">Dictionary with data providers and their corresponding credentials</param>
/// <returns>Information regarding the new algorithm <see cref="CreateLiveAlgorithmResponse"/></returns>
CreateLiveAlgorithmResponse CreateLiveAlgorithm(int projectId, string compileId, string nodeId, Dictionary<string, object> brokerageSettings, string versionId = "-1", Dictionary<string, object> dataProviders = null);
/// <summary>
/// Get a list of live running algorithms for a logged in user.
/// </summary>
/// <param name="status">Filter the statuses of the algorithms returned from the api</param>
/// <returns>List of live algorithm instances</returns>
LiveList ListLiveAlgorithms(AlgorithmStatus? status = null);
/// <summary>
/// Read out a live algorithm in the project id specified.
/// </summary>
/// <param name="projectId">Project id to read</param>
/// <param name="deployId">Specific instance id to read</param>
/// <returns>Live object with the results</returns>
LiveAlgorithmResults ReadLiveAlgorithm(int projectId, string deployId);
/// <summary>
/// Liquidate a live algorithm from the specified project.
/// </summary>
/// <param name="projectId">Project for the live instance we want to stop</param>
/// <returns></returns>
RestResponse LiquidateLiveAlgorithm(int projectId);
/// <summary>
/// Stop a live algorithm from the specified project.
/// </summary>
/// <param name="projectId">Project for the live algo we want to delete</param>
/// <returns></returns>
RestResponse StopLiveAlgorithm(int projectId);
/// <summary>
/// Sends a notification
/// </summary>
/// <param name="notification">The notification to send</param>
/// <param name="projectId">The project id</param>
/// <returns><see cref="RestResponse"/> containing success response and errors</returns>
RestResponse SendNotification(Notification notification, int projectId);
/// <summary>
/// Get the algorithm current status, active or cancelled from the user
/// </summary>
/// <param name="algorithmId"></param>
/// <returns></returns>
AlgorithmControl GetAlgorithmStatus(string algorithmId);
/// <summary>
/// Set the algorithm status from the worker to update the UX e.g. if there was an error.
/// </summary>
/// <param name="algorithmId">Algorithm id we're setting.</param>
/// <param name="status">Status enum of the current worker</param>
/// <param name="message">Message for the algorithm status event</param>
void SetAlgorithmStatus(string algorithmId, AlgorithmStatus status, string message = "");
/// <summary>
/// Send the statistics to storage for performance tracking.
/// </summary>
/// <param name="algorithmId">Identifier for algorithm</param>
/// <param name="unrealized">Unrealized gainloss</param>
/// <param name="fees">Total fees</param>
/// <param name="netProfit">Net profi</param>
/// <param name="holdings">Algorithm holdings</param>
/// <param name="equity">Total equity</param>
/// <param name="netReturn">Algorithm return</param>
/// <param name="volume">Volume traded</param>
/// <param name="trades">Total trades since inception</param>
/// <param name="sharpe">Sharpe ratio since inception</param>
void SendStatistics(string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe);
/// <summary>
/// Local implementation for downloading data to algorithms
/// </summary>
/// <param name="address">URL to download</param>
/// <param name="headers">KVP headers</param>
/// <param name="userName">Username for basic authentication</param>
/// <param name="password">Password for basic authentication</param>
/// <returns></returns>
string Download(string address, IEnumerable<KeyValuePair<string, string>> headers, string userName, string password);
/// <summary>
/// Local implementation for downloading data to algorithms
/// </summary>
/// <param name="address">URL to download</param>
/// <param name="headers">KVP headers</param>
/// <param name="userName">Username for basic authentication</param>
/// <param name="password">Password for basic authentication</param>
/// <returns></returns>
byte[] DownloadBytes(string address, IEnumerable<KeyValuePair<string, string>> headers, string userName, string password);
/// <summary>
/// Download the object store associated with the given organization ID and key
/// </summary>
/// <param name="organizationId">Organization ID we would like to get the Object Store from</param>
/// <param name="keys">Keys for the Object Store files</param>
/// <param name="destinationFolder">Folder in which the object will be stored</param>
/// <returns>True if the object was retrieved correctly, false otherwise</returns>
public bool GetObjectStore(string organizationId, List<string> keys, string destinationFolder = null);
/// <summary>
/// Get Object Store properties given the organization ID and the Object Store key
/// </summary>
/// <param name="organizationId">Organization ID we would like to get the Object Store from</param>
/// <param name="key">Key for the Object Store file</param>
/// <returns><see cref="PropertiesObjectStoreResponse"/></returns>
/// <remarks>It does not work when the object store is a directory</remarks>
public PropertiesObjectStoreResponse GetObjectStoreProperties(string organizationId, string key);
/// <summary>
/// Upload files to the Object Store
/// </summary>
/// <param name="organizationId">Organization ID we would like to upload the file to</param>
/// <param name="key">Key to the Object Store file</param>
/// <param name="objectData">File to be uploaded</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse SetObjectStore(string organizationId, string key, byte[] objectData);
/// <summary>
/// Request to delete Object Store metadata of a specific organization and key
/// </summary>
/// <param name="organizationId">Organization ID we would like to delete the Object Store file from</param>
/// <param name="key">Key to the Object Store file</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse DeleteObjectStore(string organizationId, string key);
/// <summary>
/// Gets a list of LEAN versions with their corresponding basic descriptions
/// </summary>
public VersionsResponse ReadLeanVersions();
/// <summary>
/// Broadcast a live command
/// </summary>
/// <param name="organizationId">Organization ID of the projects we would like to broadcast the command to</param>
/// <param name="excludeProjectId">Project for the live instance we want to exclude from the broadcast list</param>
/// <param name="command">The command to run</param>
/// <returns><see cref="RestResponse"/></returns>
public RestResponse BroadcastLiveCommand(string organizationId, int? excludeProjectId, object command);
}
}
+161
View File
@@ -0,0 +1,161 @@
/*
* 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 QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Brokerage interface that defines the operations all brokerages must implement. The IBrokerage implementation
/// must have a matching IBrokerageFactory implementation.
/// </summary>
public interface IBrokerage : IBrokerageCashSynchronizer, IDisposable
{
/// <summary>
/// Event that fires each time the brokerage order id changes
/// </summary>
event EventHandler<BrokerageOrderIdChangedEvent> OrderIdChanged;
/// <summary>
/// Event that fires each time the status for a list of orders change
/// </summary>
event EventHandler<List<OrderEvent>> OrdersStatusChanged;
/// <summary>
/// Event that fires each time an order is updated in the brokerage side
/// </summary>
/// <remarks>
/// These are not status changes but mainly price changes, like the stop price of a trailing stop order
/// </remarks>
event EventHandler<OrderUpdateEvent> OrderUpdated;
/// <summary>
/// Event that fires each time a short option position is assigned
/// </summary>
event EventHandler<OrderEvent> OptionPositionAssigned;
/// <summary>
/// Event that fires each time an option position has changed
/// </summary>
event EventHandler<OptionNotificationEventArgs> OptionNotification;
/// <summary>
/// Event that fires each time there's a brokerage side generated order
/// </summary>
event EventHandler<NewBrokerageOrderNotificationEventArgs> NewBrokerageOrderNotification;
/// <summary>
/// Event that fires each time a delisting occurs
/// </summary>
/// <remarks>TODO: Wire brokerages to call this event to process delistings</remarks>
event EventHandler<DelistingNotificationEventArgs> DelistingNotification;
/// <summary>
/// Event that fires each time a user's brokerage account is changed
/// </summary>
event EventHandler<AccountEvent> AccountChanged;
/// <summary>
/// Event that fires when a message is received from the brokerage
/// </summary>
event EventHandler<BrokerageMessageEvent> Message;
/// <summary>
/// Gets the name of the brokerage
/// </summary>
string Name { get; }
/// <summary>
/// Returns true if we're currently connected to the broker
/// </summary>
bool IsConnected { get; }
/// <summary>
/// Gets all open orders on the account
/// </summary>
/// <returns>The open orders returned from IB</returns>
List<Order> GetOpenOrders();
/// <summary>
/// Gets all holdings for the account
/// </summary>
/// <returns>The current holdings from the account</returns>
List<Holding> GetAccountHoldings();
/// <summary>
/// Gets the current cash balance for each currency held in the brokerage account
/// </summary>
/// <returns>The current cash balance for each currency available for trading</returns>
List<CashAmount> GetCashBalance();
/// <summary>
/// Places a new order and assigns a new broker ID to the order
/// </summary>
/// <param name="order">The order to be placed</param>
/// <returns>True if the request for a new order has been placed, false otherwise</returns>
bool PlaceOrder(Order order);
/// <summary>
/// Updates the order with the same id
/// </summary>
/// <param name="order">The new order information</param>
/// <returns>True if the request was made for the order to be updated, false otherwise</returns>
bool UpdateOrder(Order order);
/// <summary>
/// Cancels the order with the specified ID
/// </summary>
/// <param name="order">The order to cancel</param>
/// <returns>True if the request was made for the order to be canceled, false otherwise</returns>
bool CancelOrder(Order order);
/// <summary>
/// Connects the client to the broker's remote servers
/// </summary>
void Connect();
/// <summary>
/// Disconnects the client from the broker's remote servers
/// </summary>
void Disconnect();
/// <summary>
/// Specifies whether the brokerage will instantly update account balances
/// </summary>
bool AccountInstantlyUpdated { get; }
/// <summary>
/// Returns the brokerage account's base currency
/// </summary>
string AccountBaseCurrency { get; }
/// <summary>
/// Gets the history for the requested security
/// </summary>
/// <param name="request">The historical data request</param>
/// <returns>An enumerable of bars covering the span specified in the request</returns>
IEnumerable<BaseData> GetHistory(HistoryRequest request);
/// <summary>
/// Enables or disables concurrent processing of messages to and from the brokerage.
/// </summary>
bool ConcurrencyEnabled { get; set; }
}
}
@@ -0,0 +1,46 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines live brokerage cash synchronization operations.
/// </summary>
public interface IBrokerageCashSynchronizer
{
/// <summary>
/// Gets the datetime of the last sync (UTC)
/// </summary>
DateTime LastSyncDateTimeUtc { get; }
/// <summary>
/// Returns whether the brokerage should perform the cash synchronization
/// </summary>
/// <param name="currentTimeUtc">The current time (UTC)</param>
/// <returns>True if the cash sync should be performed</returns>
bool ShouldPerformCashSync(DateTime currentTimeUtc);
/// <summary>
/// Synchronizes the cashbook with the brokerage account
/// </summary>
/// <param name="algorithm">The algorithm instance</param>
/// <param name="currentTimeUtc">The current time (UTC)</param>
/// <param name="getTimeSinceLastFill">A function which returns the time elapsed since the last fill</param>
/// <returns>True if the cash sync was performed successfully</returns>
bool PerformCashSync(IAlgorithm algorithm, DateTime currentTimeUtc, Func<TimeSpan> getTimeSinceLastFill);
}
}
+64
View File
@@ -0,0 +1,64 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Brokerages;
using QuantConnect.Packets;
using QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines factory types for brokerages. Every IBrokerage is expected to also implement an IBrokerageFactory.
/// </summary>
[InheritedExport(typeof(IBrokerageFactory))]
public interface IBrokerageFactory : IDisposable
{
/// <summary>
/// Gets the type of brokerage produced by this factory
/// </summary>
Type BrokerageType { get; }
/// <summary>
/// Gets the brokerage data required to run the brokerage from configuration/disk
/// </summary>
/// <remarks>
/// The implementation of this property will create the brokerage data dictionary required for
/// running live jobs. See <see cref="IJobQueueHandler.NextJob"/>
/// </remarks>
Dictionary<string, string> BrokerageData { get; }
/// <summary>
/// Gets a brokerage model that can be used to model this brokerage's unique behaviors
/// </summary>
/// <param name="orderProvider">The order provider</param>
IBrokerageModel GetBrokerageModel(IOrderProvider orderProvider);
/// <summary>
/// Creates a new IBrokerage instance
/// </summary>
/// <param name="job">The job packet to create the brokerage for</param>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>A new brokerage instance</returns>
IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm);
/// <summary>
/// Gets a brokerage message handler
/// </summary>
IBrokerageMessageHandler CreateBrokerageMessageHandler(IAlgorithm algorithm, AlgorithmNodePacket job, IApi api);
}
}
+76
View File
@@ -0,0 +1,76 @@
/*
* 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.Threading;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Interface used to handle items being processed and communicate busy state
/// </summary>
/// <typeparam name="T">The item type being processed</typeparam>
public interface IBusyCollection<T> : IDisposable
{
/// <summary>
/// Gets a wait handle that can be used to wait until this instance is done
/// processing all of it's item
/// </summary>
WaitHandle WaitHandle { get; }
/// <summary>
/// Gets the number of items held within this collection
/// </summary>
int Count { get; }
/// <summary>
/// Returns true if processing, false otherwise
/// </summary>
bool IsBusy { get; }
/// <summary>
/// Adds the items to this collection
/// </summary>
/// <param name="item">The item to be added</param>
void Add(T item);
/// <summary>
/// Adds the items to this collection
/// </summary>
/// <param name="item">The item to be added</param>
/// <param name="cancellationToken">A cancellation token to observer</param>
void Add(T item, CancellationToken cancellationToken);
/// <summary>
/// Marks the collection as not accepting any more additions
/// </summary>
void CompleteAdding();
/// <summary>
/// Provides a consuming enumerable for items in this collection.
/// </summary>
/// <returns>An enumerable that removes and returns items from the collection</returns>
IEnumerable<T> GetConsumingEnumerable();
/// <summary>
/// Provides a consuming enumerable for items in this collection.
/// </summary>
/// <param name="cancellationToken">A cancellation token to observer</param>
/// <returns>An enumerable that removes and returns items from the collection</returns>
IEnumerable<T> GetConsumingEnumerable(CancellationToken cancellationToken);
}
}
+52
View File
@@ -0,0 +1,52 @@
/*
* 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.IO;
using System.Collections.Generic;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines a cache for data
/// </summary>
public interface IDataCacheProvider : IDisposable
{
/// <summary>
/// Property indicating the data is temporary in nature and should not be cached
/// </summary>
bool IsDataEphemeral { get; }
/// <summary>
/// Fetch data from the cache
/// </summary>
/// <param name="key">A string representing the key of the cached data</param>
/// <returns>An <see cref="Stream"/> of the cached data</returns>
Stream Fetch(string key);
/// <summary>
/// Store the data in the cache
/// </summary>
/// <param name="key">The source of the data, used as a key to retrieve data in the cache</param>
/// <param name="data">The data to cache as a byte array</param>
void Store(string key, byte[] data);
/// <summary>
/// Returns a list of zip entries in a provided zip file
/// </summary>
List<string> GetZipEntries(string zipFile);
}
}
+38
View File
@@ -0,0 +1,38 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Packets;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Specifies data channel settings
/// </summary>
public interface IDataChannelProvider
{
/// <summary>
/// Initializes the class with an algorithm node packet
/// </summary>
/// <param name="packet">Algorithm node packet</param>
void Initialize(AlgorithmNodePacket packet);
/// <summary>
/// True if this subscription configuration should be streamed
/// </summary>
bool ShouldStreamSubscription(SubscriptionDataConfig config);
}
}
+37
View File
@@ -0,0 +1,37 @@
/*
* 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.ComponentModel.Composition;
using System;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Monitors data requests and reports on missing data
/// </summary>
[InheritedExport(typeof(IDataMonitor))]
public interface IDataMonitor : IDisposable
{
/// <summary>
/// Terminates the data monitor generating a final report
/// </summary>
void Exit();
/// <summary>
/// Event handler for the <see cref="IDataProvider.NewDataRequest"/> event
/// </summary>
void OnNewDataRequest(object sender, DataProviderNewDataRequestEventArgs e);
}
}
@@ -0,0 +1,47 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Packets;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Entity in charge of handling data permissions
/// </summary>
public interface IDataPermissionManager
{
/// <summary>
/// The data channel provider instance
/// </summary>
IDataChannelProvider DataChannelProvider { get; }
/// <summary>
/// Initialize the data permission manager
/// </summary>
/// <param name="job">The job packet</param>
void Initialize(AlgorithmNodePacket job);
/// <summary>
/// Will assert the requested configuration is valid for the current job
/// </summary>
/// <param name="subscriptionRequest">The data subscription configuration to assert</param>
/// <param name="startTimeLocal">The start time of this request</param>
/// <param name="endTimeLocal">The end time of this request</param>
void AssertConfiguration(SubscriptionDataConfig subscriptionRequest, DateTime startTimeLocal, DateTime endTimeLocal);
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
* 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.IO;
using System.ComponentModel.Composition;
using System;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Fetches a remote file for a security.
/// Must save the file to Globals.DataFolder.
/// </summary>
[InheritedExport(typeof(IDataProvider))]
public interface IDataProvider
{
/// <summary>
/// Event raised each time data fetch is finished (successfully or not)
/// </summary>
event EventHandler<DataProviderNewDataRequestEventArgs> NewDataRequest;
/// <summary>
/// Retrieves data to be used in an algorithm
/// </summary>
/// <param name="key">A string representing where the data is stored</param>
/// <returns>A <see cref="Stream"/> of the data requested</returns>
Stream Fetch(string key);
}
}
+50
View File
@@ -0,0 +1,50 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Events related to data providers
/// </summary>
public interface IDataProviderEvents
{
/// <summary>
/// Event fired when an invalid configuration has been detected
/// </summary>
event EventHandler<InvalidConfigurationDetectedEventArgs> InvalidConfigurationDetected;
/// <summary>
/// Event fired when the numerical precision in the factor file has been limited
/// </summary>
event EventHandler<NumericalPrecisionLimitedEventArgs> NumericalPrecisionLimited;
/// <summary>
/// Event fired when there was an error downloading a remote file
/// </summary>
event EventHandler<DownloadFailedEventArgs> DownloadFailed;
/// <summary>
/// Event fired when there was an error reading the data
/// </summary>
event EventHandler<ReaderErrorDetectedEventArgs> ReaderErrorDetected;
/// <summary>
/// Event fired when the start date has been limited
/// </summary>
event EventHandler<StartDateLimitedEventArgs> StartDateLimited;
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Data;
using QuantConnect.Packets;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Task requestor interface with cloud system
/// </summary>
[InheritedExport(typeof(IDataQueueHandler))]
public interface IDataQueueHandler : IDisposable
{
/// <summary>
/// Subscribe to the specified configuration
/// </summary>
/// <param name="dataConfig">defines the parameters to subscribe to a data feed</param>
/// <param name="newDataAvailableHandler">handler to be fired on new data available</param>
/// <returns>The new enumerator for this subscription request</returns>
IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler);
/// <summary>
/// Removes the specified configuration
/// </summary>
/// <param name="dataConfig">Subscription config to be removed</param>
void Unsubscribe(SubscriptionDataConfig dataConfig);
/// <summary>
/// Sets the job we're subscribing for
/// </summary>
/// <param name="job">Job we're subscribing for</param>
void SetJob(LiveNodePacket job);
/// <summary>
/// Returns whether the data provider is connected
/// </summary>
/// <returns>True if the data provider is connected</returns>
bool IsConnected { get; }
}
}
@@ -0,0 +1,43 @@
/*
* 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.Collections.Generic;
namespace QuantConnect.Interfaces
{
/// <summary>
/// This interface allows interested parties to lookup or enumerate the available symbols. Data source exposes it if this feature is available.
/// Availability of a symbol doesn't imply that it is possible to trade it. This is a data source specific interface, not broker specific.
/// </summary>
public interface IDataQueueUniverseProvider
{
/// <summary>
/// Method returns a collection of Symbols that are available at the data source.
/// </summary>
/// <param name="symbol">Symbol to lookup</param>
/// <param name="includeExpired">Include expired contracts</param>
/// <param name="securityCurrency">Expected security currency(if any)</param>
/// <returns>Enumerable of Symbols, that are associated with the provided Symbol</returns>
IEnumerable<Symbol> LookupSymbols(Symbol symbol, bool includeExpired, string securityCurrency = null);
/// <summary>
/// Returns whether selection can take place or not.
/// </summary>
/// <remarks>This is useful to avoid a selection taking place during invalid times, for example IB reset times or when not connected,
/// because if allowed selection would fail since IB isn't running and would kill the algorithm</remarks>
/// <returns>True if selection can take place</returns>
bool CanPerformSelection();
}
}
+44
View File
@@ -0,0 +1,44 @@
/*
* 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.Collections.Generic;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Wrapper on the API for downloading data for an algorithm.
/// </summary>
public interface IDownloadProvider
{
/// <summary>
/// Method for downloading data for an algorithm
/// </summary>
/// <param name="address">Source URL to download from</param>
/// <param name="headers">Headers to pass to the site</param>
/// <param name="userName">Username for basic authentication</param>
/// <param name="password">Password for basic authentication</param>
/// <returns>String contents of file</returns>
string Download(string address, IEnumerable<KeyValuePair<string, string>> headers, string userName, string password);
/// <summary>
/// Method for downloading data for an algorithm that can be read from a stream
/// </summary>
/// <param name="address">Source URL to download from</param>
/// <param name="headers">Headers to pass to the site</param>
/// <param name="userName">Username for basic authentication</param>
/// <param name="password">Password for basic authentication</param>
/// <returns>String contents of file</returns>
byte[] DownloadBytes(string address, IEnumerable<KeyValuePair<string, string>> headers, string userName, string password);
}
}
+137
View File
@@ -0,0 +1,137 @@
/*
* 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 Python.Runtime;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Represents a generic collection of key/value pairs that implements python dictionary methods.
/// </summary>
public interface IExtendedDictionary<TKey, TValue>
{
/// <summary>
/// Removes all keys and values from the <see cref="IExtendedDictionary{TKey, TValue}"/>.
/// </summary>
void clear();
/// <summary>
/// Creates a shallow copy of the <see cref="IExtendedDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>Returns a shallow copy of the dictionary. It doesn't modify the original dictionary.</returns>
PyDict copy();
/// <summary>
/// Creates a new dictionary from the given sequence of elements.
/// </summary>
/// <param name="sequence">Sequence of elements which is to be used as keys for the new dictionary</param>
/// <returns>Returns a new dictionary with the given sequence of elements as the keys of the dictionary.</returns>
PyDict fromkeys(TKey[] sequence);
/// <summary>
/// Creates a new dictionary from the given sequence of elements with a value provided by the user.
/// </summary>
/// <param name="sequence">Sequence of elements which is to be used as keys for the new dictionary</param>
/// <param name="value">Value which is set to each each element of the dictionary</param>
/// <returns>Returns a new dictionary with the given sequence of elements as the keys of the dictionary.
/// Each element of the newly created dictionary is set to the provided value.</returns>
PyDict fromkeys(TKey[] sequence, TValue value);
/// <summary>
/// Returns the value for the specified key if key is in dictionary.
/// </summary>
/// <param name="key">Key to be searched in the dictionary</param>
/// <returns>The value for the specified key if key is in dictionary.
/// None if the key is not found and value is not specified.</returns>
TValue get(TKey key);
/// <summary>
/// Returns the value for the specified key if key is in dictionary.
/// </summary>
/// <param name="key">Key to be searched in the dictionary</param>
/// <param name="value">Value to be returned if the key is not found. The default value is null.</param>
/// <returns>The value for the specified key if key is in dictionary.
/// value if the key is not found and value is specified.</returns>
TValue get(TKey key, TValue value);
/// <summary>
/// Returns a view object that displays a list of dictionary's (key, value) tuple pairs.
/// </summary>
/// <returns>Returns a view object that displays a list of a given dictionary's (key, value) tuple pair.</returns>
PyList items();
/// <summary>
/// Returns a view object that displays a list of all the keys in the dictionary
/// </summary>
/// <returns>Returns a view object that displays a list of all the keys.
/// When the dictionary is changed, the view object also reflect these changes.</returns>
PyList keys();
/// <summary>
/// Returns and removes an arbitrary element (key, value) pair from the dictionary.
/// </summary>
/// <returns>Returns an arbitrary element (key, value) pair from the dictionary
/// removes an arbitrary element(the same element which is returned) from the dictionary.
/// Note: Arbitrary elements and random elements are not same.The popitem() doesn't return a random element.</returns>
PyTuple popitem();
/// <summary>
/// Returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
/// </summary>
/// <param name="key">Key with null/None value is inserted to the dictionary if key is not in the dictionary.</param>
/// <returns>The value of the key if it is in the dictionary
/// None if key is not in the dictionary</returns>
TValue setdefault(TKey key);
/// <summary>
/// Returns the value of a key (if the key is in dictionary). If not, it inserts key with a value to the dictionary.
/// </summary>
/// <param name="key">Key with a value default_value is inserted to the dictionary if key is not in the dictionary.</param>
/// <param name="default_value">Default value</param>
/// <returns>The value of the key if it is in the dictionary
/// default_value if key is not in the dictionary and default_value is specified</returns>
TValue setdefault(TKey key, TValue default_value);
/// <summary>
/// Removes and returns an element from a dictionary having the given key.
/// </summary>
/// <param name="key">Key which is to be searched for removal</param>
/// <returns>If key is found - removed/popped element from the dictionary
/// If key is not found - KeyError exception is raised</returns>
TValue pop(TKey key);
/// <summary>
/// Removes and returns an element from a dictionary having the given key.
/// </summary>
/// <param name="key">Key which is to be searched for removal</param>
/// <param name="default_value">Value which is to be returned when the key is not in the dictionary</param>
/// <returns>If key is found - removed/popped element from the dictionary
/// If key is not found - value specified as the second argument(default)</returns>
TValue pop(TKey key, TValue default_value);
/// <summary>
/// Updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs.
/// The update() method adds element(s) to the dictionary if the key is not in the dictionary.If the key is in the dictionary, it updates the key with the new value.
/// </summary>
/// <param name="other">Takes either a dictionary or an iterable object of key/value pairs (generally tuples).</param>
void update(PyObject other);
/// <summary>
/// Returns a view object that displays a list of all the values in the dictionary.
/// </summary>
/// <returns>Returns a view object that displays a list of all values in a given dictionary.</returns>
PyList values();
}
}
+43
View File
@@ -0,0 +1,43 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Data.Auxiliary;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides instances of <see cref="FactorFile{T}"/> at run time
/// </summary>
[InheritedExport(typeof(IFactorFileProvider))]
public interface IFactorFileProvider
{
/// <summary>
/// Initializes our FactorFileProvider by supplying our mapFileProvider
/// and dataProvider
/// </summary>
/// <param name="mapFileProvider">MapFileProvider to use</param>
/// <param name="dataProvider">DataProvider to use</param>
void Initialize(IMapFileProvider mapFileProvider, IDataProvider dataProvider);
/// <summary>
/// Gets a <see cref="FactorFile{T}"/> instance for the specified symbol, or null if not found
/// </summary>
/// <param name="symbol">The security's symbol whose factor file we seek</param>
/// <returns>The resolved factor file, or null if not found</returns>
IFactorProvider Get(Symbol symbol);
}
}
+34
View File
@@ -0,0 +1,34 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides the full future chain for a given underlying.
/// </summary>
public interface IFutureChainProvider
{
/// <summary>
/// Gets the list of future contracts for a given underlying symbol
/// </summary>
/// <param name="symbol">The underlying symbol</param>
/// <param name="date">The date for which to request the future chain (only used in backtesting)</param>
/// <returns>The list of future contracts</returns>
IEnumerable<Symbol> GetFutureContractList(Symbol symbol, DateTime date);
}
}
+49
View File
@@ -0,0 +1,49 @@
/*
* 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.Collections.Generic;
using System.ComponentModel.Composition;
using NodaTime;
using QuantConnect.Data;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides historical data to an algorithm at runtime
/// </summary>
[InheritedExport(typeof(IHistoryProvider))]
public interface IHistoryProvider : IDataProviderEvents
{
/// <summary>
/// Gets the total number of data points emitted by this history provider
/// </summary>
int DataPointCount { get; }
/// <summary>
/// Initializes this history provider to work for the specified job
/// </summary>
/// <param name="parameters">The initialization parameters</param>
void Initialize(HistoryProviderInitializeParameters parameters);
/// <summary>
/// Gets the history for the requested securities
/// </summary>
/// <param name="requests">The historical data requests</param>
/// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param>
/// <returns>An enumerable of the slices of data covering the span specified in each request</returns>
IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone);
}
}
+45
View File
@@ -0,0 +1,45 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Packets;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Task requestor interface with cloud system
/// </summary>
[InheritedExport(typeof(IJobQueueHandler))]
public interface IJobQueueHandler
{
/// <summary>
/// Initialize the internal state
/// </summary>
void Initialize(IApi api, IMessagingHandler messagingHandler);
/// <summary>
/// Request the next task to run through the engine:
/// </summary>
/// <returns>Algorithm job to process</returns>
AlgorithmNodePacket NextJob(out string algorithmPath);
/// <summary>
/// Signal task complete
/// </summary>
/// <param name="job">Work to do.</param>
void AcknowledgeJob(AlgorithmNodePacket job);
}
}
+42
View File
@@ -0,0 +1,42 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Data.Auxiliary;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides instances of <see cref="MapFileResolver"/> at run time
/// </summary>
[InheritedExport(typeof(IMapFileProvider))]
public interface IMapFileProvider
{
/// <summary>
/// Initializes our MapFileProvider by supplying our dataProvider
/// </summary>
/// <param name="dataProvider">DataProvider to use</param>
void Initialize(IDataProvider dataProvider);
/// <summary>
/// Gets a <see cref="MapFileResolver"/> representing all the map
/// files for the specified market
/// </summary>
/// <param name="auxiliaryDataKey">Key used to fetch a map file resolver. Specifying market and security type</param>
/// <returns>A <see cref="MapFileResolver"/> containing all map files for the specified market</returns>
MapFileResolver Get(AuxiliaryDataKey auxiliaryDataKey);
}
}
+61
View File
@@ -0,0 +1,61 @@
/*
* 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.ComponentModel.Composition;
using QuantConnect.Notifications;
using QuantConnect.Packets;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Messaging System Plugin Interface.
/// Provides a common messaging pattern between desktop and cloud implementations of QuantConnect.
/// </summary>
[InheritedExport(typeof(IMessagingHandler))]
public interface IMessagingHandler : IDisposable
{
/// <summary>
/// Gets or sets whether this messaging handler has any current subscribers.
/// When set to false, messages won't be sent.
/// </summary>
bool HasSubscribers { get; set; }
/// <summary>
/// Initialize the Messaging System Plugin.
/// </summary>
/// <param name="initializeParameters">The parameters required for initialization</param>
void Initialize(MessagingHandlerInitializeParameters initializeParameters);
/// <summary>
/// Set the user communication channel
/// </summary>
/// <param name="job">The job packet</param>
void SetAuthentication(AlgorithmNodePacket job);
/// <summary>
/// Send any message with a base type of Packet.
/// </summary>
/// <param name="packet">Packet of data to send via the messaging system plugin</param>
void Send(Packet packet);
/// <summary>
/// Send any notification with a base type of Notification.
/// </summary>
/// <param name="notification">The notification to be sent.</param>
void SendNotification(Notification notification);
}
}
+100
View File
@@ -0,0 +1,100 @@
/*
* 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 QuantConnect.Packets;
using System.Collections.Generic;
using System.ComponentModel.Composition;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides object storage for data persistence.
/// </summary>
[InheritedExport(typeof(IObjectStore))]
public interface IObjectStore : IDisposable, IEnumerable<KeyValuePair<string, byte[]>>
{
/// <summary>
/// Gets the maximum storage limit in bytes
/// </summary>
long MaxSize { get; }
/// <summary>
/// Gets the maximum number of files allowed
/// </summary>
int MaxFiles { get; }
/// <summary>
/// Event raised each time there's an error
/// </summary>
event EventHandler<ObjectStoreErrorRaisedEventArgs> ErrorRaised;
/// <summary>
/// Initializes the object store
/// </summary>
/// <param name="userId">The user id</param>
/// <param name="projectId">The project id</param>
/// <param name="userToken">The user token</param>
/// <param name="controls">The job controls instance</param>
/// <param name="algorithmMode">The algorithm mode</param>
void Initialize(int userId, int projectId, string userToken, Controls controls, AlgorithmMode algorithmMode);
/// <summary>
/// Determines whether the store contains data for the specified path
/// </summary>
/// <param name="path">The object path</param>
/// <returns>True if the key was found</returns>
bool ContainsKey(string path);
/// <summary>
/// Returns the object data for the specified key
/// </summary>
/// <param name="path">The object key</param>
/// <returns>A byte array containing the data</returns>
byte[] ReadBytes(string path);
/// <summary>
/// Saves the object data for the specified path
/// </summary>
/// <param name="path">The object path</param>
/// <param name="contents">The object data</param>
/// <returns>True if the save operation was successful</returns>
bool SaveBytes(string path, byte[] contents);
/// <summary>
/// Deletes the object data for the specified path
/// </summary>
/// <param name="path">The object path</param>
/// <returns>True if the delete operation was successful</returns>
bool Delete(string path);
/// <summary>
/// Returns the file path for the specified path
/// </summary>
/// <param name="path">The object path</param>
/// <returns>The path for the file</returns>
string GetFilePath(string path);
/// <summary>
/// Returns the file paths present in the object store. This is specially useful not to load the object store into memory
/// </summary>
ICollection<string> Keys { get; }
/// <summary>
/// Will clear the object store state cache. This is useful when the object store is used concurrently by nodes which want to share information
/// </summary>
void Clear();
}
}
+35
View File
@@ -0,0 +1,35 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Provides the full option chain for a given underlying.
/// </summary>
public interface IOptionChainProvider
{
/// <summary>
/// Gets the list of option contracts for a given underlying symbol
/// </summary>
/// <param name="symbol">The option or the underlying symbol to get the option chain for.
/// Providing the option allows targetting an option ticker different than the default e.g. SPXW</param>
/// <param name="date">The date for which to request the option chain (only used in backtesting)</param>
/// <returns>The list of option contracts</returns>
IEnumerable<Symbol> GetOptionContractList(Symbol symbol, DateTime date);
}
}
+44
View File
@@ -0,0 +1,44 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Securities.Option;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Reduced interface for accessing <see cref="Option"/>
/// specific price properties and methods
/// </summary>
public interface IOptionPrice : ISecurityPrice
{
/// <summary>
/// Gets a reduced interface of the underlying security object.
/// </summary>
ISecurityPrice Underlying { get; }
/// <summary>
/// Evaluates the specified option contract to compute a theoretical price, IV and greeks
/// </summary>
/// <param name="slice">The current data slice. This can be used to access other information
/// available to the algorithm</param>
/// <param name="contract">The option contract to evaluate</param>
/// <returns>An instance of <see cref="OptionPriceModelResult"/> containing the theoretical
/// price of the specified option contract</returns>
OptionPriceModelResult EvaluatePriceModel(Slice slice, OptionContract contract);
}
}
+37
View File
@@ -0,0 +1,37 @@
/*
* 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 Newtonsoft.Json;
using QuantConnect.Orders;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Contains additional properties and settings for an order
/// </summary>
public interface IOrderProperties
{
/// <summary>
/// Defines the length of time over which an order will continue working before it is cancelled
/// </summary>
[JsonProperty(PropertyName = "timeInForce")]
TimeInForce TimeInForce { get; set; }
/// <summary>
/// Returns a new instance clone of this object
/// </summary>
IOrderProperties Clone();
}
}
@@ -0,0 +1,30 @@
/*
* 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.
*/
namespace QuantConnect.Interfaces
{
/// <summary>
/// Primary Exchange Provider interface
/// </summary>
public interface IPrimaryExchangeProvider
{
/// <summary>
/// Gets the primary exchange for a given security identifier
/// </summary>
/// <param name="securityIdentifier">The security identifier to get the primary exchange for</param>
/// <returns>Returns the primary exchange or null if not found</returns>
Exchange GetPrimaryExchange(SecurityIdentifier securityIdentifier);
}
}
@@ -0,0 +1,57 @@
/*
* 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.Collections.Generic;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines a C# algorithm as a regression algorithm to be run as part of the test suite.
/// This interface also allows the algorithm to declare that it has versions in other languages
/// that should yield identical results.
/// </summary>
public interface IRegressionAlgorithmDefinition
{
/// <summary>
/// Final status of the algorithm
/// </summary>
AlgorithmStatus AlgorithmStatus { get; }
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
bool CanRunLocally { get; }
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
List<Language> Languages { get; }
/// <summary>
/// Data Points count of all timeslices of algorithm
/// </summary>
long DataPoints { get; }
/// <summary>
/// Data Points count of the algorithm history
/// </summary>
int AlgorithmHistoryDataPoints { get; }
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
Dictionary<string, string> ExpectedStatistics { get; }
}
}
@@ -0,0 +1,32 @@
/*
* 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.
*/
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines interface for research notebooks to be run as part of the research test suite.
/// </summary>
public interface IRegressionResearchDefinition
{
#pragma warning disable CS1574
/// <summary>
/// This is used by the research regression test system to validate the output
/// </summary>
/// <remarks>Requires to be implemented last in the file <see cref="ResearchRegressionTests.UpdateResearchRegressionOutputInSourceFile"/>
/// get should start from next line</remarks>
#pragma warning restore CS1574
string ExpectedOutput { get; }
}
}
@@ -0,0 +1,34 @@
/*
* 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 QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Reduced interface which provides an instance which implements <see cref="ISecurityInitializer"/>
/// </summary>
public interface ISecurityInitializerProvider
{
/// <summary>
/// Gets an instance that is to be used to initialize newly created securities.
/// </summary>
ISecurityInitializer SecurityInitializer
{
get;
}
}
}
+104
View File
@@ -0,0 +1,104 @@
/*
* 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 QuantConnect.Data;
using QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Reduced interface which allows setting and accessing
/// price properties for a <see cref="Security"/>
/// </summary>
public interface ISecurityPrice
{
/// <summary>
/// Get the current value of the security.
/// </summary>
decimal Price { get; }
/// <summary>
/// If this uses trade bar data, return the most recent close.
/// </summary>
decimal Close { get; }
/// <summary>
/// Access to the volume of the equity today
/// </summary>
decimal Volume { get; }
/// <summary>
/// Gets the most recent bid price if available
/// </summary>
decimal BidPrice { get; }
/// <summary>
/// Gets the most recent bid size if available
/// </summary>
decimal BidSize { get; }
/// <summary>
/// Gets the most recent ask price if available
/// </summary>
decimal AskPrice { get; }
/// <summary>
/// Gets the most recent ask size if available
/// </summary>
decimal AskSize { get; }
/// <summary>
/// Access to the open interest of the security today
/// </summary>
long OpenInterest { get; }
/// <summary>
/// <see cref="Symbol"/> for the asset.
/// </summary>
Symbol Symbol { get; }
/// <summary>
/// <see cref="SymbolProperties"/> of the symbol
/// </summary>
SymbolProperties SymbolProperties { get; }
/// <summary>
/// Update any security properties based on the latest market data and time
/// </summary>
/// <param name="data">New data packet from LEAN</param>
void SetMarketPrice(BaseData data);
/// <summary>
/// Updates all of the security properties, such as price/OHLCV/bid/ask based
/// on the data provided. Data is also stored into the security's data cache
/// </summary>
/// <param name="data">The security update data</param>
/// <param name="dataType">The data type</param>
/// <param name="containsFillForwardData">Flag indicating whether
/// <param name="isInternalConfig">True if this update data corresponds to an internal subscription
/// such as currency or security benchmark</param>
/// <paramref name="data"/> contains any fill forward bar or not</param>
void Update(IReadOnlyList<BaseData> data, Type dataType, bool? containsFillForwardData, bool isInternalConfig);
/// <summary>
/// Get the last price update set to the security.
/// </summary>
/// <returns>BaseData object for this security</returns>
BaseData GetLastData();
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* 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.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// This interface exposes methods for creating a new <see cref="Security" />
/// </summary>
public interface ISecurityService
{
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
Security CreateSecurity(Symbol symbol,
List<SubscriptionDataConfig> subscriptionDataConfigList,
decimal leverage = 0,
bool addToSymbolCache = true,
Security underlying = null,
bool seedSecurity = true);
/// <summary>
/// Creates a new security
/// </summary>
/// <remarks>Following the obsoletion of Security.Subscriptions,
/// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks>
Security CreateSecurity(Symbol symbol,
SubscriptionDataConfig subscriptionDataConfig,
decimal leverage = 0,
bool addToSymbolCache = true,
Security underlying = null,
bool seedSecurity = true);
/// <summary>
/// Creates a new benchmark security
/// </summary>
Security CreateBenchmarkSecurity(Symbol symbol);
}
}
+51
View File
@@ -0,0 +1,51 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines a short list/easy-to-borrow provider
/// </summary>
[StubsAvoidImplicits]
public interface IShortableProvider
{
/// <summary>
/// Gets interest rate charged on borrowed shares for a given asset.
/// </summary>
/// <param name="symbol">Symbol to lookup fee rate</param>
/// <param name="localTime">Time of the algorithm</param>
/// <returns>Fee rate. Zero if the data for the brokerage/date does not exist.</returns>
decimal FeeRate(Symbol symbol, DateTime localTime);
/// <summary>
/// Gets the Fed funds or other currency-relevant benchmark rate minus the interest rate charged on borrowed shares for a given asset.
/// Interest rate - borrow fee rate = borrow rebate rate: 5.32% - 0.25% = 5.07%
/// </summary>
/// <param name="symbol">Symbol to lookup rebate rate</param>
/// <param name="localTime">Time of the algorithm</param>
/// <returns>Rebate fee. Zero if the data for the brokerage/date does not exist.</returns>
decimal RebateRate(Symbol symbol, DateTime localTime);
/// <summary>
/// Gets the quantity shortable for a <see cref="Symbol"/>.
/// </summary>
/// <param name="symbol">Symbol to check shortable quantity</param>
/// <param name="localTime">Local time of the algorithm</param>
/// <returns>The quantity shortable for the given Symbol as a positive number. Null if the Symbol is shortable without restrictions.</returns>
long? ShortableQuantity(Symbol symbol, DateTime localTime);
}
}
+32
View File
@@ -0,0 +1,32 @@
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio.SignalExports;
using System;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Interface to send positions holdings to different 3rd party API's
/// </summary>
public interface ISignalExportTarget: IDisposable
{
/// <summary>
/// Sends user's positions to certain 3rd party API
/// </summary>
/// <param name="parameters">Holdings the user have defined to be sent to certain 3rd party API and the algorithm being ran</param>
bool Send(SignalExportTargetParameters parameters);
}
}
+52
View File
@@ -0,0 +1,52 @@
/*
* 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.IO;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Defines a transport mechanism for data from its source into various reader methods
/// </summary>
public interface IStreamReader : IDisposable
{
/// <summary>
/// Gets the transport medium of this stream reader
/// </summary>
SubscriptionTransportMedium TransportMedium { get; }
/// <summary>
/// Gets whether or not there's more data to be read in the stream
/// </summary>
bool EndOfStream { get; }
/// <summary>
/// Gets the next line/batch of content from the stream
/// </summary>
string ReadLine();
/// <summary>
/// Direct access to the StreamReader instance
/// </summary>
StreamReader StreamReader { get; }
/// <summary>
/// Gets whether or not this stream reader should be rate limited
/// </summary>
bool ShouldBeRateLimited { get; }
}
}
@@ -0,0 +1,34 @@
/*
* 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.Collections.Generic;
using QuantConnect.Data;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Reduced interface which provides access to registered <see cref="SubscriptionDataConfig"/>
/// </summary>
public interface ISubscriptionDataConfigProvider
{
/// <summary>
/// Gets a list of all registered <see cref="SubscriptionDataConfig"/> for a given <see cref="Symbol"/> if any
/// else will return the whole list of subscriptions
/// </summary>
/// <remarks>Will not return internal subscriptions by default</remarks>
List<SubscriptionDataConfig> GetSubscriptionDataConfigs(Symbol symbol = null, bool includeInternalConfigs = false);
}
}
@@ -0,0 +1,85 @@
/*
* 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 QuantConnect.Data;
namespace QuantConnect.Interfaces
{
/// <summary>
/// This interface exposes methods for creating a list of <see cref="SubscriptionDataConfig" /> for a given
/// configuration
/// </summary>
public interface ISubscriptionDataConfigService : ISubscriptionDataConfigProvider
{
/// <summary>
/// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration.
/// Can optionally pass in desired subscription data type to use.
/// If the config already existed will return existing instance instead
/// </summary>
SubscriptionDataConfig Add(
Type dataType,
Symbol symbol,
Resolution? resolution = null,
bool fillForward = true,
bool extendedMarketHours = false,
bool isFilteredSubscription = true,
bool isInternalFeed = false,
bool isCustomData = false,
DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted,
DataMappingMode dataMappingMode = DataMappingMode.OpenInterest,
uint contractDepthOffset = 0
);
/// <summary>
/// Creates and adds a list of <see cref="SubscriptionDataConfig" /> for a given symbol and configuration.
/// Can optionally pass in desired subscription data types to use.
/// If the config already existed will return existing instance instead
/// </summary>
List<SubscriptionDataConfig> Add(
Symbol symbol,
Resolution? resolution = null,
bool fillForward = true,
bool extendedMarketHours = false,
bool isFilteredSubscription = true,
bool isInternalFeed = false,
bool isCustomData = false,
List<Tuple<Type, TickType>> subscriptionDataTypes = null,
DataNormalizationMode dataNormalizationMode = DataNormalizationMode.Adjusted,
DataMappingMode dataMappingMode = DataMappingMode.OpenInterest,
uint contractDepthOffset = 0
);
/// <summary>
/// Get the data feed types for a given <see cref="SecurityType" /> <see cref="Resolution" />
/// </summary>
/// <param name="symbolSecurityType">The <see cref="SecurityType" /> used to determine the types</param>
/// <param name="resolution">The resolution of the data requested</param>
/// <param name="isCanonical">Indicates whether the security is Canonical (future and options)</param>
/// <returns>Types that should be added to the <see cref="SubscriptionDataConfig" /></returns>
List<Tuple<Type, TickType>> LookupSubscriptionConfigDataTypes(
SecurityType symbolSecurityType,
Resolution resolution,
bool isCanonical
);
/// <summary>
/// Gets the available data types
/// </summary>
Dictionary<SecurityType, List<TickType>> AvailableDataTypes { get; }
}
}
+43
View File
@@ -0,0 +1,43 @@
/*
* 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 QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Handles the time in force for an order
/// </summary>
public interface ITimeInForceHandler
{
/// <summary>
/// Checks if an order is expired
/// </summary>
/// <param name="security">The security matching the order</param>
/// <param name="order">The order to be checked</param>
/// <returns>Returns true if the order has expired, false otherwise</returns>
bool IsOrderExpired(Security security, Order order);
/// <summary>
/// Checks if an order fill is valid
/// </summary>
/// <param name="security">The security matching the order</param>
/// <param name="order">The order to be checked</param>
/// <param name="fill">The order fill to be checked</param>
/// <returns>Returns true if the order fill can be emitted, false otherwise</returns>
bool IsFillValid(Security security, Order order, OrderEvent fill);
}
}
+44
View File
@@ -0,0 +1,44 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Interface implemented by <see cref="TimeKeeper"/>
/// </summary>
public interface ITimeKeeper
{
/// <summary>
/// Gets the current time in UTC
/// </summary>
DateTime UtcTime { get; }
/// <summary>
/// Adds the specified time zone to this time keeper
/// </summary>
/// <param name="timeZone"></param>
void AddTimeZone(DateTimeZone timeZone);
/// <summary>
/// Gets the <see cref="LocalTimeKeeper"/> instance for the specified time zone
/// </summary>
/// <param name="timeZone">The time zone whose <see cref="LocalTimeKeeper"/> we seek</param>
/// <returns>The <see cref="LocalTimeKeeper"/> instance for the specified time zone</returns>
LocalTimeKeeper GetLocalTimeKeeper(DateTimeZone timeZone);
}
}
+80
View File
@@ -0,0 +1,80 @@
/*
* 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.Collections.Generic;
using QuantConnect.Data.Market;
using QuantConnect.Orders;
using QuantConnect.Securities;
using QuantConnect.Statistics;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Generates trades from executions and market price updates
/// </summary>
public interface ITradeBuilder
{
/// <summary>
/// Sets the security manager instance
/// </summary>
/// <param name="securities">The security manager</param>
void SetSecurityManager(SecurityManager securities);
/// <summary>
/// Sets the live mode flag
/// </summary>
/// <param name="live">The live mode flag</param>
void SetLiveMode(bool live);
/// <summary>
/// The list of closed trades
/// </summary>
List<Trade> ClosedTrades { get; }
/// <summary>
/// Returns true if there is an open position for the symbol
/// </summary>
/// <param name="symbol">The symbol</param>
/// <returns>true if there is an open position for the symbol</returns>
bool HasOpenPosition(Symbol symbol);
/// <summary>
/// Sets the current market price for the symbol
/// </summary>
/// <param name="symbol"></param>
/// <param name="price"></param>
void SetMarketPrice(Symbol symbol, decimal price);
/// <summary>
/// Applies a split to the trade builder
/// </summary>
/// <param name="split">The split to be applied</param>
/// <param name="liveMode">True if live mode, false for backtest</param>
/// <param name="dataNormalizationMode">The <see cref="DataNormalizationMode"/> for this security</param>
void ApplySplit(Split split, bool liveMode, DataNormalizationMode dataNormalizationMode);
/// <summary>
/// Processes a new fill, eventually creating new trades
/// </summary>
/// <param name="fill">The new fill order event</param>
/// <param name="securityConversionRate">The current security market conversion rate into the account currency</param>
/// <param name="feeInAccountCurrency">The current order fee in the account currency</param>
/// <param name="multiplier">The contract multiplier</param>
void ProcessFill(OrderEvent fill,
decimal securityConversionRate,
decimal feeInAccountCurrency,
decimal multiplier = 1.0m);
}
}
@@ -0,0 +1,38 @@
/*
* 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.
*
*/
namespace QuantConnect.Interfaces
{
/// <summary>
/// Parameters required to initialize a <see cref="IMessagingHandler"/> instance
/// </summary>
public class MessagingHandlerInitializeParameters
{
/// <summary>
/// The api instance to use
/// </summary>
public IApi Api { get; }
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="api">The api instance to use</param>
public MessagingHandlerInitializeParameters(IApi api)
{
Api = api;
}
}
}
@@ -0,0 +1,39 @@
/*
* 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;
namespace QuantConnect.Interfaces
{
/// <summary>
/// Event arguments for the <see cref="IObjectStore.ErrorRaised"/> event
/// </summary>
public class ObjectStoreErrorRaisedEventArgs : EventArgs
{
/// <summary>
/// Gets the <see cref="Exception"/> that was raised
/// </summary>
public Exception Error { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ObjectStoreErrorRaisedEventArgs"/> class
/// </summary>
/// <param name="error">The error that was raised</param>
public ObjectStoreErrorRaisedEventArgs(Exception error)
{
Error = error;
}
}
}