Exemple #1
0
        public Security(Guid securityId, SecurityType securityType, string name, string symbol, CurrencyFormat format, int fractionTraded)
        {
            if (securityId == Guid.Empty)
            {
                throw new ArgumentNullException("securityId");
            }

            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (string.IsNullOrEmpty(symbol))
            {
                throw new ArgumentNullException("symbol");
            }

            if (format == null)
            {
                throw new ArgumentNullException("signFormat");
            }

            if (fractionTraded <= 0)
            {
                throw new ArgumentOutOfRangeException("fractionTraded", "The fraction traded must be greater than or equal to one.");
            }

            this.SecurityId = securityId;
            this.SecurityType = securityType;
            this.Name = name;
            this.Symbol = symbol;
            this.Format = format;
            this.FractionTraded = fractionTraded;
        }
 /********************************************************
 * CLASS CONSTRUCTOR
 *********************************************************/
 /// <summary>
 /// Constructor for Data Subscriptions
 /// </summary>
 /// <param name="objectType">Type of the data objects.</param>
 /// <param name="securityType">SecurityType Enum Set Equity/FOREX/Futures etc.</param>
 /// <param name="symbol">Symbol of the asset we're requesting</param>
 /// <param name="resolution">Resolution of the asset we're requesting</param>
 /// <param name="fillForward">Fill in gaps with historical data</param>
 /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
 public SubscriptionDataConfig(Type objectType, SecurityType securityType = SecurityType.Equity, string symbol = "", Resolution resolution = Resolution.Minute, bool fillForward = true, bool extendedHours = false)
 {
     this.Type = objectType;
     this.Security = securityType;
     this.Resolution = resolution;
     this.Symbol = symbol;
     this.FillDataForward = fillForward;
     this.ExtendedMarketHours = extendedHours;
     this.PriceScaleFactor = 1;
     this.MappedSymbol = symbol;
     switch (resolution)
     {
         case Resolution.Tick:
             Increment = TimeSpan.FromSeconds(0);
             break;
         case Resolution.Second:
             Increment = TimeSpan.FromSeconds(1);
             break;
         default:
         case Resolution.Minute:
             Increment = TimeSpan.FromMinutes(1);
             break;
         case Resolution.Hour:
             Increment = TimeSpan.FromHours(1);
             break;
         case Resolution.Daily:
             Increment = TimeSpan.FromDays(1);
             break;
     }
 }
Exemple #3
0
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct the Market Vehicle
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours)
        {
            //Set Basics:
            this._symbol = symbol;
            this._type = type;
            this._resolution = resolution;
            this._isFillDataForward = fillDataForward;
            this._leverage = leverage;
            this._isExtendedMarketHours = extendedMarketHours;

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, Model);
            Exchange = new SecurityExchange();

            //Cannot initalise a default model.
            Model = null;

            //Set data type:
            if (resolution == Resolution.Minute || resolution == Resolution.Second) {
                _dataType = typeof(TradeBar);
            } else {
                _dataType = typeof(Tick);
            }
        }
 public Connection(string dataSource, SecurityType securityType, string userId, string password)
 {
     m_DataSource = dataSource;
     m_Password = password;
     m_UserId = userId;
     m_SecurityType = securityType;
 }
        /// <summary>
        /// Get historical data enumerable for a single symbol, type and resolution given this start and end time (in UTC).
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="type">Security type</param>
        /// <param name="resolution">Resolution of the data request</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable<BaseData> Get(Symbol symbol, SecurityType type, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            // We subtract one day to make sure we have data from yahoo
            var finishMonth = endUtc.Month;
            var finishDay = endUtc.Subtract(TimeSpan.FromDays(1)).Day;
            var finishYear = endUtc.Year;
            var url = string.Format(_urlPrototype, symbol, 01, 01, 1990, finishMonth, finishDay, finishYear, "d");

            using (var cl = new WebClient())
            {
                var data = cl.DownloadString(url);
                var lines = data.Split('\n');

                for (var i = lines.Length - 1; i >= 1; i--)
                {
                    var str = lines[i].Split(',');
                    if (str.Length < 6) continue;
                    var ymd = str[0].Split('-');
                    var year = Convert.ToInt32(ymd[0]);
                    var month = Convert.ToInt32(ymd[1]);
                    var day = Convert.ToInt32(ymd[2]);
                    var open = decimal.Parse(str[1]);
                    var high = decimal.Parse(str[2]);
                    var low = decimal.Parse(str[3]);
                    var close = decimal.Parse(str[4]);
                    var volume = int.Parse(str[5]);
                    yield return new TradeBar(new DateTime(year, month, day), symbol, open, high, low, close, volume, TimeSpan.FromDays(1));
                }
            }
        }
Exemple #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HistoryRequest"/> class from the specified parameters
 /// </summary>
 /// <param name="startTimeUtc">The start time for this request,</param>
 /// <param name="endTimeUtc">The start time for this request</param>
 /// <param name="dataType">The data type of the output data</param>
 /// <param name="symbol">The symbol to request data for</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="resolution">The requested data resolution</param>
 /// <param name="market">The market this data belongs to</param>
 /// <param name="exchangeHours">The exchange hours used in fill forward processing</param>
 /// <param name="fillForwardResolution">The requested fill forward resolution for this request</param>
 /// <param name="includeExtendedMarketHours">True to include data from pre/post market hours</param>
 /// <param name="isCustomData">True for custom user data, false for normal QC data</param>
 public HistoryRequest(DateTime startTimeUtc, 
     DateTime endTimeUtc,
     Type dataType,
     Symbol symbol,
     SecurityType securityType,
     Resolution resolution,
     string market,
     SecurityExchangeHours exchangeHours,
     Resolution? fillForwardResolution,
     bool includeExtendedMarketHours,
     bool isCustomData
     )
 {
     StartTimeUtc = startTimeUtc;
     EndTimeUtc = endTimeUtc;
     Symbol = symbol;
     ExchangeHours = exchangeHours;
     Resolution = resolution;
     FillForwardResolution = fillForwardResolution;
     IncludeExtendedMarketHours = includeExtendedMarketHours;
     DataType = dataType;
     SecurityType = securityType;
     Market = market;
     IsCustomData = isCustomData;
     TimeZone = exchangeHours.TimeZone;
 }
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct the Market Vehicle
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours, bool useQuantConnectData = false)
        {
            //Set Basics:
            this._symbol = symbol;
            this._type = type;
            this._resolution = resolution;
            this._isFillDataForward = fillDataForward;
            this._leverage = leverage;
            this._isExtendedMarketHours = extendedMarketHours;
            this._isQuantConnectData = useQuantConnectData;

            //Setup Transaction Model for this Asset
            switch (type)
            {
                case SecurityType.Equity:
                    Model = new EquityTransactionModel();
                    break;
                case SecurityType.Forex:
                    Model = new ForexTransactionModel();
                    break;
                case SecurityType.Base:
                    Model = new SecurityTransactionModel();
                    break;
            }

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, Model);
            Exchange = new SecurityExchange();
        }
Exemple #8
0
        /// <summary>
        /// Parse a line from the CSV's into our trade bars.
        /// </summary>
        /// <param name="symbol">Symbol for this tick</param>
        /// <param name="baseDate">Base date of this tick</param>
        /// <param name="line">CSV from data files.</param>
        public TradeBar(SecurityType type, string line, string symbol, DateTime baseDate)
        {
            try {
                string[] csv = line.Split(',');
                //Parse the data into a trade bar:
                this.Symbol = symbol;
                base.Type = MarketDataType.TradeBar;
                decimal scaleFactor = 10000m;

                switch (type)
                {
                    case SecurityType.Equity:
                        Time = baseDate.Date.AddMilliseconds(Convert.ToInt32(csv[0]));
                        Open = Convert.ToDecimal(csv[1]) / scaleFactor;
                        High = Convert.ToDecimal(csv[2]) / scaleFactor;
                        Low = Convert.ToDecimal(csv[3]) / scaleFactor;
                        Close = Convert.ToDecimal(csv[4]) / scaleFactor;
                        Volume = Convert.ToInt64(csv[5]);
                        break;
                    case SecurityType.Forex:
                        Time = DateTime.ParseExact(csv[0], "yyyyMMdd HH:mm:ss.ffff", CultureInfo.InvariantCulture);
                        Open = Convert.ToDecimal(csv[1]);
                        High = Convert.ToDecimal(csv[2]);
                        Low = Convert.ToDecimal(csv[3]);
                        Close = Convert.ToDecimal(csv[4]);
                        break;
                }

                base.Price = Close;
            } catch (Exception err) {
                Log.Error("DataModels: TradeBar(): Error Initializing - " + type + " - " + err.Message + " - " + line);
            }
        }
Exemple #9
0
        /********************************************************
        * CONSTRUCTOR/DELEGATE DEFINITIONS
        *********************************************************/
        /// <summary>
        /// Construct a new security vehicle based on the user options.
        /// </summary>
        public Security(string symbol, SecurityType type, Resolution resolution, bool fillDataForward, decimal leverage, bool extendedMarketHours, bool isDynamicallyLoadedData = false)
        {
            //Set Basics:
            _symbol = symbol;
            _type = type;
            _resolution = resolution;
            _isFillDataForward = fillDataForward;
            _leverage = leverage;
            _isExtendedMarketHours = extendedMarketHours;
            _isDynamicallyLoadedData = isDynamicallyLoadedData;

            //Setup Transaction Model for this Asset
            switch (type)
            {
                case SecurityType.Equity:
                    Model = new EquityTransactionModel();
                    DataFilter = new EquityDataFilter();
                    break;
                case SecurityType.Forex:
                    Model = new ForexTransactionModel();
                    DataFilter = new ForexDataFilter();
                    break;
                case SecurityType.Base:
                    Model = new SecurityTransactionModel();
                    DataFilter = new SecurityDataFilter();
                    break;
            }

            //Holdings for new Vehicle:
            Cache = new SecurityCache();
            Holdings = new SecurityHolding(symbol, type, Model);
            Exchange = new SecurityExchange();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerTreeNode"/> class.
 /// </summary>
 public ServerTreeNode()
 {
     this.ImageIndex = 0;
     this.SelectedImageIndex = 0;
     _sType = SecurityType.Integrated;
     _connected = false;
 }
 private SubscriptionDataConfig CreateTradeBarDataConfig(SecurityType type)
 {
     if (type == SecurityType.Equity)
         return new SubscriptionDataConfig(typeof(TradeBar), Symbols.USDJPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, true);
     if (type == SecurityType.Forex)
         return new SubscriptionDataConfig(typeof(TradeBar), Symbols.USDJPY, Resolution.Minute, TimeZones.EasternStandard, TimeZones.EasternStandard, true, true, true);
     throw new NotImplementedException(type.ToString());
 }
Exemple #12
0
 /// <summary>
 /// clone a security
 /// </summary>
 /// <param name="copy"></param>
 public SecurityImpl(Security copy)
 {
     _sym = copy.Symbol;
     _strike = copy.Strike;
     _type = copy.Type;
     _destex = copy.DestEx;
     _date = copy.Date;
     _details = copy.Details;
 }
Exemple #13
0
        private static Symbol ConvertSymbol(string instrument, SecurityType securityType)
        {
            if (securityType == SecurityType.Forex)
            {
                return new Symbol(SecurityIdentifier.GenerateForex(instrument, Market.Oanda), instrument);
            }

            throw new NotImplementedException("The specfied security type has not been implemented yet: " + securityType);
        }
 /// <summary>
 /// Initialzies a new instance of the <see cref="SymbolSecurityType"/> class
 /// </summary>
 /// <param name="symbol">The symbol of the security</param>
 /// <param name="securityType">The security type of the security</param>
 public SymbolSecurityType(string symbol, SecurityType securityType)
 {
     if (symbol == null)
     {
         throw new ArgumentNullException("symbol");
     }
     Symbol = symbol;
     SecurityType = securityType;
 }
        public readonly Symbol Symbol; // for options this is a 'canonical' symbol using info derived from the path

        /// <summary>
        /// Initializes a new instance of the <see cref="LeanDataPathComponents"/> class
        /// </summary>
        public LeanDataPathComponents(SecurityType securityType, string market, Resolution resolution, Symbol symbol, string filename, DateTime date)
        {
            Date = date;
            SecurityType = securityType;
            Market = market;
            Resolution = resolution;
            Filename = filename;
            Symbol = symbol;
        }
Exemple #16
0
        /// <summary>
        /// Full Constructor
        /// </summary>
        /// <param name="clientId">Filter the results of the ReqExecutions() method based on the clientId.</param>
        /// <param name="acctCode">Filter the results of the ReqExecutions() method based on an account code.</param>
        /// <param name="time">Filter the results of the ReqExecutions() method based on execution reports received after the specified time.</param>
        /// <param name="symbol">Filter the results of the ReqExecutions() method based on the order symbol.</param>
        /// <param name="securityType">Refer to the Contract struct for the list of valid security types.</param>
        /// <param name="exchange">Filter the results of the ReqExecutions() method based on the order exchange.</param>
        /// <param name="side">Filter the results of the ReqExecutions() method based on the order action.</param>
        public KrsExecutionFilter(int clientId, String acctCode, DateTime time, String symbol, SecurityType securityType,
            String exchange, ActionSide side)
        {
            DateTime = time;
            SecurityType = securityType;
            ActionSide = side;

            Convert();
        }
 public ProformaSubmitOrderRequest(OrderType orderType, SecurityType securityType, string symbol, int quantity, decimal stopPrice, decimal limitPrice, DateTime time, string tag) : base(orderType, securityType, symbol, quantity, stopPrice, limitPrice, time, tag)
 {
     SecurityType = securityType;
     Symbol = symbol.ToUpper();
     OrderType = orderType;
     Quantity = quantity;
     LimitPrice = limitPrice;
     StopPrice = stopPrice;
 }
Exemple #18
0
 /// <summary>
 /// Add Market Data Required (Overloaded method for backwards compatibility).
 /// </summary>
 /// <param name="security">Market Data Asset</param>
 /// <param name="symbol">Symbol of the asset we're like</param>
 /// <param name="resolution">Resolution of Asset Required</param>
 /// <param name="fillDataForward">when there is no data pass the last tradebar forward</param>
 /// <param name="extendedMarketHours">Request premarket data as well when true </param>
 public SubscriptionDataConfig Add(SecurityType security, string symbol, Resolution resolution = Resolution.Minute, bool fillDataForward = true, bool extendedMarketHours = false)
 {
     //Set the type: market data only comes in two forms -- ticks(trade by trade) or tradebar(time summaries)
     var dataType = typeof(TradeBar);
     if (resolution == Resolution.Tick)
     {
         dataType = typeof(Tick);
     }
     return Add(dataType, security, symbol, resolution, fillDataForward, extendedMarketHours, true, true);
 }
        /// <summary>
        /// Converts an InteractiveBrokers symbol to a Lean symbol instance
        /// </summary>
        /// <param name="brokerageSymbol">The InteractiveBrokers symbol</param>
        /// <param name="securityType">The security type</param>
        /// <param name="market">The market</param>
        /// <returns>A new Lean Symbol instance</returns>
        public Symbol GetLeanSymbol(string brokerageSymbol, SecurityType securityType, string market)
        {
            if (string.IsNullOrWhiteSpace(brokerageSymbol))
                throw new ArgumentException("Invalid symbol: " + brokerageSymbol);

            if (securityType != SecurityType.Forex && securityType != SecurityType.Equity)
                throw new ArgumentException("Invalid security type: " + securityType);

            return Symbol.Create(brokerageSymbol, securityType, market);
        }
Exemple #20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SubmitOrderRequest"/> class.
 /// The <see cref="OrderRequest.OrderId"/> will default to <see cref="OrderResponseErrorCode.UnableToFindOrder"/>
 /// </summary>
 /// <param name="orderType">The order type to be submitted</param>
 /// <param name="securityType">The symbol's <see cref="SecurityType"/></param>
 /// <param name="symbol">The symbol to be traded</param>
 /// <param name="quantity">The number of units to be ordered</param>
 /// <param name="stopPrice">The stop price for stop orders, non-stop orers this value is ignored</param>
 /// <param name="limitPrice">The limit price for limit orders, non-limit orders this value is ignored</param>
 /// <param name="time">The time this request was created</param>
 /// <param name="tag">A custom tag for this request</param>
 public SubmitOrderRequest(OrderType orderType, SecurityType securityType, string symbol, int quantity, decimal stopPrice, decimal limitPrice, DateTime time, string tag)
     : base(time, (int) OrderResponseErrorCode.UnableToFindOrder, tag)
 {
     SecurityType = securityType;
     Symbol = symbol.ToUpper();
     OrderType = orderType;
     Quantity = quantity;
     LimitPrice = limitPrice;
     StopPrice = stopPrice;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerTreeNode"/> class.
 /// </summary>
 /// <param name="servername">The servername.</param>
 public ServerTreeNode(string servername)
 {
     this.Name = servername;
     this.Text = servername;
     this.ImageIndex = 0;
     this.SelectedImageIndex = 0;
     _sType = SecurityType.Integrated;
     _connected = false;
     _savePWD = false;
 }
Exemple #22
0
        /// <summary>
        /// Create a new holding class instance setting the initial properties to $0.
        /// </summary>
        public SecurityHolding(string symbol, SecurityType type, ISecurityTransactionModel transactionModel)
        {
            _model = transactionModel;
            _symbol = symbol;
            _securityType = type;

            //Total Sales Volume for the day
            _totalSaleVolume = 0;
            _lastTradeProfit = 0;
        }
 /******************************************************** 
 * CLASS CONSTRUCTOR
 *********************************************************/
 /// <summary>
 /// Constructor for Data Subscriptions
 /// </summary>
 /// <param name="objectType">Type of the data objects.</param>
 /// <param name="securityType">SecurityType Enum Set Equity/FOREX/Futures etc.</param>
 /// <param name="symbol">Symbol of the asset we're requesting</param>
 /// <param name="resolution">Resolution of the asset we're requesting</param>
 /// <param name="fillForward">Fill in gaps with historical data</param>
 /// <param name="extendedHours">Equities only - send in data from 4am - 8pm</param>
 public SubscriptionDataConfig(Type objectType, SecurityType securityType = SecurityType.Equity, string symbol = "", Resolution resolution = Resolution.Minute, bool fillForward = true, bool extendedHours = false)
 {
     this.Type = objectType;
     this.Security = securityType;
     this.Resolution = resolution;
     this.Symbol = symbol;
     this.FillDataForward = fillForward;
     this.ExtendedMarketHours = extendedHours;
     this.PriceScaleFactor = 1;
     this.MappedSymbol = symbol;
 }
Exemple #24
0
        /// <summary>
        /// New Stop Market Order constructor - 
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="type">Type of the security order</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
        /// <param name="time">Time the order was placed</param>
        /// <param name="stopPrice">Price the order should be filled at if a limit order</param>
        /// <param name="tag">User defined data tag for this order</param>
        public StopMarketOrder(string symbol, int quantity, decimal stopPrice, DateTime time, string tag = "", SecurityType type = SecurityType.Base)
            : base(symbol, quantity, OrderType.StopMarket, time, 0, tag, type)
        {
            StopPrice = stopPrice;

            if (tag == "")
            {
                //Default tag values to display stop price in GUI.
                Tag = "Stop Price: " + stopPrice.ToString("C");
            }
        }
Exemple #25
0
        /// <summary>
        /// New limit order constructor
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="type">Type of the security order</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
        /// <param name="time">Time the order was placed</param>
        /// <param name="limitPrice">Price the order should be filled at if a limit order</param>
        /// <param name="tag">User defined data tag for this order</param>
        public LimitOrder(string symbol, int quantity, decimal limitPrice, DateTime time, string tag = "", SecurityType type = SecurityType.Base)
            : base(symbol, quantity, OrderType.Limit, time, 0, tag, type)
        {
            LimitPrice = limitPrice;

            if (tag == "")
            {
                //Default tag values to display limit price in GUI.
                Tag = "Limit Price: " + limitPrice.ToString("C");
            }
        }
 /// <summary>
 /// Full Constructor
 /// </summary>
 /// <param name="clientId">Filter the results of the ReqExecutions() method based on the clientId.</param>
 /// <param name="acctCode">Filter the results of the ReqExecutions() method based on an account code.</param>
 /// <param name="time">Filter the results of the ReqExecutions() method based on execution reports received after the specified time.</param>
 /// <param name="symbol">Filter the results of the ReqExecutions() method based on the order symbol.</param>
 /// <param name="securityType">Refer to the Contract struct for the list of valid security types.</param>
 /// <param name="exchange">Filter the results of the ReqExecutions() method based on the order exchange.</param>
 /// <param name="side">Filter the results of the ReqExecutions() method based on the order action.</param>
 public ExecutionFilter(int clientId, String acctCode, DateTime time, String symbol, SecurityType securityType,
                        String exchange, ActionSide side)
 {
     this.clientId = clientId;
     this.acctCode = acctCode;
     this.time = time;
     this.symbol = symbol;
     this.securityType = securityType;
     this.exchange = exchange;
     this.side = side;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerTreeNode"/> class.
 /// </summary>
 /// <param name="servername">The servername.</param>
 /// <param name="UID">The UID.</param>
 /// <param name="PWD">The PWD.</param>
 public ServerTreeNode(string servername, string UID, string PWD, bool savePWD)
 {
     this.Name = servername;
     this.Text = servername;
     this.ImageIndex = 0;
     this.SelectedImageIndex = 0;
     _uID = UID;
     _pwd = PWD;
     _sType = SecurityType.Mixed;
     _connected = false;
     _savePWD = savePWD;
 }
Exemple #28
0
 /// <summary>
 /// Creates the entry name for a QC zip data file
 /// </summary>
 public static string CreateZipEntryName(string symbol, SecurityType securityType, DateTime date, Resolution resolution)
 {
     if (resolution == Resolution.Hour || resolution == Resolution.Daily)
     {
         return symbol + ".csv";
     }
     if (securityType == SecurityType.Forex)
     {
         return String.Format("{0}_{1}_{2}_quote.csv", date.ToString(DateFormat.EightCharacter), symbol.ToLower(), resolution.ToString().ToLower());
     }
     return String.Format("{0}_{1}_{2}_trade.csv", date.ToString(DateFormat.EightCharacter), symbol.ToLower(), resolution.ToString().ToLower());
 }
        /// <summary>
        /// New Stop Market Order constructor - 
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="type">Type of the security order</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
        /// <param name="limitPrice">Maximum price to fill the order</param>
        /// <param name="time">Time the order was placed</param>
        /// <param name="stopPrice">Price the order should be filled at if a limit order</param>
        /// <param name="tag">User defined data tag for this order</param>
        public StopLimitOrder(Symbol symbol, int quantity, decimal stopPrice, decimal limitPrice, DateTime time, string tag = "", SecurityType type = SecurityType.Base)
            : base(symbol, quantity, time, tag, type)
        {
            StopPrice = stopPrice;
            LimitPrice = limitPrice;

            if (tag == "")
            {
                //Default tag values to display stop price in GUI.
                Tag = "Stop Price: " + stopPrice.ToString("C") + " Limit Price: " + limitPrice.ToString("C");
            }
        }
Exemple #30
0
 /// <summary>
 /// New order constructor
 /// </summary>
 /// <param name="symbol">Symbol asset we're seeking to trade</param>
 /// <param name="type"></param>
 /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
 /// <param name="time">Time the order was placed</param>
 /// <param name="tag">User defined data tag for this order</param>
 protected Order(Symbol symbol, SecurityType type, int quantity, DateTime time, string tag = "")
 {
     Time = time;
     Price = 0;
     Quantity = quantity;
     Symbol = symbol;
     Status = OrderStatus.None;
     Tag = tag;
     SecurityType = type;
     Duration = OrderDuration.GTC;
     BrokerId = new List<long>();
     ContingentId = 0;
 }
 public StopMarketOrderTestParameters(string symbol, SecurityType securityType, decimal highLimit, decimal lowLimit)
     : base(symbol, securityType)
 {
     _highLimit = highLimit;
     _lowLimit  = lowLimit;
 }
Exemple #32
0
        /// <summary>
        /// Parses the contents as a FactorFile, if error returns a new empty factor file
        /// </summary>
        public static IFactorProvider SafeRead(string permtick, IEnumerable <string> contents, SecurityType securityType)
        {
            try
            {
                DateTime?minimumDate;

                contents = contents.Distinct();

                if (securityType == SecurityType.Future)
                {
                    return(new MappingContractFactorProvider(permtick, MappingContractFactorRow.Parse(contents, out minimumDate), minimumDate));
                }
                // FactorFileRow.Parse handles entries with 'inf' and exponential notation and provides the associated minimum tradeable date for these cases
                // previously these cases were not handled causing an exception and returning an empty factor file
                return(new CorporateFactorProvider(permtick, CorporateFactorRow.Parse(contents, out minimumDate), minimumDate));
            }
            catch (Exception e)
            {
                if (securityType == SecurityType.Future)
                {
                    return(new MappingContractFactorProvider(permtick, Enumerable.Empty <MappingContractFactorRow>()));
                }
                return(new CorporateFactorProvider(permtick, Enumerable.Empty <CorporateFactorRow>()));
            }
        }
Exemple #33
0
 /// <summary>
 /// Tries to get the entry for the specified market/symbol/security-type
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="entry">The entry found if any</param>
 /// <returns>True if the entry was present, else false</returns>
 public bool TryGetEntry(string market, Symbol symbol, SecurityType securityType, out Entry entry)
 {
     return(TryGetEntry(market, GetDatabaseSymbolKey(symbol), securityType, out entry));
 }
Exemple #34
0
 /// <summary>
 /// Generates a new <see cref="SecurityIdentifier"/> for a <see cref="ConstituentsUniverseData"/>.
 /// Note that the symbol ticker is case sensitive here.
 /// </summary>
 /// <param name="symbol">The ticker to use for this constituent identifier</param>
 /// <param name="securityType">The security type of this constituent universe</param>
 /// <param name="market">The security's market</param>
 /// <remarks>This method is special in the sense that it does not force the Symbol to be upper
 /// which is required to determine the source file of the constituent
 /// <see cref="ConstituentsUniverseData.GetSource(Data.SubscriptionDataConfig,DateTime,bool)"/></remarks>
 /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified constituent universe</returns>
 public static SecurityIdentifier GenerateConstituentIdentifier(string symbol, SecurityType securityType, string market)
 {
     return(Generate(DefaultDate, symbol, securityType, market, forceSymbolToUpper: false));
 }
 /// <summary>
 /// Get the available data types for a security
 /// </summary>
 public IReadOnlyList <TickType> GetDataTypesForSecurity(SecurityType securityType)
 {
     return(AvailableDataTypes[securityType]);
 }
        /// <summary>
        /// Creates a new user defined universe that will fire on the requested resolution during market hours.
        /// </summary>
        /// <param name="securityType">The security type of the universe</param>
        /// <param name="name">A unique name for this universe</param>
        /// <param name="resolution">The resolution this universe should be triggered on</param>
        /// <param name="market">The market of the universe</param>
        /// <param name="universeSettings">The subscription settings used for securities added from this universe</param>
        /// <param name="pySelector">Function delegate that accepts a DateTime and returns a collection of string symbols</param>
        public void AddUniverse(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, PyObject pySelector)
        {
            var selector = PythonUtil.ToFunc <DateTime, object[]>(pySelector);

            AddUniverse(securityType, name, resolution, market, universeSettings, d => selector(d).Select(x => (string)x));
        }
Exemple #37
0
        /// <summary>
        /// Set IP security to configure IIS to restrict client access
        /// based on IP addresses or DNS host names. Configuring IP
        /// security modifies the IPSecurity metabase property.
        /// </summary>
        /// <param name="iisHostPath">The iis host path.</param>
        /// <param name="securityType">The security type to set.</param>
        /// <param name="item">The item value to use to set the security value.</param>
        /// <returns>True if the security was set else false.</returns>
        /// <example>
        /// iisHostPath : [servername]/[service]/[websiteID] : localhost/W3SVC/1
        /// iisHostPath : [servername]/[service] : localhost/W3SVC
        /// iisHostPath : [servername]/[service]/[smtpID] : localhost/SMTPSVC/1
        /// iisHostPath : [servername]/[service] : localhost/SMTPSVC
        /// </example>
        /// <remarks>
        /// <para>iisHostPath : [servername]/[service]/[websiteID] : localhost/W3SVC/1</para>
        /// <para>iisHostPath : [servername]/[service] : localhost/W3SVC</para>
        /// <para>iisHostPath : [servername]/[service]/[smtpID] : localhost/SMTPSVC/1</para>
        /// <para>iisHostPath : [servername]/[service] : localhost/SMTPSVC</para>
        /// </remarks>
        public virtual bool SetSecurity(string iisHostPath,
                                        SecurityType securityType, string item)
        {
            // Validate the inputs.
            if (String.IsNullOrEmpty(iisHostPath))
            {
                throw new System.ArgumentNullException("IIS path can not be null.",
                                                       new System.Exception("A valid IIS path should be specified."));
            }

            // Validate the inputs.
            if (String.IsNullOrEmpty(item))
            {
                throw new System.ArgumentNullException("Item can not be null.",
                                                       new System.Exception("A valid itemshould be specified."));
            }

            // Create a new directory entry
            // instance to the iis machine.
            DirectoryEntry localMachine = new DirectoryEntry(
                "IIS://" + iisHostPath);

            // Loads the data into the cache.
            localMachine.RefreshCache();

            // Get the IPSecurity object, this object is a type
            // that contains fields, properties and methods.
            object ipSecurity = localMachine.Invoke("Get", new string[] { "IPSecurity" });

            // Get the IPSecurity type.
            Type type = ipSecurity.GetType();

            // Invoke the IPSecurity member, in this case the
            // member is a property with the securityType name.
            // Get this property in the IPSecurity object, in this
            // case the property is an array of data.
            Array data = (Array)type.InvokeMember(securityType.ToString(),
                                                  BindingFlags.GetProperty, null, ipSecurity, null);

            // Search for the item in the array of data
            // indicate if the item already exists.
            bool exists = false;

            foreach (object dataItem in data)
            {
                if (dataItem.ToString().StartsWith(item))
                {
                    exists = true;
                }
            }

            // If the item already exists.
            if (exists)
            {
                // Throw a new exception indicating that
                // the item already exists.
                throw new System.Exception(item + " already exists in " + securityType.ToString());
            }
            else
            {
                // Create a new object array this array will
                // contain all the current data from the member
                // and one more.
                object[] newData = new object[data.Length + 1];

                // Copy the current member data to the new
                // data member object.
                data.CopyTo(newData, 0);

                // Set the last item in the new array
                // with the new value.
                newData.SetValue(item, data.Length);

                // Invoke the IPSecurity member, in this case the
                // member is a property with the securityType name.
                // Set this property in the IPSecurity object with the new data.
                type.InvokeMember(securityType.ToString(),
                                  BindingFlags.SetProperty, null, ipSecurity, new object[] { newData });

                // Invoke the IP Security property, put
                // the new data set in the IPSecurity object
                // to the current iis host path.
                localMachine.Invoke("Put", new object[] { "IPSecurity", ipSecurity });

                // Commit the changes for the account.
                localMachine.CommitChanges();
            }

            // Close the connections.
            localMachine.Close();

            // Return success.
            return(true);
        }
 /// <summary>
 /// Returns whether the time can be advanced or not.
 /// </summary>
 /// <param name="securityType">The security type</param>
 /// <returns>true if the time can be advanced</returns>
 public bool CanAdvanceTime(SecurityType securityType)
 {
     return(true);
 }
Exemple #39
0
 /// <summary>
 /// Generates the full zip file path rooted in the <paramref name="dataDirectory"/>
 /// </summary>
 public static string GenerateZipFilePath(string dataDirectory, string symbol, SecurityType securityType, string market, DateTime date, Resolution resolution)
 {
     return(Path.Combine(dataDirectory, GenerateRelativeZipFilePath(symbol, securityType, market, date, resolution)));
 }
Exemple #40
0
        private static Symbol CreateSymbol(IReadOnlyDictionary <SecurityType, string> marketMap, string crypto, Dictionary <SecurityType, string> markets, SecurityType securityType)
        {
            string market;

            if (!markets.TryGetValue(securityType, out market))
            {
                market = marketMap[securityType];
            }

            return(QuantConnect.Symbol.Create(crypto, securityType, market));
        }
Exemple #41
0
 /// <summary>
 /// Creates a new universe and adds it to the algorithm. This will use the default universe settings
 /// specified via the <see cref="UniverseSettings"/> property.
 /// </summary>
 /// <typeparam name="T">The data type</typeparam>
 /// <param name="securityType">The security type the universe produces</param>
 /// <param name="name">A unique name for this universe</param>
 /// <param name="resolution">The epected resolution of the universe data</param>
 /// <param name="market">The market for selected symbols</param>
 /// <param name="selector">Function delegate that performs selection on the universe data</param>
 public void AddUniverse <T>(SecurityType securityType, string name, Resolution resolution, string market, Func <IEnumerable <T>, IEnumerable <string> > selector)
 {
     AddUniverse(securityType, name, resolution, market, UniverseSettings, selector);
 }
Exemple #42
0
 private static decimal GetScaleFactor(SecurityType securityType)
 {
     return(securityType == SecurityType.Equity || securityType == SecurityType.Option ? 10000m : 1);
 }
Exemple #43
0
 /// <summary>
 /// Gets the current market price of the specified security
 /// </summary>
 protected override decimal GetAskPrice(string symbol, SecurityType securityType)
 {
     // not used, we use bid/ask prices
     return(0);
 }
Exemple #44
0
 public void T04_StringCase()
 {
     SecurityType.SetStringComparer(StringComparer.OrdinalIgnoreCase);
     Assert.Equal(SecurityType.Stock, SecurityType.ToStringEnum("stk"));
 }
Exemple #45
0
 public ClassMethod(string name, string desc, DataType returnType, SecurityType sectype, bool isstatic)
     : base(name, desc, returnType, sectype, isstatic)
 {
 }
        /// <summary>
        /// Check whether symbol properties exists for the specified market/symbol/security-type
        /// </summary>
        /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
        /// <param name="symbol">The particular symbol being traded</param>
        /// <param name="securityType">The security type of the symbol</param>
        public bool ContainsKey(string market, string symbol, SecurityType securityType)
        {
            var key = new SecurityDatabaseKey(market, symbol, securityType);

            return(_entries.ContainsKey(key));
        }
 /// <summary>
 /// Creates a new universe and adds it to the algorithm
 /// </summary>
 /// <param name="T">The data type</param>
 /// <param name="securityType">The security type the universe produces</param>
 /// <param name="name">A unique name for this universe</param>
 /// <param name="resolution">The epected resolution of the universe data</param>
 /// <param name="market">The market for selected symbols</param>
 /// <param name="universeSettings">The subscription settings to use for newly created subscriptions</param>
 /// <param name="selector">Function delegate that performs selection on the universe data</param>
 public void AddUniverse(PyObject T, SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, PyObject selector)
 {
     AddUniverse(CreateType(T), securityType, name, resolution, market, universeSettings, selector);
 }
 /// <summary>
 /// Converts IQFeed ticker to a Lean symbol instance
 /// </summary>
 /// <param name="ticker">IQFeed ticker</param>
 /// <param name="securityType">The security type</param>
 /// <param name="market">The market</param>
 /// <param name="expirationDate">Expiration date of the security(if applicable)</param>
 /// <param name="strike">The strike of the security (if applicable)</param>
 /// <param name="optionRight">The option right of the security (if applicable)</param>
 /// <returns>A new Lean Symbol instance</returns>
 public Symbol GetLeanSymbol(string ticker, SecurityType securityType, string market, DateTime expirationDate = default(DateTime), decimal strike = 0, OptionRight optionRight = 0)
 {
     return(_tickers.ContainsKey(ticker) ? _tickers[ticker] : Symbol.Empty);
 }
Exemple #49
0
 /// <summary>
 /// Convenience method for the common custom data case.
 /// Sets the entry for the specified symbol using SecurityExchangeHours.AlwaysOpen(timeZone)
 /// This sets the data time zone equal to the exchange time zone as well.
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="timeZone">The time zone of the symbol's exchange and raw data</param>
 /// <returns>The entry matching the specified market/symbol/security-type</returns>
 public virtual Entry SetEntryAlwaysOpen(string market, string symbol, SecurityType securityType, DateTimeZone timeZone)
 {
     return(SetEntry(market, symbol, securityType, SecurityExchangeHours.AlwaysOpen(timeZone)));
 }
Exemple #50
0
 public void SymbolCreate(string ticker, SecurityType securityType, string market, Symbol expected)
 {
     Assert.AreEqual(Symbol.Create(ticker, securityType, market), expected);
 }
Exemple #51
0
        /// <summary>
        /// Generic generate method. This method should be used carefully as some parameters are not required and
        /// some parameters mean different things for different security types
        /// </summary>
        private static SecurityIdentifier Generate(DateTime date,
                                                   string symbol,
                                                   SecurityType securityType,
                                                   string market,
                                                   decimal strike                = 0,
                                                   OptionRight optionRight       = 0,
                                                   OptionStyle optionStyle       = 0,
                                                   SecurityIdentifier underlying = null,
                                                   bool forceSymbolToUpper       = true)
        {
            if ((ulong)securityType >= SecurityTypeWidth || securityType < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(securityType), "securityType must be between 0 and 99");
            }
            if ((int)optionRight > 1 || optionRight < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(optionRight), "optionType must be either 0 or 1");
            }

            // normalize input strings
            market = market.ToLowerInvariant();
            symbol = forceSymbolToUpper ? symbol.LazyToUpper() : symbol;

            var marketIdentifier = QuantConnect.Market.Encode(market);

            if (!marketIdentifier.HasValue)
            {
                throw new ArgumentOutOfRangeException(nameof(market), "The specified market wasn't found in the  markets lookup. " +
                                                      $"Requested: {market}. You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)"
                                                      );
            }

            var days       = (ulong)date.ToOADate() * DaysOffset;
            var marketCode = (ulong)marketIdentifier * MarketOffset;

            ulong strikeScale;
            var   strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset;

            strikeScale *= StrikeScaleOffset;
            var style   = (ulong)optionStyle * OptionStyleOffset;
            var putcall = (ulong)optionRight * PutCallOffset;

            var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType;

            var result = new SecurityIdentifier(symbol, otherData, underlying ?? Empty);

            // we already have these so lets set them
            switch (securityType)
            {
            case SecurityType.Base:
            case SecurityType.Equity:
            case SecurityType.Future:
                result._date = date;
                break;

            case SecurityType.Option:
                result._date        = date;
                result._strikePrice = strike;
                result._optionRight = optionRight;
                result._optionStyle = optionStyle;
                break;
            }
            return(result);
        }
Exemple #52
0
        /// <summary>
        /// Performs a lookup using the specified information and returns the data's time zone if found,
        /// if an entry is not found, an exception is thrown
        /// </summary>
        /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
        /// <param name="symbol">The particular symbol being traded</param>
        /// <param name="securityType">The security type of the symbol</param>
        /// <returns>The raw data time zone for the specified security</returns>
        public DateTimeZone GetDataTimeZone(string market, Symbol symbol, SecurityType securityType)
        {
            var stringSymbol = symbol == null ? string.Empty : symbol.Value;

            return(GetEntry(market, stringSymbol, securityType).DataTimeZone);
        }
Exemple #53
0
        public void NonUsdAccountCurrencyCurrencyDataFeedsGetAdded(string accountCurrency,
                                                                   string quoteCurrency,
                                                                   string baseCurrency,
                                                                   string quoteCurrencySymbol,
                                                                   string baseCurrencySymbol,
                                                                   SecurityType securityType,
                                                                   string market)
        {
            var quoteCash = new Cash(quoteCurrency, 100, 1);
            var baseCash  = new Cash(baseCurrency, 100, 1);
            var cashBook  = new CashBook {
                { quoteCurrency, quoteCash },
                { baseCurrency, baseCash }
            };

            var symbol = Symbol.Create(baseCurrency + quoteCurrency,
                                       securityType,
                                       market);
            var subscriptions = new SubscriptionManager();
            var dataManager   = new DataManagerStub(TimeKeeper);

            subscriptions.SetDataManager(dataManager);
            var securities = new SecurityManager(TimeKeeper)
            {
                {
                    symbol, new Security(
                        SecurityExchangeHours,
                        subscriptions.Add(symbol, Resolution.Minute, TimeZone, TimeZone),
                        new Cash(cashBook.AccountCurrency, 0, 1m),
                        SymbolProperties.GetDefault(cashBook.AccountCurrency),
                        ErrorCurrencyConverter.Instance,
                        RegisteredSecurityDataTypesProvider.Null,
                        new SecurityCache()
                        )
                }
            };

            var configs1 = quoteCash.EnsureCurrencyDataFeed(securities,
                                                            subscriptions,
                                                            MarketMap,
                                                            SecurityChanges.None,
                                                            dataManager.SecurityService,
                                                            accountCurrency);

            Assert.AreEqual(1, configs1.Count);

            var config1 = configs1[0];

            Assert.IsNotNull(config1);
            Assert.AreEqual(quoteCurrencySymbol, config1.Symbol.Value);

            var configs2 = baseCash.EnsureCurrencyDataFeed(securities,
                                                           subscriptions,
                                                           MarketMap,
                                                           SecurityChanges.None,
                                                           dataManager.SecurityService,
                                                           accountCurrency);

            Assert.AreEqual(1, configs2.Count);

            var config2 = configs2[0];

            Assert.IsNotNull(config2);
            Assert.AreEqual(baseCurrencySymbol, config2.Symbol.Value);
        }
Exemple #54
0
 public static string GetPrimaryExchangeCodeGetPrimaryExchange(this string exchange,
                                                               SecurityType securityType = SecurityType.Equity,
                                                               string market             = Market.USA)
 {
     return(exchange.GetPrimaryExchange(securityType, market).Code);
 }
Exemple #55
0
        public static Exchange GetPrimaryExchange(this string exchange,
                                                  SecurityType securityType = SecurityType.Equity,
                                                  string market             = Market.USA)
        {
            var primaryExchange = Exchange.UNKNOWN;

            if (string.IsNullOrEmpty(exchange))
            {
                return(primaryExchange);
            }

            if (securityType == SecurityType.Equity)
            {
                switch (exchange.LazyToUpper())
                {
                case "T":
                case "Q":
                case "NASDAQ":
                case "NASDAQ_OMX":
                    return(Exchange.NASDAQ);

                case "Z":
                case "BATS":
                case "BATS Z":
                case "BATS_Z":
                    return(Exchange.BATS);

                case "P":
                case "ARCA":
                    return(Exchange.ARCA);

                case "N":
                case "NYSE":
                    return(Exchange.NYSE);

                case "C":
                case "NSX":
                case "NSE":
                    if (market == Market.USA)
                    {
                        return(Exchange.NSX);
                    }
                    else if (market == Market.India)
                    {
                        return(Exchange.NSE);
                    }
                    return(Exchange.UNKNOWN);

                case "D":
                case "FINRA":
                    return(Exchange.FINRA);

                case "I":
                case "ISE":
                    return(Exchange.ISE);

                case "M":
                case "CSE":
                    return(Exchange.CSE);

                case "W":
                case "CBOE":
                    return(Exchange.CBOE);

                case "A":
                case "AMEX":
                    return(Exchange.AMEX);

                case "SIAC":
                    return(Exchange.SIAC);

                case "J":
                case "EDGA":
                    return(Exchange.EDGA);

                case "K":
                case "EDGX":
                    return(Exchange.EDGX);

                case "B":
                case "NASDAQ BX":
                case "NASDAQ_BX":
                    return(Exchange.NASDAQ_BX);

                case "X":
                case "NASDAQ PSX":
                case "NASDAQ_PSX":
                    return(Exchange.NASDAQ_PSX);

                case "Y":
                case "BATS Y":
                case "BATS_Y":
                    return(Exchange.BATS_Y);

                case "BOSTON":
                    return(Exchange.BOSTON);

                case "BSE":
                    return(Exchange.BSE);
                }
            }
            else if (securityType == SecurityType.Option)
            {
                switch (exchange.LazyToUpper())
                {
                case "A":
                case "AMEX":
                    return(Exchange.AMEX_Options);

                case "MIAX":
                    return(Exchange.MIAX);

                case "I":
                case "ISE":
                    return(Exchange.ISE);

                case "H":
                case "ISE GEMINI":
                case "ISE_GEMINI":
                    return(Exchange.ISE_GEMINI);

                case "J":
                case "ISE MERCURY":
                case "ISE_MERCURY":
                    return(Exchange.ISE_MERCURY);

                case "O":
                case "OPRA":
                    return(Exchange.OPRA);

                case "W":
                case "C2":
                    return(Exchange.C2);

                default:
                    return(Exchange.UNKNOWN);
                }
            }
            else if (securityType == SecurityType.Future || securityType == SecurityType.FutureOption)
            {
                switch (exchange.LazyToUpper())
                {
                case "CME":
                    return(Exchange.CME);

                case "CBOT":
                    return(Exchange.CBOT);

                case "NYMEX":
                    return(Exchange.NYMEX);

                case "ICE":
                    return(Exchange.ICE);

                case "CFE":
                    return(Exchange.CFE);

                case "COMEX":
                    return(Exchange.COMEX);

                default:
                    return(Exchange.UNKNOWN);
                }
            }
            return(Exchange.UNKNOWN);
        }
Exemple #56
0
 /// <summary>
 /// Gets the entry for the specified market/symbol/security-type
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded (Symbol class)</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <returns>The entry matching the specified market/symbol/security-type</returns>
 public virtual Entry GetEntry(string market, Symbol symbol, SecurityType securityType)
 {
     return(GetEntry(market, GetDatabaseSymbolKey(symbol), securityType));
 }
Exemple #57
0
 /// <summary>
 /// Tries to get the entry for the specified market/symbol/security-type
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <param name="entry">The entry found if any</param>
 /// <returns>True if the entry was present, else false</returns>
 public bool TryGetEntry(string market, string symbol, SecurityType securityType, out Entry entry)
 {
     return(_entries.TryGetValue(new SecurityDatabaseKey(market, symbol, securityType), out entry)
            // now check with null symbol key
            || _entries.TryGetValue(new SecurityDatabaseKey(market, null, securityType), out entry));
 }
Exemple #58
0
 /// <summary>
 /// Convenience method for retrieving exchange hours from market hours database using a subscription config
 /// </summary>
 /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
 /// <param name="symbol">The particular symbol being traded</param>
 /// <param name="securityType">The security type of the symbol</param>
 /// <returns>The exchange hours for the specified security</returns>
 public SecurityExchangeHours GetExchangeHours(string market, Symbol symbol, SecurityType securityType)
 {
     return(GetEntry(market, symbol, securityType).ExchangeHours);
 }
Exemple #59
0
        /// <summary>
        /// Converts the specified base data instance into a lean data file csv line
        /// </summary>
        public static string GenerateLine(IBaseData data, SecurityType securityType, Resolution resolution)
        {
            var milliseconds = data.Time.TimeOfDay.TotalMilliseconds.ToString(CultureInfo.InvariantCulture);
            var longTime     = data.Time.ToStringInvariant(DateFormat.TwelveCharacter);

            switch (securityType)
            {
            case SecurityType.Equity:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = (Tick)data;
                    if (tick.TickType == TickType.Trade)
                    {
                        return(ToCsv(milliseconds, Scale(tick.LastPrice), tick.Quantity, tick.Exchange, tick.SaleCondition, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.Quote)
                    {
                        return(ToCsv(milliseconds, Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.Exchange, tick.SaleCondition, tick.Suspicious ? "1" : "0"));
                    }
                    break;

                case Resolution.Minute:
                case Resolution.Second:
                    var tradeBar = data as TradeBar;
                    if (tradeBar != null)
                    {
                        return(ToCsv(milliseconds, Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume));
                    }
                    var quoteBar = data as QuoteBar;
                    if (quoteBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
                                     ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize));
                    }
                    break;

                case Resolution.Hour:
                case Resolution.Daily:
                    var bigTradeBar = data as TradeBar;
                    if (bigTradeBar != null)
                    {
                        return(ToCsv(longTime, Scale(bigTradeBar.Open), Scale(bigTradeBar.High), Scale(bigTradeBar.Low), Scale(bigTradeBar.Close), bigTradeBar.Volume));
                    }
                    var bigQuoteBar = data as QuoteBar;
                    if (bigQuoteBar != null)
                    {
                        return(ToCsv(longTime,
                                     ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
                                     ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize));
                    }
                    break;
                }
                break;

            case SecurityType.Crypto:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = data as Tick;
                    if (tick == null)
                    {
                        throw new ArgumentException("Cryto tick could not be created", nameof(data));
                    }
                    if (tick.TickType == TickType.Trade)
                    {
                        return(ToCsv(milliseconds, tick.LastPrice, tick.Quantity));
                    }
                    if (tick.TickType == TickType.Quote)
                    {
                        return(ToCsv(milliseconds, tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize));
                    }
                    throw new ArgumentException("Cryto tick could not be created");

                case Resolution.Second:
                case Resolution.Minute:
                    var quoteBar = data as QuoteBar;
                    if (quoteBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
                                     ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize));
                    }
                    var tradeBar = data as TradeBar;
                    if (tradeBar != null)
                    {
                        return(ToCsv(milliseconds, tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume));
                    }
                    throw new ArgumentException("Cryto minute/second bar could not be created", nameof(data));

                case Resolution.Hour:
                case Resolution.Daily:
                    var bigQuoteBar = data as QuoteBar;
                    if (bigQuoteBar != null)
                    {
                        return(ToCsv(longTime,
                                     ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
                                     ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize));
                    }
                    var bigTradeBar = data as TradeBar;
                    if (bigTradeBar != null)
                    {
                        return(ToCsv(longTime,
                                     bigTradeBar.Open,
                                     bigTradeBar.High,
                                     bigTradeBar.Low,
                                     bigTradeBar.Close,
                                     bigTradeBar.Volume));
                    }
                    throw new ArgumentException("Cryto hour/daily bar could not be created", nameof(data));
                }
                break;

            case SecurityType.Forex:
            case SecurityType.Cfd:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = data as Tick;
                    if (tick == null)
                    {
                        throw new ArgumentException("Expected data of type 'Tick'", nameof(data));
                    }
                    return(ToCsv(milliseconds, tick.BidPrice, tick.AskPrice));

                case Resolution.Second:
                case Resolution.Minute:
                    var bar = data as QuoteBar;
                    if (bar == null)
                    {
                        throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
                    }
                    return(ToCsv(milliseconds,
                                 ToNonScaledCsv(bar.Bid), bar.LastBidSize,
                                 ToNonScaledCsv(bar.Ask), bar.LastAskSize));

                case Resolution.Hour:
                case Resolution.Daily:
                    var bigBar = data as QuoteBar;
                    if (bigBar == null)
                    {
                        throw new ArgumentException("Expected data of type 'QuoteBar'", nameof(data));
                    }
                    return(ToCsv(longTime,
                                 ToNonScaledCsv(bigBar.Bid), bigBar.LastBidSize,
                                 ToNonScaledCsv(bigBar.Ask), bigBar.LastAskSize));
                }
                break;

            case SecurityType.Index:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = (Tick)data;
                    return(ToCsv(milliseconds, tick.LastPrice, tick.Quantity, string.Empty, string.Empty, "0"));

                case Resolution.Second:
                case Resolution.Minute:
                    var bar = data as TradeBar;
                    if (bar == null)
                    {
                        throw new ArgumentException("Expected data of type 'TradeBar'", nameof(data));
                    }
                    return(ToCsv(milliseconds, bar.Open, bar.High, bar.Low, bar.Close, bar.Volume));

                case Resolution.Hour:
                case Resolution.Daily:
                    var bigTradeBar = data as TradeBar;
                    return(ToCsv(longTime, bigTradeBar.Open, bigTradeBar.High, bigTradeBar.Low, bigTradeBar.Close, bigTradeBar.Volume));
                }
                break;

            case SecurityType.Option:
            case SecurityType.IndexOption:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = (Tick)data;
                    if (tick.TickType == TickType.Trade)
                    {
                        return(ToCsv(milliseconds,
                                     Scale(tick.LastPrice), tick.Quantity, tick.Exchange, tick.SaleCondition, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.Quote)
                    {
                        return(ToCsv(milliseconds,
                                     Scale(tick.BidPrice), tick.BidSize, Scale(tick.AskPrice), tick.AskSize, tick.Exchange, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.OpenInterest)
                    {
                        return(ToCsv(milliseconds, tick.Value));
                    }
                    break;

                case Resolution.Second:
                case Resolution.Minute:
                    // option and future data can be quote or trade bars
                    var quoteBar = data as QuoteBar;
                    if (quoteBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     ToScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
                                     ToScaledCsv(quoteBar.Ask), quoteBar.LastAskSize));
                    }
                    var tradeBar = data as TradeBar;
                    if (tradeBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     Scale(tradeBar.Open), Scale(tradeBar.High), Scale(tradeBar.Low), Scale(tradeBar.Close), tradeBar.Volume));
                    }
                    var openInterest = data as OpenInterest;
                    if (openInterest != null)
                    {
                        return(ToCsv(milliseconds, openInterest.Value));
                    }
                    break;

                case Resolution.Hour:
                case Resolution.Daily:
                    // option and future data can be quote or trade bars
                    var bigQuoteBar = data as QuoteBar;
                    if (bigQuoteBar != null)
                    {
                        return(ToCsv(longTime,
                                     ToScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
                                     ToScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize));
                    }
                    var bigTradeBar = data as TradeBar;
                    if (bigTradeBar != null)
                    {
                        return(ToCsv(longTime, ToScaledCsv(bigTradeBar), bigTradeBar.Volume));
                    }
                    var bigOpenInterest = data as OpenInterest;
                    if (bigOpenInterest != null)
                    {
                        return(ToCsv(milliseconds, bigOpenInterest.Value));
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
                }
                break;

            case SecurityType.FutureOption:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = (Tick)data;
                    if (tick.TickType == TickType.Trade)
                    {
                        return(ToCsv(milliseconds,
                                     tick.LastPrice, tick.Quantity, tick.Exchange, tick.SaleCondition, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.Quote)
                    {
                        return(ToCsv(milliseconds,
                                     tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.Exchange, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.OpenInterest)
                    {
                        return(ToCsv(milliseconds, tick.Value));
                    }
                    break;

                case Resolution.Second:
                case Resolution.Minute:
                    // option and future data can be quote or trade bars
                    var quoteBar = data as QuoteBar;
                    if (quoteBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
                                     ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize));
                    }
                    var tradeBar = data as TradeBar;
                    if (tradeBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume));
                    }
                    var openInterest = data as OpenInterest;
                    if (openInterest != null)
                    {
                        return(ToCsv(milliseconds, openInterest.Value));
                    }
                    break;

                case Resolution.Hour:
                case Resolution.Daily:
                    // option and future data can be quote or trade bars
                    var bigQuoteBar = data as QuoteBar;
                    if (bigQuoteBar != null)
                    {
                        return(ToCsv(longTime,
                                     ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
                                     ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize));
                    }
                    var bigTradeBar = data as TradeBar;
                    if (bigTradeBar != null)
                    {
                        return(ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume));
                    }
                    var bigOpenInterest = data as OpenInterest;
                    if (bigOpenInterest != null)
                    {
                        return(ToCsv(milliseconds, bigOpenInterest.Value));
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
                }
                break;

            case SecurityType.Future:
                switch (resolution)
                {
                case Resolution.Tick:
                    var tick = (Tick)data;
                    if (tick.TickType == TickType.Trade)
                    {
                        return(ToCsv(milliseconds,
                                     tick.LastPrice, tick.Quantity, tick.Exchange, tick.SaleCondition, tick.Suspicious ? "1": "0"));
                    }
                    if (tick.TickType == TickType.Quote)
                    {
                        return(ToCsv(milliseconds,
                                     tick.BidPrice, tick.BidSize, tick.AskPrice, tick.AskSize, tick.Exchange, tick.Suspicious ? "1" : "0"));
                    }
                    if (tick.TickType == TickType.OpenInterest)
                    {
                        return(ToCsv(milliseconds, tick.Value));
                    }
                    break;

                case Resolution.Second:
                case Resolution.Minute:
                    // option and future data can be quote or trade bars
                    var quoteBar = data as QuoteBar;
                    if (quoteBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     ToNonScaledCsv(quoteBar.Bid), quoteBar.LastBidSize,
                                     ToNonScaledCsv(quoteBar.Ask), quoteBar.LastAskSize));
                    }
                    var tradeBar = data as TradeBar;
                    if (tradeBar != null)
                    {
                        return(ToCsv(milliseconds,
                                     tradeBar.Open, tradeBar.High, tradeBar.Low, tradeBar.Close, tradeBar.Volume));
                    }
                    var openInterest = data as OpenInterest;
                    if (openInterest != null)
                    {
                        return(ToCsv(milliseconds, openInterest.Value));
                    }
                    break;

                case Resolution.Hour:
                case Resolution.Daily:
                    // option and future data can be quote or trade bars
                    var bigQuoteBar = data as QuoteBar;
                    if (bigQuoteBar != null)
                    {
                        return(ToCsv(longTime,
                                     ToNonScaledCsv(bigQuoteBar.Bid), bigQuoteBar.LastBidSize,
                                     ToNonScaledCsv(bigQuoteBar.Ask), bigQuoteBar.LastAskSize));
                    }
                    var bigTradeBar = data as TradeBar;
                    if (bigTradeBar != null)
                    {
                        return(ToCsv(longTime, ToNonScaledCsv(bigTradeBar), bigTradeBar.Volume));
                    }
                    var bigOpenInterest = data as OpenInterest;
                    if (bigOpenInterest != null)
                    {
                        return(ToCsv(longTime, bigOpenInterest.Value));
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(resolution), resolution, null);
                }
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(securityType), securityType, null);
            }

            throw new NotImplementedException(Invariant(
                                                  $"LeanData.GenerateLine has not yet been implemented for security type: {securityType} at resolution: {resolution}"
                                                  ));
        }
        /// <summary>
        /// Gets a list of symbol properties for the specified market/security-type
        /// </summary>
        /// <param name="market">The market the exchange resides in, i.e, 'usa', 'fxcm', ect...</param>
        /// <param name="securityType">The security type of the symbol</param>
        /// <returns>An IEnumerable of symbol properties matching the specified market/security-type</returns>
        public IEnumerable <KeyValuePair <SecurityDatabaseKey, SymbolProperties> > GetSymbolPropertiesList(string market, SecurityType securityType)
        {
            foreach (var entry in _entries)
            {
                var key = entry.Key;
                var symbolProperties = entry.Value;

                if (key.Market == market && key.SecurityType == securityType)
                {
                    yield return(new KeyValuePair <SecurityDatabaseKey, SymbolProperties>(key, symbolProperties));
                }
            }
        }