示例#1
0
        /// <summary>
        /// Deserialises an <see cref="XmlElement"/> containing security settings configuration.
        /// </summary>
        /// <param name="element">The <see cref="XmlElement"/> to deserialise.</param>
        public override void Deserialize(XmlElement element)
        {
            Type         = "External File-based";
            DefaultRight = Util.GetEnumFromElementOrAttribute <SecurityRight>("defaultRight", element);

            foreach (XmlElement ele in element.SelectNodes("files/*"))
            {
                var externalFile = new ExternalFile();
                externalFile.Deserialize(ele);
                Files.Add(externalFile);
            }

            foreach (XmlElement ele in element.SelectNodes("audit/*"))
            {
                SecurityLogger logger = Util.CreateInstanceFromXmlName <SecurityLogger>(ele.Name);
                if (logger != null)
                {
                    logger.Deserialize(ele);
                    AuditLoggers.Add(logger);
                }
            }

            XmlElement readerEl = element.SelectSingleNode("auditReader") as XmlElement;

            if (readerEl != null)
            {
                string xmlName             = readerEl.GetAttribute("type");
                SecurityAuditReader reader = Util.CreateInstanceFromXmlName <SecurityAuditReader>(xmlName);
                if (reader != null)
                {
                    reader.Deserialize(readerEl);
                    AuditReader = reader;
                }
            }

            XmlElement cacheEl = element.SelectSingleNode("cache") as XmlElement;

            if (cacheEl != null)
            {
                string        xmlName = cacheEl.GetAttribute("type");
                SecurityCache cache   = Util.CreateInstanceFromXmlName <SecurityCache>(xmlName);
                if (cache != null)
                {
                    cache.Deserialize(cacheEl);
                    Cache = cache;
                }
            }
        }
示例#2
0
        public ActionResult UserHasBeenDeleted(long?userid)
        {
            if (userid == null)
            {
                return(HttpNotFound());
            }

            try
            {
                SecurityCache.Revoke(userid.Value);
                return(new HttpStatusCodeResult(200));
            }
            catch
            {
                return(new HttpStatusCodeResult(500));
            }
        }
示例#3
0
        public ActionResult GetHistory(string metaViewName, Guid id)
        {
            if (!SecurityCache.ViewCan(metaViewName, SecurityPermissionBaseTypeEnum.View))
            {
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = DynamicEntityJSONDataSource.GetNotSuccess(WsFactory.GetАccessDeniedPage())
                });
            }

            return(new ContentResult
            {
                ContentType = "text/html",
                Content = VersionFormatter.GetObjectHistoryInHtml(id)
            });
        }
示例#4
0
 /// <summary>
 /// Creates instance of the Option class.
 /// </summary>
 /// <remarks>
 /// Allows for the forwarding of the security configuration to the
 /// base Security constructor
 /// </remarks>
 protected Option(Symbol symbol,
                  Cash quoteCurrency,
                  SymbolProperties symbolProperties,
                  SecurityExchange exchange,
                  SecurityCache cache,
                  ISecurityPortfolioModel portfolioModel,
                  IFillModel fillModel,
                  IFeeModel feeModel,
                  ISlippageModel slippageModel,
                  ISettlementModel settlementModel,
                  IVolatilityModel volatilityModel,
                  IBuyingPowerModel buyingPowerModel,
                  ISecurityDataFilter dataFilter,
                  IPriceVariationModel priceVariationModel,
                  ICurrencyConverter currencyConverter,
                  IRegisteredSecurityDataTypesProvider registeredTypesProvider,
                  Security underlying
                  ) : base(
         symbol,
         quoteCurrency,
         symbolProperties,
         exchange,
         cache,
         portfolioModel,
         fillModel,
         feeModel,
         slippageModel,
         settlementModel,
         volatilityModel,
         buyingPowerModel,
         dataFilter,
         priceVariationModel,
         currencyConverter,
         registeredTypesProvider
         )
 {
     ExerciseSettlement = SettlementType.PhysicalDelivery;
     SetDataNormalizationMode(DataNormalizationMode.Raw);
     OptionExerciseModel = new DefaultExerciseModel();
     PriceModel          = new CurrentPriceOptionPriceModel();
     Holdings            = new OptionHolding(this, currencyConverter);
     _symbolProperties   = (OptionSymbolProperties)symbolProperties;
     SetFilter(-1, 1, TimeSpan.Zero, TimeSpan.FromDays(35));
     Underlying = underlying;
 }
        private void AddDataAndAssertChanges(SecurityCache cache, SecuritySeedData seedType, SecuritySeedData dataType, BaseData data, Dictionary <string, string> cacheToBaseDataPropertyMap = null)
        {
            var before       = JObject.FromObject(cache);
            var dataSnapshot = JObject.FromObject(data);

            cache.AddData(data);
            var after = JObject.FromObject(cache);

            var updatedCacheProperties = GetPropertiesBy(dataType);

            if (seedType == SecuritySeedData.QuoteBar && (dataType == SecuritySeedData.QuoteBar || dataType == SecuritySeedData.TradeBar))
            {
                // these properties aren't updated when previous data is quote bar at same time as a new IBar
                updatedCacheProperties = updatedCacheProperties.Where(p =>
                                                                      p != "Open" &&
                                                                      p != "High" &&
                                                                      p != "Low" &&
                                                                      p != "Close" &&
                                                                      p != "Price"
                                                                      ).ToArray();
            }

            foreach (var property in before.Properties())
            {
                string dataPropertyName = null;
                if (updatedCacheProperties.Contains(property.Name))
                {
                    if (cacheToBaseDataPropertyMap?.TryGetValue(property.Name, out dataPropertyName) == true)
                    {
                        // avoiding failures due to decimal <> long in JToken.DeepEquals
                        var e = dataSnapshot.SelectToken(dataPropertyName).ToString();
                        var a = after.SelectToken(property.Name).ToString();
                        Assert.AreEqual(e, a, $"{property.Name}: Expected {e}. Actual {a}");
                    }
                    else
                    {
                        dataSnapshot.IsEqualTo(after, property.Name);
                    }
                }
                else
                {
                    before.IsEqualTo(after, property.Name);
                }
            }
        }
示例#6
0
        public async Task <ActionResult> Permissions(long?userid)
        {
            if (userid == null)
            {
                return(HttpNotFound());
            }

            try
            {
                await SecurityCache.UpdatePermissionsForUserID(userid.Value);

                return(new HttpStatusCodeResult(200));
            }
            catch
            {
                return(new HttpStatusCodeResult(500));
            }
        }
示例#7
0
        public ActionResult BudgetItemChangeManager(Guid employeeid, string budgetitems)
        {
            var idsList = budgetitems.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => new Guid(x)).ToList();

            if (SecurityCache.FormCan("BudgetItem", "ChangeManager"))
            {
                try
                {
                    string message;
                    if (BudgetItem.ChangeManager(employeeid, idsList, out message))
                    {
                        return(new ContentResult
                        {
                            ContentType = "text/html",
                            Content = DynamicEntityJSONDataSource.GetSuccess(message)
                        });
                    }

                    return(new ContentResult
                    {
                        ContentType = "text/html",
                        Content = DynamicEntityJSONDataSource.GetNotSuccess(message)
                    });
                }
                catch (Exception ex)
                {
                    Logger.Log.Error(ex);

                    return(new ContentResult
                    {
                        ContentType = "text/html",
                        Content = DynamicEntityJSONDataSource.GetNotSuccess(ex.Message)
                    });
                }
            }
            else
            {
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = DynamicEntityJSONDataSource.GetNotSuccess(OptimaJet.Localization.LocalizationProvider.Provider.Get("Access is denied"))
                });
            }
        }
示例#8
0
        public ActionResult InvoiceToState(Guid id, byte state)
        {
            string res = string.Empty;

            if (!SecurityCache.FormCan("Invoice", "ChangeState"))
            {
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = DynamicEntityJSONDataSource.GetNotSuccess(OptimaJet.Localization.LocalizationProvider.Provider.Get("Access is denied"))
                });
            }


            try
            {
                var error = OptimaJet.BJet.VTB.Invoice.ToState(id, state);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    return(new ContentResult
                    {
                        ContentType = "text/html",
                        Content = DynamicEntityJSONDataSource.GetNotSuccess(error)
                    });
                }
                res = OptimaJet.Localization.LocalizationProvider.Provider.Get("State is changed");
            }
            catch (Exception ex)
            {
                Logger.Log.Error(ex);

                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = DynamicEntityJSONDataSource.GetNotSuccess(ex.Message)
                });
            }

            return(new ContentResult
            {
                ContentType = "text/html",
                Content = DynamicEntityJSONDataSource.GetSuccess(res)
            });
        }
        public void GivenSameTimeStampForTradeBarAndQuoteQuotebarPrioritizeQuoteBar()
        {
            // Arrange
            var securityCache = new SecurityCache();
            var time          = DateTime.Now;
            var quotes        = GenerateData(MarketDataType.QuoteBar, 5, false, time);
            var trades        = GenerateData(MarketDataType.TradeBar, 5, false, time);
            var data          = quotes.Concat(trades);

            data = data.OrderBy(d => d.EndTime);
            // Act
            foreach (var baseData in data)
            {
                securityCache.AddData(baseData);
            }
            // Assert
            Assert.True(securityCache.GetData().Equals(quotes.Last()));
            Assert.True(securityCache.GetData <TradeBar>().Equals(trades.Last()));
        }
示例#10
0
        /// <summary>
        /// Helper method to create a new instance.
        /// Knows which security types should create one and determines the appropriate delisting event provider to use
        /// </summary>
        public static bool TryCreate(SubscriptionDataConfig dataConfig, ITimeProvider timeProvider, IDataQueueHandler dataQueueHandler,
                                     SecurityCache securityCache, IMapFileProvider mapFileProvider, out IEnumerator <BaseData> enumerator)
        {
            enumerator = null;
            var securityType = dataConfig.SecurityType;

            if (securityType == SecurityType.FutureOption || securityType == SecurityType.Future ||
                securityType == SecurityType.Option || securityType == SecurityType.Equity)
            {
                var mapfile = mapFileProvider.Get(dataConfig.Symbol.ID.Market).ResolveMapFile(dataConfig.Symbol, dataConfig.Type);
                var delistingEventProvider = new DelistingEventProvider();
                if (securityType == SecurityType.Equity)
                {
                    delistingEventProvider = new LiveDataBasedDelistingEventProvider(dataConfig, dataQueueHandler);
                }
                enumerator = new LiveDelistingEventProviderEnumerator(timeProvider, dataConfig, securityCache, delistingEventProvider, mapfile);
                return(true);
            }
            return(false);
        }
        public void AddDataWithSameEndTime_SetsQuoteBarValues(SecurityCache cache, SecuritySeedData seedType)
        {
            var map = new Dictionary <string, string>
            {
                { "Price", "Close" },
                { "BidPrice", "Bid.Close" },
                { "BidSize", "LastBidSize" },
                { "AskPrice", "Ask.Close" },
                { "AskSize", "LastAskSize" }
            };

            AddDataAndAssertChanges(cache, seedType, SecuritySeedData.QuoteBar, new QuoteBar
            {
                Bid         = new Bar(101, 102, 103, 104),
                Ask         = new Bar(105, 106, 107, 108),
                LastAskSize = 109,
                LastBidSize = 110,
                EndTime     = ReferenceTime
            }, map);
        }
示例#12
0
        public async override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(actionContext.Request.Headers.Authorization?.Scheme) ||
                string.IsNullOrEmpty(actionContext.Request.Headers.Authorization.Parameter) ||
                !actionContext.Request.Headers.Authorization.Scheme.Equals("Bearer") ||
                !await SecurityCache.IsValid(actionContext.Request.Headers.Authorization.Parameter))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                return;
            }

            SecurityProfile securityProfile = SecurityCache.Get(actionContext.Request.Headers.Authorization.Parameter);

            if (securityProfile == null || !RequiredPermissions.All(permission => securityProfile.Permissions.Contains(permission)))
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
            }

            actionContext.Request.Properties.Add("SecurityProfile", securityProfile);
        }
        public void GetAllData_ReturnsListOfData()
        {
            var cache = new SecurityCache();

            cache.StoreData(new []
            {
                new CustomDataBitcoinAlgorithm.Bitcoin {
                    Ask = 1m
                },
                new CustomDataBitcoinAlgorithm.Bitcoin {
                    Ask = 2m
                }
            }, typeof(CustomDataBitcoinAlgorithm.Bitcoin));

            var data = cache.GetAll <CustomDataBitcoinAlgorithm.Bitcoin>().ToList();

            Assert.AreEqual(2, data.Count);
            Assert.AreEqual(1m, data[0].Ask);
            Assert.AreEqual(2m, data[1].Ask);
        }
        public void UseLatestTradebarIfThereIsntAvailableQuotebar()
        {
            // Arrange
            var securityCache = new SecurityCache();
            var time          = DateTime.Now;
            var quotes        = GenerateData(MarketDataType.QuoteBar, 5, false, time);

            foreach (var baseData in quotes)
            {
                securityCache.AddData(baseData);
            }
            // Add one last tradebar with a later timestamp
            var laterTrade = GenerateData(MarketDataType.TradeBar, 1, true, quotes.Last().Time.AddSeconds(1)).First();

            // Act
            securityCache.AddData(laterTrade);
            // Assert
            Assert.True(securityCache.GetData().Equals(laterTrade));
            Assert.True(securityCache.GetData <QuoteBar>().Equals(quotes.Last()));
        }
示例#15
0
        protected override bool PostSave(ITransaction transaction)
        {
            if (IsInsert && RevokeTime == null) // Is insert, not revoking
            {
                SecurityProfile securityProfile = new SecurityProfile();
                securityProfile.AccessToken = AccessToken.ToString();
                securityProfile.Expiration  = Expiration.Value;
                securityProfile.UserID      = UserID.Value;

                User user = DataObject.GetReadOnlyByPrimaryKey <User>(UserID, transaction, new string[] { "UserPermissions.Permission.Key" });
                securityProfile.Permissions.AddRange(user.UserPermissions.Select(up => up.Permission.Key));

                SecurityCache.AddSecurityProfile(securityProfile);
            }

            if (IsFieldDirty("RevokeTime") && RevokeTime != null)
            {
                SecurityCache.Revoke(AccessToken.ToString());
            }
            return(base.PostSave(transaction));
        }
示例#16
0
        public ActionResult ExportCSV(string metaViewName, string entityIds)
        {
            if (!SecurityCache.ViewCan(metaViewName, SecurityPermissionBaseTypeEnum.View))
            {
                return(Content(WsFactory.GetАccessDeniedHtmlFrom()));
            }

            EventsLogHelper.ExportData("CSV", metaViewName, Request);

            EntityContainer data;

            if (string.IsNullOrEmpty(entityIds))
            {
                data = GetDataFromRequest(metaViewName);
            }
            else
            {
                data = GetDataFromRequest(metaViewName, entityIds);
            }

            return(File(data.ToCsv(DynamicEntityJSONDataSource.GetFieldColumns(Request.QueryString)), "application/CSV", string.Format("{0}.csv", metaViewName)));
        }
示例#17
0
        public void TickQuantityUpdatedInSecurityCache()
        {
            var tick1 = new Tick();

            tick1.Update(1, 1, 1, 10, 1, 1);

            var tick2 = new Tick();

            tick2.Update(1, 1, 1, 20, 1, 1);

            var securityCache = new SecurityCache();

            Assert.AreEqual(0, securityCache.Volume);

            securityCache.AddData(tick1);

            Assert.AreEqual(10, securityCache.Volume);

            securityCache.AddData(tick2);

            Assert.AreEqual(20, securityCache.Volume);
        }
示例#18
0
        public void StoreData_TargetToModify_SecurityCacheHasTradeAndQuoteTick()
        {
            // Arrange
            var sourceToShare = new SecurityCache();
            var time          = DateTime.Now;

            var quote = new Tick(time, Symbol.Empty, 100, 102)
            {
                TickType = TickType.Quote
            };

            sourceToShare.StoreData(new[] { quote }, typeof(Tick));

            var trade = new Tick(time, Symbol.Empty, 100, 100, 102)
            {
                TickType = TickType.Trade
            };

            sourceToShare.StoreData(new[] { trade }, typeof(Tick));

            // Adding OpenInterest as Tick or OpenInterest should not matter
            var openInterest = new OpenInterest(time, Symbol.Empty, 1000);

            sourceToShare.StoreData(new[] { openInterest }, typeof(Tick));           // Add as Tick
            sourceToShare.StoreData(new[] { openInterest }, typeof(OpenInterest));   // Add as OI

            var targetToModify = new SecurityCache();

            SecurityCache.ShareTypeCacheInstance(sourceToShare, targetToModify);

            // Assert
            Assert.IsTrue(targetToModify.HasData(typeof(Tick)));
            Assert.True(targetToModify.GetData <Tick>().Equals(trade));
            Assert.True(targetToModify.GetData <OpenInterest>().Equals(openInterest));

            Assert.True(targetToModify.GetAll <Tick>().LastOrDefault(x => x.TickType == TickType.Quote).Equals(quote));
            Assert.True(targetToModify.GetAll <Tick>().LastOrDefault(x => x.TickType == TickType.Trade).Equals(trade));
        }
示例#19
0
        public ActionResult ExportXls(string metaViewName, string entityIds)
        {
            if (!SecurityCache.ViewCan(metaViewName, SecurityPermissionBaseTypeEnum.View))
            {
                return(Content(WsFactory.GetАccessDeniedHtmlFrom()));
            }

            EventsLogHelper.ExportData("Xls", metaViewName, Request);

            EntityContainer data;

            if (string.IsNullOrEmpty(entityIds))
            {
                data = GetDataFromRequest(metaViewName);
            }
            else
            {
                data = GetDataFromRequest(metaViewName, entityIds);
            }
            var dt = data.ToDataTable(DynamicEntityJSONDataSource.GetFieldColumns(Request.QueryString));

            return(GridExportHelper.ExportToXls(metaViewName, dt));
        }
        public void AlwaysReturnTheLastData(MarketDataType marketDataType, int quantity, bool sameTime)
        {
            // Arrange
            var securityCache = new SecurityCache();
            var quotes        = GenerateData(marketDataType, quantity, sameTime);

            // Act
            foreach (var quoteBar in quotes)
            {
                quoteBar.Symbol = Symbols.SPY;
                securityCache.AddData(quoteBar);
            }

            var lastData = securityCache.GetData();

            if (marketDataType == MarketDataType.QuoteBar)
            {
                Assert.IsNull(lastData);
            }
            else
            {
                Assert.True(lastData.Equals(quotes.Last()));
            }
        }
示例#21
0
        public void GetAllData_ReturnsListOfDataOnTargetCache()
        {
            var cache = new SecurityCache();

            cache.StoreData(new[]
            {
                new CustomDataBitcoinAlgorithm.Bitcoin {
                    Ask = 1m
                },
                new CustomDataBitcoinAlgorithm.Bitcoin {
                    Ask = 2m
                }
            }, typeof(CustomDataBitcoinAlgorithm.Bitcoin));

            var targetToModify = new SecurityCache();

            SecurityCache.ShareTypeCacheInstance(cache, targetToModify);

            var data = targetToModify.GetAll <CustomDataBitcoinAlgorithm.Bitcoin>().ToList();

            Assert.AreEqual(2, data.Count);
            Assert.AreEqual(1m, data[0].Ask);
            Assert.AreEqual(2m, data[1].Ask);
        }
示例#22
0
 public void Grant(SecurityProfile profile)
 {
     SecurityCache.AddSecurityProfile(profile);
 }
示例#23
0
        public ActionResult FormCan(string name, string permission)
        {
            var res = SecurityCache.FormCan(name, permission);

            return(Content(res.ToString()));
        }
示例#24
0
        public ActionResult Can(string group, string permission)
        {
            var res = SecurityCache.CheckPermission(group, permission);

            return(Content(res.ToString()));
        }
        private static TestCaseData[] GetSecurityCacheInitialStates()
        {
            var defaultInstance = new SecurityCache();

            var tradeTick = new SecurityCache();

            tradeTick.AddData(new Tick
            {
                Value    = 5,
                Quantity = 6,
                EndTime  = ReferenceTime,
                TickType = TickType.Trade
            });

            var quoteTick = new SecurityCache();

            quoteTick.AddData(new Tick
            {
                AskPrice = 1,
                AskSize  = 2,
                BidPrice = 3,
                BidSize  = 4,
                EndTime  = ReferenceTime,
                TickType = TickType.Quote
            });

            var openInterestTick = new SecurityCache();

            openInterestTick.AddData(new Tick
            {
                Value    = 24,
                EndTime  = ReferenceTime,
                TickType = TickType.OpenInterest
            });

            var openInterest = new SecurityCache();

            openInterest.AddData(new OpenInterest
            {
                Value   = 23,
                EndTime = ReferenceTime,
            });

            var tradeBar = new SecurityCache();

            tradeBar.AddData(new TradeBar
            {
                Open    = 7,
                High    = 8,
                Low     = 9,
                Close   = 10,
                Volume  = 11,
                EndTime = ReferenceTime
            });

            var quoteBar = new SecurityCache();

            quoteBar.AddData(new QuoteBar
            {
                Ask         = new Bar(12, 13, 14, 15),
                Bid         = new Bar(16, 17, 18, 19),
                LastAskSize = 20,
                LastBidSize = 21,
                Value       = 22,
                EndTime     = ReferenceTime
            });

            var fundamentals = new SecurityCache();

            fundamentals.AddData(new Fundamentals
            {
                Value = 23
            });

            return(new[]
            {
                new TestCaseData(defaultInstance, SecuritySeedData.None).SetName("Default Instance"),
                new TestCaseData(tradeTick, SecuritySeedData.TradeTick).SetName("Seeded w/ Trade Tick"),
                new TestCaseData(quoteTick, SecuritySeedData.QuoteTick).SetName("Seeded w/ Quote Tick"),
                new TestCaseData(openInterestTick, SecuritySeedData.OpenInterestTick).SetName("Seeded w/ OpenInterest Tick"),
                new TestCaseData(openInterest, SecuritySeedData.OpenInterest).SetName("Seeded w/ OpenInterest"),
                new TestCaseData(tradeBar, SecuritySeedData.TradeBar).SetName("Seeded w/ TradeBar"),
                new TestCaseData(quoteBar, SecuritySeedData.QuoteBar).SetName("Seeded w/ QuoteBar"),
                new TestCaseData(fundamentals, SecuritySeedData.Fundamentals).SetName("Seeded w/ Fundamentals")
            });
        }
        /// <summary>
        /// Deserialises an <see cref="XmlElement"/> containing security settings configuration.
        /// </summary>
        /// <param name="element">The <see cref="XmlElement"/> to deserialise.</param>
        public override void Deserialize(XmlElement element)
        {
            Type         = "Internal";
            DefaultRight = Util.GetEnumFromElementOrAttribute <SecurityRight>("defaultRight", element);

            foreach (XmlElement ele in element.SelectNodes("users/*"))
            {
                SecurityUser user = Util.CreateInstanceFromXmlName <SecurityUser>(ele.Name);
                if (user != null)
                {
                    user.Deserialize(ele);
                    Users.Add(user);
                }
            }

            foreach (XmlElement ele in element.SelectNodes("permissions/*"))
            {
                SecurityPermission permission = Util.CreateInstanceFromXmlName <SecurityPermission>(ele.Name);
                if (permission != null)
                {
                    permission.Deserialize(ele);
                    Permissions.Add(permission);
                }
            }

            foreach (XmlElement ele in element.SelectNodes("audit/*"))
            {
                SecurityLogger logger = Util.CreateInstanceFromXmlName <SecurityLogger>(ele.Name);
                if (logger != null)
                {
                    logger.Deserialize(ele);
                    AuditLoggers.Add(logger);
                }
            }

            XmlElement readerEl = element.SelectSingleNode("auditReader") as XmlElement;

            if (readerEl != null)
            {
                string xmlName             = readerEl.GetAttribute("type");
                SecurityAuditReader reader = Util.CreateInstanceFromXmlName <SecurityAuditReader>(xmlName);
                if (reader != null)
                {
                    reader.Deserialize(readerEl);
                    AuditReader = reader;
                }
            }

            XmlElement cacheEl = element.SelectSingleNode("cache") as XmlElement;

            if (cacheEl != null)
            {
                string        xmlName = cacheEl.GetAttribute("type");
                SecurityCache cache   = Util.CreateInstanceFromXmlName <SecurityCache>(xmlName);
                if (cache != null)
                {
                    cache.Deserialize(cacheEl);
                    Cache = cache;
                }
            }
        }
        public void AddDataEquity_OHLC_IgnoresQuoteBar()
        {
            var securityCache = new SecurityCache();
            var quoteBar      = new QuoteBar
            {
                Bid         = new Bar(101, 102, 103, 104),
                Ask         = new Bar(105, 106, 107, 108),
                LastAskSize = 109,
                LastBidSize = 110,
                EndTime     = ReferenceTime,
                Symbol      = Symbols.SPY
            };

            securityCache.AddData(quoteBar);

            var last = securityCache.GetData();

            Assert.IsNull(last);

            Assert.AreEqual(0, securityCache.High);
            Assert.AreEqual(0, securityCache.Close);
            Assert.AreEqual(0, securityCache.Low);
            Assert.AreEqual(0, securityCache.Open);
            Assert.AreEqual(0, securityCache.Volume);

            var actualQuoteBar = securityCache.GetData <QuoteBar>();

            Assert.IsNotNull(actualQuoteBar);
            Assert.AreEqual(108, securityCache.AskPrice);
            Assert.AreEqual(109, securityCache.AskSize);
            Assert.AreEqual(104, securityCache.BidPrice);
            Assert.AreEqual(110, securityCache.BidSize);

            var tradeBar = new TradeBar
            {
                Open    = 101,
                High    = 102,
                Low     = 103,
                Close   = 104,
                Volume  = 105,
                EndTime = ReferenceTime,
                Symbol  = Symbols.SPY
            };

            securityCache.AddData(tradeBar);

            last = securityCache.GetData();
            Assert.IsNotNull(last);

            var actualTradeBar = securityCache.GetData <TradeBar>();

            Assert.IsNotNull(actualTradeBar);
            Assert.AreEqual(102, securityCache.High);
            Assert.AreEqual(104, securityCache.Close);
            Assert.AreEqual(103, securityCache.Low);
            Assert.AreEqual(101, securityCache.Open);
            Assert.AreEqual(105, securityCache.Volume);

            // quote bar data should still be the same
            Assert.AreEqual(108, securityCache.AskPrice);
            Assert.AreEqual(109, securityCache.AskSize);
            Assert.AreEqual(104, securityCache.BidPrice);
            Assert.AreEqual(110, securityCache.BidSize);
        }
        public void EmitsMappingEventsBasedOnCurrentMapFileAndTime(DataMappingMode dataMappingMode, string mappingDate, bool delayed)
        {
            var config = new SubscriptionDataConfig(typeof(TradeBar),
                                                    Symbols.ES_Future_Chain,
                                                    Resolution.Daily,
                                                    TimeZones.NewYork,
                                                    TimeZones.NewYork,
                                                    true,
                                                    true,
                                                    false,
                                                    dataMappingMode: dataMappingMode);
            var symbolMaps = new List <SubscriptionDataConfig.NewSymbolEventArgs>();

            config.NewSymbol += (sender, args) => symbolMaps.Add(args);
            var time  = new DateTime(2013, 05, 28);
            var cache = new SecurityCache();

            cache.AddData(new Tick(time, config.Symbol, 20, 10));
            var timeProvider = new ManualTimeProvider(time);

            var futureTicker1 = "es vhle2yxr5blt";

            TestMapFileResolver.MapFile = new MapFile(Futures.Indices.SP500EMini, new []
            {
                new MapFileRow(Time.BeginningOfTime, Futures.Indices.SP500EMini, Exchange.CME),
                new MapFileRow(new DateTime(2013, 06, 01), futureTicker1, Exchange.CME, DataMappingMode.FirstDayMonth),
                new MapFileRow(new DateTime(2013, 06, 15), futureTicker1, Exchange.CME, DataMappingMode.OpenInterest),
                new MapFileRow(new DateTime(2013, 06, 22), futureTicker1, Exchange.CME, DataMappingMode.LastTradingDay),
            });

            IEnumerator <BaseData> enumerator;

            Assert.IsTrue(LiveAuxiliaryDataEnumerator.TryCreate(config, timeProvider, null, cache, new TestMapFileProvider(), TestGlobals.FactorFileProvider, time, out enumerator));

            // get's mapped right away!
            Assert.AreEqual(futureTicker1.ToUpper(), config.MappedSymbol);

            Assert.AreEqual(1, symbolMaps.Count);
            Assert.AreEqual(Symbols.ES_Future_Chain, symbolMaps[0].Old);
            Assert.AreEqual(Futures.Indices.SP500EMini, symbolMaps[0].Old.ID.Symbol);
            Assert.AreEqual(Symbols.ES_Future_Chain, symbolMaps[0].New);
            Assert.AreEqual(futureTicker1.ToUpper(), symbolMaps[0].New.Underlying.ID.ToString());

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);

            var expectedMappingDate = DateTime.ParseExact(mappingDate, DateFormat.EightCharacter, CultureInfo.InvariantCulture);

            if (delayed)
            {
                // we advance to the mapping date, without any new mapFile!
                timeProvider.Advance(expectedMappingDate.ConvertToUtc(config.ExchangeTimeZone) - timeProvider.GetUtcNow() + Time.LiveAuxiliaryDataOffset);
            }
            else
            {
                // just advance a day to show nothing happens until mapping time
                timeProvider.Advance(TimeSpan.FromDays(1));
            }

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);

            var futureTicker2 = "es vk2zrh843z7l";

            TestMapFileResolver.MapFile = new MapFile(Futures.Indices.SP500EMini, TestMapFileResolver.MapFile.Concat(
                                                          new []
            {
                new MapFileRow(new DateTime(2013, 09, 01), futureTicker2, Exchange.CME, DataMappingMode.FirstDayMonth),
                new MapFileRow(new DateTime(2013, 09, 14), futureTicker2, Exchange.CME, DataMappingMode.OpenInterest),
                new MapFileRow(new DateTime(2013, 09, 21), futureTicker2, Exchange.CME, DataMappingMode.LastTradingDay),
            }));

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);

            if (delayed)
            {
                // we got a new mapFile! advance the date and expect mapping to have happened
                timeProvider.Advance(TimeSpan.FromDays(1));
            }
            else
            {
                // we advance to the mapping date
                timeProvider.Advance(expectedMappingDate.ConvertToUtc(config.ExchangeTimeZone) - timeProvider.GetUtcNow() + Time.LiveAuxiliaryDataOffset);
            }

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);

            Assert.AreEqual(2, symbolMaps.Count);
            Assert.AreEqual(Symbols.ES_Future_Chain, symbolMaps[1].Old);
            Assert.AreEqual(futureTicker1.ToUpper(), symbolMaps[1].Old.Underlying.ID.ToString());
            Assert.AreEqual(Symbols.ES_Future_Chain, symbolMaps[1].New);
            Assert.AreEqual(futureTicker2.ToUpper(), symbolMaps[1].New.Underlying.ID.ToString());

            Assert.AreEqual(futureTicker2.ToUpper(), config.MappedSymbol);

            Assert.AreEqual(futureTicker2.ToUpper(), (enumerator.Current as SymbolChangedEvent).NewSymbol);
            Assert.AreEqual(futureTicker1.ToUpper(), (enumerator.Current as SymbolChangedEvent).OldSymbol);
            Assert.AreEqual(config.Symbol, (enumerator.Current as SymbolChangedEvent).Symbol);
            Assert.AreEqual(timeProvider.GetUtcNow().Date, (enumerator.Current as SymbolChangedEvent).Time);

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);
        }
示例#29
0
 public void Revoke(RevokeParameter token)
 {
     SecurityCache.Revoke(token.token);
 }
 public void SetUp()
 {
     _cache             = new SecurityCache();
     _dataTypesProvider = new RegisteredSecurityDataTypesProvider();
     _dataTypesProvider.RegisterType(typeof(TradeBar));
 }