public void SymbolAndUnderlyingSymbolsMapped(string ticker, string mappedTicker, string sid) { var symbol = new Symbol(SecurityIdentifier.Parse(sid), ticker); var symbolChain = symbol; do { Assert.AreEqual(symbolChain.Value, ticker); symbolChain = symbolChain.Underlying; }while (symbolChain != null); symbol = symbol.UpdateMappedSymbol(mappedTicker); symbolChain = symbol; do { Console.WriteLine(symbolChain.ToString() + "; Value: " + symbolChain.Value); if (symbolChain.SecurityType == SecurityType.Base || symbolChain.SecurityType.RequiresMapping()) { Assert.AreEqual(mappedTicker, symbolChain.Value); } else { Assert.AreNotEqual(mappedTicker, symbolChain.Value); } symbolChain = symbolChain.Underlying; }while (symbolChain != null); }
/// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { if (string.IsNullOrEmpty(line)) { return(null); } var split = line.Split(','); var symbol = new Symbol(SecurityIdentifier.Parse(split[1]), split[0]); var lastUpdateDate = Parse.TryParseExact(split[2], "yyyyMMdd", DateTimeStyles.None, out var lastUpdateDateParsed) ? lastUpdateDateParsed : (DateTime?)null; var weighting = split[3].IsNullOrEmpty() ? (decimal?)null : Parse.Decimal(split[3], NumberStyles.Any); var sharesHeld = split[4].IsNullOrEmpty() ? (decimal?)null : Parse.Decimal(split[4], NumberStyles.Any); var marketValue = split[5].IsNullOrEmpty() ? (decimal?)null : Parse.Decimal(split[5], NumberStyles.Any); return(new ETFConstituentData { LastUpdate = lastUpdateDate, Weight = weighting, SharesHeld = sharesHeld, MarketValue = marketValue, Symbol = symbol, Time = date }); }
public void NumberStrikePriceApproachesBoundsWithoutOverflowingSid(string strikeStr) { var strike = decimal.Parse(strikeStr, CultureInfo.InvariantCulture); var equity = Symbol.Create("AAPL", SecurityType.Equity, Market.USA); var option = Symbol.CreateOption( equity, Market.USA, OptionStyle.American, OptionRight.Call, strike, new DateTime(2020, 5, 21)); // The SID specification states that the total width for the properties value // is at most 20 digits long. If we overflowed the SID, the strike price can and will // eat from other slots, corrupting the data. If we have no overflow, the SID will // be constructed properly without corrupting any data, even as we approach the bounds. // We will assert that all properties contained within the _properties field are valid and not corrupted var sid = SecurityIdentifier.Parse(option.ID.ToString()); Assert.AreEqual(new DateTime(2020, 5, 21), sid.Date); Assert.AreEqual(strike, sid.StrikePrice); Assert.AreEqual(OptionRight.Call, sid.OptionRight); Assert.AreEqual(OptionStyle.American, sid.OptionStyle); Assert.AreEqual(Market.USA, sid.Market); Assert.AreEqual(SecurityType.Option, sid.SecurityType); Assert.AreEqual(option.ID.Date, sid.Date); Assert.AreEqual(option.ID.StrikePrice, sid.StrikePrice); Assert.AreEqual(option.ID.OptionRight, sid.OptionRight); Assert.AreEqual(option.ID.OptionStyle, sid.OptionStyle); Assert.AreEqual(option.ID.Market, sid.Market); Assert.AreEqual(option.ID.SecurityType, sid.SecurityType); }
/// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { try { var csv = line.Split(','); var coarse = new CoarseFundamental { Symbol = new Symbol(SecurityIdentifier.Parse(csv[0]), csv[1]), Time = date, Market = config.Market, Value = csv[2].ToDecimal(), Volume = csv[3].ToInt64(), DollarVolume = csv[4].ToDecimal() }; if (csv.Length > 5) { coarse.HasFundamentalData = Convert.ToBoolean(csv[5]); } if (csv.Length > 7) { coarse.PriceFactor = csv[6].ToDecimal(); coarse.SplitFactor = csv[7].ToDecimal(); } return(coarse); } catch (Exception) { return(null); } }
/// <summary> /// Creates a new instance based on the provided serialized order event /// </summary> public static OrderEvent FromSerialized(SerializedOrderEvent serializedOrderEvent) { var sid = SecurityIdentifier.Parse(serializedOrderEvent.Symbol); var symbol = new Symbol(sid, sid.Symbol); var orderFee = OrderFee.Zero; if (serializedOrderEvent.OrderFeeAmount.HasValue) { orderFee = new OrderFee(new CashAmount(serializedOrderEvent.OrderFeeAmount.Value, serializedOrderEvent.OrderFeeCurrency)); } var orderEvent = new OrderEvent(serializedOrderEvent.OrderId, symbol, DateTime.SpecifyKind(Time.UnixTimeStampToDateTime(serializedOrderEvent.Time), DateTimeKind.Utc), serializedOrderEvent.Status, serializedOrderEvent.Direction, serializedOrderEvent.FillPrice, serializedOrderEvent.FillQuantity, orderFee, serializedOrderEvent.Message) { IsAssignment = serializedOrderEvent.IsAssignment, LimitPrice = serializedOrderEvent.LimitPrice, StopPrice = serializedOrderEvent.StopPrice, FillPriceCurrency = serializedOrderEvent.FillPriceCurrency, Id = serializedOrderEvent.OrderEventId, Quantity = serializedOrderEvent.Quantity }; return(orderEvent); }
/// <summary> /// Creates a new Order instance from a SerializedOrder instance /// </summary> /// <remarks>Used by the <see cref="SerializedOrderJsonConverter"/></remarks> public static Order FromSerialized(SerializedOrder serializedOrder) { var sid = SecurityIdentifier.Parse(serializedOrder.Symbol); var symbol = new Symbol(sid, sid.Symbol); TimeInForce timeInForce = null; var type = System.Type.GetType($"QuantConnect.Orders.TimeInForces.{serializedOrder.TimeInForceType}", throwOnError: false, ignoreCase: true); if (type != null) { timeInForce = (TimeInForce)Activator.CreateInstance(type, true); if (timeInForce is GoodTilDateTimeInForce) { var expiry = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.TimeInForceExpiry.Value); timeInForce = new GoodTilDateTimeInForce(expiry); } } var createdTime = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CreatedTime); var order = CreateOrder(serializedOrder.OrderId, serializedOrder.Type, symbol, serializedOrder.Quantity, DateTime.SpecifyKind(createdTime, DateTimeKind.Utc), serializedOrder.Tag, new OrderProperties { TimeInForce = timeInForce }, serializedOrder.LimitPrice ?? 0, serializedOrder.StopPrice ?? 0, serializedOrder.TriggerPrice ?? 0); order.OrderSubmissionData = new OrderSubmissionData(serializedOrder.SubmissionBidPrice, serializedOrder.SubmissionAskPrice, serializedOrder.SubmissionLastPrice); order.BrokerId = serializedOrder.BrokerId; order.ContingentId = serializedOrder.ContingentId; order.Price = serializedOrder.Price; order.PriceCurrency = serializedOrder.PriceCurrency; order.Status = serializedOrder.Status; if (serializedOrder.LastFillTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastFillTime.Value); order.LastFillTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } if (serializedOrder.LastUpdateTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastUpdateTime.Value); order.LastUpdateTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } if (serializedOrder.CanceledTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CanceledTime.Value); order.CanceledTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } return(order); }
public void ParsedToStringEqualsValue() { var value = SPY_Put_19550.ToString(); Console.WriteLine(value); var sid2 = SecurityIdentifier.Parse(value); Assert.AreEqual(SPY_Put_19550, sid2); }
/// <summary> /// Create an order from a simple JObject /// </summary> /// <param name="jObject"></param> /// <returns>Order Object</returns> public static Order CreateOrderFromJObject(JObject jObject) { // create order instance based on order type field var orderType = (OrderType)jObject["Type"].Value <int>(); var order = CreateOrder(orderType, jObject); // populate common order properties order.Id = jObject["Id"].Value <int>(); order.Status = (OrderStatus)jObject["Status"].Value <int>(); order.Time = jObject["Time"].Value <DateTime>(); order.Tag = jObject["Tag"].Value <string>(); try { order.Quantity = jObject["Quantity"].Value <int>(); } catch { order.Quantity = jObject["Quantity"].Value <decimal>(); } order.Price = jObject["Price"].Value <decimal>(); var securityType = (SecurityType)jObject["SecurityType"].Value <int>(); order.BrokerId = jObject["BrokerId"].Select(x => x.Value <string>()).ToList(); order.ContingentId = jObject["ContingentId"].Value <int>(); string market = Market.USA; //does data have market? var suppliedMarket = jObject.SelectTokens("Symbol.ID.Market"); if (suppliedMarket.Any()) { market = suppliedMarket.Single().Value <string>(); } else { //no data, use default new DefaultBrokerageModel().DefaultMarkets.TryGetValue(securityType, out market); } if (jObject.SelectTokens("Symbol.ID").Any()) { var sid = SecurityIdentifier.Parse(jObject.SelectTokens("Symbol.ID").Single().Value <string>()); var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = new Symbol(sid, ticker); } else if (jObject.SelectTokens("Symbol.Value").Any()) { // provide for backwards compatibility var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = Symbol.Create(ticker, securityType, market); } else { var tickerstring = jObject["Symbol"].Value <string>(); order.Symbol = Symbol.Create(tickerstring, securityType, market); } return(order); }
public void GetDividends() { var date = new DateTime(2018, 05, 11); var AAPL = new Symbol(SecurityIdentifier.Parse("AAPL R735QTJ8XC9X"), "AAPL"); var dividends = _api.GetDividends(date, date); var aapl = dividends.Single(s => s.Symbol == AAPL); Assert.AreEqual(0.73m, aapl.Distribution); Assert.AreEqual(date, aapl.Time); Assert.AreEqual(190.03m, aapl.ReferencePrice); }
public void GetsSplits() { var date = new DateTime(2014, 06, 09); var AAPL = new Symbol(SecurityIdentifier.Parse("AAPL R735QTJ8XC9X"), "AAPL"); var splits = _api.GetSplits(date, date); var aapl = splits.Single(s => s.Symbol == AAPL); Assert.AreEqual((1 / 7m).RoundToSignificantDigits(6), aapl.SplitFactor); Assert.AreEqual(date, aapl.Time); Assert.AreEqual(SplitType.SplitOccurred, aapl.Type); Assert.AreEqual(645.57m, aapl.ReferencePrice); }
/// <summary> /// Parses a single line of CSV and converts it into an instance /// </summary> /// <param name="line">Line of CSV</param> /// <returns>SecurityDefinition instance</returns> public static SecurityDefinition FromCsvLine(string line) { var csv = line.Split(','); return(new SecurityDefinition { SecurityIdentifier = SecurityIdentifier.Parse(csv[0]), CUSIP = string.IsNullOrWhiteSpace(csv[1]) ? null : csv[1], CompositeFIGI = string.IsNullOrWhiteSpace(csv[2]) ? null : csv[2], SEDOL = string.IsNullOrWhiteSpace(csv[3]) ? null : csv[3], ISIN = string.IsNullOrWhiteSpace(csv[4]) ? null : csv[4] }); }
/// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader"/> to read from.</param><param name="objectType">Type of the object.</param><param name="existingValue">The existing value of object being read.</param><param name="serializer">The calling serializer.</param> /// <returns> /// The object value. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObject = JObject.Load(reader); // create order instance based on order type field var orderType = (OrderType)jObject["Type"].Value <int>(); var order = CreateOrder(orderType, jObject); // populate common order properties order.Id = jObject["Id"].Value <int>(); order.Quantity = jObject["Quantity"].Value <int>(); order.Status = (OrderStatus)jObject["Status"].Value <int>(); order.Time = jObject["Time"].Value <DateTime>(); order.Tag = jObject["Tag"].Value <string>(); order.Quantity = jObject["Quantity"].Value <int>(); order.Price = jObject["Price"].Value <decimal>(); order.SecurityType = (SecurityType)jObject["SecurityType"].Value <int>(); order.BrokerId = jObject["BrokerId"].Select(x => x.Value <long>()).ToList(); order.ContingentId = jObject["ContingentId"].Value <int>(); if (jObject.SelectTokens("Symbol.ID").Any()) { var sid = SecurityIdentifier.Parse(jObject.SelectTokens("Symbol.ID").Single().Value <string>()); var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = new Symbol(sid, ticker); } else { // provide for backwards compatibility var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); SecurityIdentifier sid; if (order.SecurityType == SecurityType.Equity) { sid = GetEquitySid(ticker, order.Time.Date); } else if (order.SecurityType == SecurityType.Forex) { sid = SecurityIdentifier.GenerateForex(ticker, Market.FXCM); } else { throw new NotImplementedException("The specified security type has not been implemented yet: " + order.SecurityType); } order.Symbol = new Symbol(sid, ticker); } return(order); }
/// <summary> /// Creates a new ScheduledEventParams instance from a SerializedScheduledEventParams instance /// </summary> /// <param name="serializedScheduledEventsParams"></param> /// <returns></returns> public static ScheduledEventParams FromSerialized(SerializedScheduledEventParams serializedScheduledEventsParams) { string name = serializedScheduledEventsParams.Name; string tag = serializedScheduledEventsParams.Tag; var sid = SecurityIdentifier.Parse(serializedScheduledEventsParams.Symbol); Symbol symbol = new Symbol(sid, sid.Symbol); DateTime expiry_time = QuantConnect.Time.UnixTimeStampToDateTime(serializedScheduledEventsParams.ExpiryTime); OrderReason orderReason = serializedScheduledEventsParams.OrderReason; decimal quantity = serializedScheduledEventsParams.Quantity; return(new ScheduledEventParams(name, expiry_time, symbol, quantity, orderReason)); }
/// <summary> /// Create an order from a simple JObject /// </summary> /// <param name="jObject"></param> /// <returns>Order Object</returns> public static Order CreateOrderFromJObject(JObject jObject) { // create order instance based on order type field var orderType = (OrderType)jObject["Type"].Value <int>(); var order = CreateOrder(orderType, jObject); // populate common order properties order.Id = jObject["Id"].Value <int>(); order.Quantity = jObject["Quantity"].Value <int>(); order.Status = (OrderStatus)jObject["Status"].Value <int>(); order.Time = jObject["Time"].Value <DateTime>(); order.Tag = jObject["Tag"].Value <string>(); order.Quantity = jObject["Quantity"].Value <int>(); order.Price = jObject["Price"].Value <decimal>(); var securityType = (SecurityType)jObject["SecurityType"].Value <int>(); order.BrokerId = jObject["BrokerId"].Select(x => x.Value <string>()).ToList(); order.ContingentId = jObject["ContingentId"].Value <int>(); var market = Market.USA; if (securityType == SecurityType.Forex) { market = Market.FXCM; } if (jObject.SelectTokens("Symbol.ID").Any()) { var sid = SecurityIdentifier.Parse(jObject.SelectTokens("Symbol.ID").Single().Value <string>()); var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = new Symbol(sid, ticker); } else if (jObject.SelectTokens("Symbol.Value").Any()) { // provide for backwards compatibility var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = Symbol.Create(ticker, securityType, market); } else { var tickerstring = jObject["Symbol"].Value <string>(); order.Symbol = Symbol.Create(tickerstring, securityType, market); } return(order); }
/// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { try { var csv = line.Split(','); var preselected = new ConstituentsUniverseData { Symbol = new Symbol(SecurityIdentifier.Parse(csv[1]), csv[0]), Time = isLiveMode ? date.AddDays(-1) : date }; return(preselected); } catch { return(null); } }
/// <summary> /// Creates a new <see cref="Insight"/> object from the specified serialized form /// </summary> /// <param name="serializedInsight">The insight DTO</param> /// <returns>A new insight containing the information specified</returns> public static Insight FromSerializedInsight(SerializedInsight serializedInsight) { var insight = new Insight( Time.UnixTimeStampToDateTime(serializedInsight.CreatedTime), new Symbol(SecurityIdentifier.Parse(serializedInsight.Symbol), serializedInsight.Ticker), TimeSpan.FromSeconds(serializedInsight.Period), serializedInsight.Type, serializedInsight.Direction, serializedInsight.Magnitude, serializedInsight.Confidence, serializedInsight.SourceModel, serializedInsight.Weight ) { Id = Guid.Parse(serializedInsight.Id), CloseTimeUtc = Time.UnixTimeStampToDateTime(serializedInsight.CloseTime), EstimatedValue = serializedInsight.EstimatedValue, ReferenceValue = serializedInsight.ReferenceValue, ReferenceValueFinal = serializedInsight.ReferenceValueFinal, GroupId = string.IsNullOrEmpty(serializedInsight.GroupId) ? (Guid?)null : Guid.Parse(serializedInsight.GroupId) }; // only set score values if non-zero or if they're the final scores if (serializedInsight.ScoreIsFinal) { insight.Score.SetScore(InsightScoreType.Magnitude, serializedInsight.ScoreMagnitude, insight.CloseTimeUtc); insight.Score.SetScore(InsightScoreType.Direction, serializedInsight.ScoreDirection, insight.CloseTimeUtc); insight.Score.Finalize(insight.CloseTimeUtc); } else { if (serializedInsight.ScoreMagnitude != 0) { insight.Score.SetScore(InsightScoreType.Magnitude, serializedInsight.ScoreMagnitude, insight.CloseTimeUtc); } if (serializedInsight.ScoreDirection != 0) { insight.Score.SetScore(InsightScoreType.Direction, serializedInsight.ScoreDirection, insight.CloseTimeUtc); } } return(insight); }
public void ToStringPipeDelimitsUnderlying() { var actual = SPY_Put_19550.ToString(); var parts = actual.Split('|'); var option = SecurityIdentifier.Parse(parts[0]); // verify various values Assert.AreEqual(OptionRight.Put, option.OptionRight); // put Assert.AreEqual(new DateTime(2015, 09, 18), option.Date); // oa date 2015.09.18 Assert.AreEqual(OptionStyle.European, option.OptionStyle); // option style Assert.AreEqual(195.5m, option.StrikePrice); // strike/scale Assert.AreEqual(Market.USA, option.Market); // market Assert.AreEqual(SecurityType.Option, option.SecurityType); // security type Assert.AreEqual("SPY", option.Symbol); // SPY in base36 Assert.IsFalse(option.HasUnderlying); Assert.Throws <InvalidOperationException>(() => { var x = option.Underlying; }); var equity = SecurityIdentifier.Parse(parts[1]); Assert.AreEqual(SPY, equity); }
/// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { try { var csv = line.Split(','); return(new CoarseFundamental { Symbol = new Symbol(SecurityIdentifier.Parse(csv[0]), csv[1]), Time = date, Market = config.Market, Value = csv[2].ToDecimal(), Volume = csv[3].ToInt64(), DollarVolume = csv[4].ToDecimal() }); } catch (Exception) { return(null); } }
/// <summary> /// Creates a new <see cref="Insight"/> object from the specified serialized form /// </summary> /// <param name="serializedInsight">The insight DTO</param> /// <returns>A new insight containing the information specified</returns> internal static Insight FromSerializedInsight(SerializedInsight serializedInsight) { var insight = new Insight( Time.UnixTimeStampToDateTime(serializedInsight.GeneratedTime), new Symbol(SecurityIdentifier.Parse(serializedInsight.Symbol), serializedInsight.Ticker), serializedInsight.Type, serializedInsight.Direction, TimeSpan.FromSeconds(serializedInsight.Period), serializedInsight.Magnitude, serializedInsight.Confidence ) { Id = Guid.Parse(serializedInsight.Id), CloseTimeUtc = Time.UnixTimeStampToDateTime(serializedInsight.CloseTime), EstimatedValue = serializedInsight.EstimatedValue, ReferenceValue = serializedInsight.ReferenceValue }; // only set score values if non-zero or if they're the final scores if (serializedInsight.ScoreIsFinal) { insight.Score.SetScore(InsightScoreType.Magnitude, serializedInsight.ScoreMagnitude, insight.CloseTimeUtc); insight.Score.SetScore(InsightScoreType.Direction, serializedInsight.ScoreDirection, insight.CloseTimeUtc); insight.Score.Finalize(insight.CloseTimeUtc); } else { if (serializedInsight.ScoreMagnitude != 0) { insight.Score.SetScore(InsightScoreType.Magnitude, serializedInsight.ScoreMagnitude, insight.CloseTimeUtc); } if (serializedInsight.ScoreDirection != 0) { insight.Score.SetScore(InsightScoreType.Direction, serializedInsight.ScoreDirection, insight.CloseTimeUtc); } } return(insight); }
public void NegativeStrikePriceRoundTrip() { var future = Symbol.CreateFuture( "CL", Market.NYMEX, new DateTime(2020, 5, 20)); var option = Symbol.CreateOption( future, Market.NYMEX, OptionStyle.American, OptionRight.Call, -50, new DateTime(2020, 4, 16)); Assert.AreEqual(-50, option.ID.StrikePrice); // Forces the reconstruction of the strike price to ensure that it's been properly parsed. var newSid = SecurityIdentifier.Parse(option.ID.ToString()); Assert.AreEqual(-50, newSid.StrikePrice); }
[TestCase("BTCUSD XJ", "BTCUSD", null)] // Crypto public void SymbolCanonical(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); if (expectedValue != null) { var result = symbol.Canonical; Assert.IsNotNull(result); Assert.AreSame(result, symbol.Canonical); Assert.IsTrue(result.IsCanonical()); Assert.IsTrue(result.Value.Contains(ticker)); Assert.AreEqual(symbol.SecurityType, result.SecurityType); Assert.AreEqual(symbol.ID.Market, result.ID.Market); } else { Assert.Throws <InvalidOperationException>(() => { var canonical = symbol.Canonical; }); } }
/// <summary> /// Create an order from a simple JObject /// </summary> /// <param name="jObject"></param> /// <returns>Order Object</returns> public static Order CreateOrderFromJObject(JObject jObject) { // create order instance based on order type field var orderType = (OrderType)jObject["Type"].Value <int>(); var order = CreateOrder(orderType, jObject); // populate common order properties order.Id = jObject["Id"].Value <int>(); order.Status = (OrderStatus)jObject["Status"].Value <int>(); order.Time = jObject["Time"].Value <DateTime>(); var orderSubmissionData = jObject["OrderSubmissionData"]; if (orderSubmissionData != null && orderSubmissionData.Type != JTokenType.Null) { var bidPrice = orderSubmissionData["BidPrice"].Value <decimal>(); var askPrice = orderSubmissionData["AskPrice"].Value <decimal>(); var lastPrice = orderSubmissionData["LastPrice"].Value <decimal>(); order.OrderSubmissionData = new OrderSubmissionData(bidPrice, askPrice, lastPrice); } var lastFillTime = jObject["LastFillTime"]; var lastUpdateTime = jObject["LastUpdateTime"]; var canceledTime = jObject["CanceledTime"]; if (canceledTime != null && canceledTime.Type != JTokenType.Null) { order.CanceledTime = canceledTime.Value <DateTime>(); } if (lastFillTime != null && lastFillTime.Type != JTokenType.Null) { order.LastFillTime = lastFillTime.Value <DateTime>(); } if (lastUpdateTime != null && lastUpdateTime.Type != JTokenType.Null) { order.LastUpdateTime = lastUpdateTime.Value <DateTime>(); } var tag = jObject["Tag"]; if (tag != null && tag.Type != JTokenType.Null) { order.Tag = tag.Value <string>(); } else { order.Tag = ""; } order.Quantity = jObject["Quantity"].Value <decimal>(); order.Price = jObject["Price"].Value <decimal>(); var priceCurrency = jObject["PriceCurrency"]; if (priceCurrency != null && priceCurrency.Type != JTokenType.Null) { order.PriceCurrency = priceCurrency.Value <string>(); } var securityType = (SecurityType)jObject["SecurityType"].Value <int>(); order.BrokerId = jObject["BrokerId"].Select(x => x.Value <string>()).ToList(); order.ContingentId = jObject["ContingentId"].Value <int>(); var timeInForce = jObject["Properties"]?["TimeInForce"] ?? jObject["TimeInForce"] ?? jObject["Duration"]; order.Properties.TimeInForce = timeInForce != null ? CreateTimeInForce(timeInForce, jObject) : TimeInForce.GoodTilCanceled; string market = null; //does data have market? var suppliedMarket = jObject.SelectTokens("Symbol.ID.Market"); if (suppliedMarket.Any()) { market = suppliedMarket.Single().Value <string>(); } if (jObject.SelectTokens("Symbol.ID").Any()) { var sid = SecurityIdentifier.Parse(jObject.SelectTokens("Symbol.ID").Single().Value <string>()); var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); order.Symbol = new Symbol(sid, ticker); } else if (jObject.SelectTokens("Symbol.Value").Any()) { // provide for backwards compatibility var ticker = jObject.SelectTokens("Symbol.Value").Single().Value <string>(); if (market == null && !SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(ticker, securityType, out market)) { market = DefaultBrokerageModel.DefaultMarketMap[securityType]; } order.Symbol = Symbol.Create(ticker, securityType, market); } else { var tickerstring = jObject["Symbol"].Value <string>(); if (market == null && !SymbolPropertiesDatabase.FromDataFolder().TryGetMarket(tickerstring, securityType, out market)) { market = DefaultBrokerageModel.DefaultMarketMap[securityType]; } order.Symbol = Symbol.Create(tickerstring, securityType, market); } return(order); }
public void RoundTripNoneParse() { Assert.AreEqual(SecurityIdentifier.None, SecurityIdentifier.Parse(SecurityIdentifier.None.ToString())); }
public void RoundTripEmptyParse() { Assert.AreEqual(SecurityIdentifier.Empty, SecurityIdentifier.Parse(SecurityIdentifier.Empty.ToString())); }
public void PreviousEmptyFormatStillSupported() { Assert.AreEqual(SecurityIdentifier.Empty, SecurityIdentifier.Parse(" ")); }
[TestCase("BTCUSD XJ", "BTCUSD", "BTCUSD")] // Crypto public void SymbolAlias(string identifier, string ticker, string expectedValue) { var symbol = new Symbol(SecurityIdentifier.Parse(identifier), ticker); Assert.AreEqual(expectedValue, symbol.Value); }