protected void GetRoute()
        {
            _routeCancelToken?.Cancel();
            _routeCancelToken = new CancellationTokenSource();
            Route.Clear();

            int collisionMask;

            if (!Owner.TryGetComponent(out CollidableComponent collidableComponent))
            {
                collisionMask = 0;
            }
            else
            {
                collisionMask = collidableComponent.CollisionMask;
            }

            var startGrid = _mapManager.GetGrid(Owner.Transform.GridID).GetTileRef(Owner.Transform.GridPosition);
            var endGrid   = _mapManager.GetGrid(TargetGrid.GridID).GetTileRef(TargetGrid);;
            var access    = AccessReader.FindAccessTags(Owner);

            RouteJob = _pathfinder.RequestPath(new PathfindingArgs(
                                                   Owner.Uid,
                                                   access,
                                                   collisionMask,
                                                   startGrid,
                                                   endGrid,
                                                   PathfindingProximity
                                                   ), _routeCancelToken.Token);
        }
Example #2
0
        public void TestEmpty()
        {
            var reader = new AccessReader();

            Assert.That(reader.IsAllowed(new[] { "Foo" }), Is.True);
            Assert.That(reader.IsAllowed(new[] { "Bar" }), Is.True);
            Assert.That(reader.IsAllowed(new string[] {}), Is.True);
        }
Example #3
0
        public bool IsAllowed(AccessReader reader, ICollection <string> accessTags)
        {
            if (reader.DenyTags.Overlaps(accessTags))
            {
                // Sec owned by cargo.
                return(false);
            }

            return(!reader.Enabled || reader.AccessLists.Count == 0 || reader.AccessLists.Any(a => a.IsSubsetOf(accessTags)));
        }
Example #4
0
        public void TestDeny()
        {
            var reader = new AccessReader();

            reader.DenyTags.Add("A");

            Assert.That(reader.IsAllowed(new[] { "Foo" }), Is.True);
            Assert.That(reader.IsAllowed(new[] { "A" }), Is.False);
            Assert.That(reader.IsAllowed(new[] { "A", "Foo" }), Is.False);
            Assert.That(reader.IsAllowed(new string[] {}), Is.True);
        }
Example #5
0
        private void OnInit(EntityUid uid, AccessReader reader, ComponentInit args)
        {
            var allTags = reader.AccessLists.SelectMany(c => c).Union(reader.DenyTags);

            foreach (var level in allTags)
            {
                if (!_prototypeManager.HasIndex <AccessLevelPrototype>(level))
                {
                    Logger.ErrorS("access", $"Invalid access level: {level}");
                }
            }
        }
Example #6
0
        public void TestOneListTwoItems()
        {
            var reader = new AccessReader();

            reader.AccessLists.Add(new HashSet <string> {
                "A", "B"
            });

            Assert.That(reader.IsAllowed(new[] { "A" }), Is.False);
            Assert.That(reader.IsAllowed(new[] { "B" }), Is.False);
            Assert.That(reader.IsAllowed(new[] { "A", "B" }), Is.True);
            Assert.That(reader.IsAllowed(new string[] {}), Is.False);
        }
Example #7
0
        /// <summary>
        /// Get appropriate args for a particular entity
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static ReachableArgs GetArgs(IEntity entity)
        {
            var collisionMask = 0;

            if (entity.TryGetComponent(out IPhysicsComponent physics))
            {
                collisionMask = physics.CollisionMask;
            }

            var access       = AccessReader.FindAccessTags(entity);
            var visionRadius = entity.GetComponent <AiControllerComponent>().VisionRadius;

            return(new ReachableArgs(visionRadius, access, collisionMask));
        }
Example #8
0
        public void TestDenyList()
        {
            var reader = new AccessReader();

            reader.AccessLists.Add(new HashSet <string> {
                "A"
            });
            reader.DenyTags.Add("B");

            Assert.That(reader.IsAllowed(new[] { "A" }), Is.True);
            Assert.That(reader.IsAllowed(new[] { "B" }), Is.False);
            Assert.That(reader.IsAllowed(new[] { "A", "B" }), Is.False);
            Assert.That(reader.IsAllowed(new string[] {}), Is.False);
        }
        public bool CanTraverse(IEntity entity, PathfindingNode node)
        {
            if (entity.TryGetComponent(out IPhysicsComponent physics) &&
                (physics.CollisionMask & node.BlockedCollisionMask) != 0)
            {
                return(false);
            }

            var access = AccessReader.FindAccessTags(entity);

            foreach (var reader in node.AccessReaders)
            {
                if (!reader.IsAllowed(access))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #10
0
        // *****************************************************************
        // ****                     Properties                          ****
        // *****************************************************************
        //
        //
        #endregion//Properties


        #region Public Methods
        // *****************************************************************
        // ****                     Public Methods                      ****
        // *****************************************************************
        //
        //
        //
        //
        //
        //
        /// <summary>
        /// This function reads all lines in the audit trail file, generating fill event args and store them.
        /// In addition to that, it also collect the last most recent fill information and update the position for the next step.
        /// </summary>
        /// <param name="startDateTime"></param>
        /// <param name="endDateTime"></param>
        /// <returns></returns>
        public bool TryReadAuditTrailFills(DateTime startDateTime, DateTime endDateTime, AuditTrailFillHub auditTrailFillHub)
        {
            // This method will load the audit trail fills from TT given start and end date time automatically.
            // The results will be added to the audit trail fills dictionary.
            // It will also construct the fill hub name by user dictionary.

            // Get the target audit trail files to read. The file name format is AuditLog_yyyy-mm-dd_N.
            DateTime startDate;
            DateTime endDate;

            startDate = startDateTime.Subtract(startDateTime.TimeOfDay);
            while (startDate.DayOfWeek == DayOfWeek.Saturday || startDate.DayOfWeek == DayOfWeek.Sunday)
            {
                startDate = startDate.AddDays(-1);
            }
            endDate = endDateTime.Subtract(endDateTime.TimeOfDay).AddDays(1);
            while (endDate.DayOfWeek == DayOfWeek.Saturday || endDate.DayOfWeek == DayOfWeek.Sunday)
            {
                endDate = endDate.AddDays(1);
            }
            if (!System.IO.Directory.Exists(m_AuditTrailPath))
            {
                System.IO.Directory.CreateDirectory(m_AuditTrailPath);
            }
            string          pattern         = "AuditLog*.mdb";
            List <string>   fileList        = new List <string>();
            List <string>   targetFileList  = new List <string>();
            List <string>   targetTableList = new List <string>();
            List <DateTime> targetDateList  = new List <DateTime>();

            fileList.AddRange(System.IO.Directory.GetFiles(m_AuditTrailPath, pattern));
            int      dateDelimiterStart;
            int      dateDelimiterEnd;
            DateTime fileDate = DateTime.MinValue;
            string   fileDateString;

            // Loop through the file collection and choose the desired files.
            foreach (string fileName in fileList)
            {
                dateDelimiterEnd   = fileName.LastIndexOf("_");
                dateDelimiterStart = fileName.LastIndexOf("_", dateDelimiterEnd - 1);

                if (dateDelimiterStart < fileName.Length && dateDelimiterEnd < fileName.Length)
                {
                    fileDateString = fileName.Substring(dateDelimiterStart + 1, dateDelimiterEnd - dateDelimiterStart - 1);
                    if (DateTime.TryParseExact(fileDateString, "yyyy-MM-dd", null, System.Globalization.DateTimeStyles.None, out fileDate))
                    {
                        if (startDate <= fileDate && fileDate <= endDate)
                        {
                            Log.NewEntry(LogLevel.Minor, "Include the file name:{0}.", fileName);
                            targetFileList.Add(fileName);
                            targetTableList.Add(fileDate.ToString("MMMdd"));
                            targetDateList.Add(fileDate);
                        }
                        else
                        {
                            Log.NewEntry(LogLevel.Major, "Exclude the file name:{0}.", fileName);
                            continue;
                        }
                    }
                    else
                    {
                        Log.NewEntry(LogLevel.Major, "There is problem in parsing file date string:{0}.", fileDateString);
                        continue;
                    }
                }
                else
                {
                    Log.NewEntry(LogLevel.Major, "There is problem in parsing file name:{0}.", fileName);
                    continue;
                }
            }

            // Build the connections and load data from the file collection.
            m_FillEventArgsList.Clear();
            bool isBadRow;
            List <InstrumentKey> instrumentKeyList = new List <InstrumentKey>();
            bool readAllFillAccounts = false;

            if (auditTrailFillHub.HubName == string.Empty)
            {
                readAllFillAccounts = true;
            }
            for (int fileIndex = 0; fileIndex < targetFileList.Count; ++fileIndex)
            {
                // Read from the audit file.
                List <List <object> > dataCollections = new List <List <object> >();
                if (AccessReader.TryReadAccessFile(targetFileList[fileIndex], targetTableList[fileIndex], out dataCollections))
                {
                    // Get the information from the output. All the values are in object type.
                    int rowNumber = dataCollections.Count;
                    for (int rowIndex = 0; rowIndex < rowNumber; ++rowIndex)
                    {
                        isBadRow = false;

                        // The valid data types are explored in detail by test program.
                        string localTimeStamp = (string)dataCollections[rowIndex][ObjectListSchema.LocalTimeStamp];
                        string exchangeName   = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeName];
                        string orderStatus    = (string)dataCollections[rowIndex][ObjectListSchema.OrderStatus];
                        string orderAction    = (string)dataCollections[rowIndex][ObjectListSchema.OrderAction];
                        string orderSide      = (string)dataCollections[rowIndex][ObjectListSchema.OrderSide];
                        int    orderQty       = (int)dataCollections[rowIndex][ObjectListSchema.OrderQty];
                        string product        = (string)dataCollections[rowIndex][ObjectListSchema.Product];
                        string contract       = (string)dataCollections[rowIndex][ObjectListSchema.Contract];
                        string orderPrice     = (string)dataCollections[rowIndex][ObjectListSchema.OrderPrice];
                        string accountName    = (string)dataCollections[rowIndex][ObjectListSchema.AccountName];
                        string userName       = (string)dataCollections[rowIndex][ObjectListSchema.UserName];
                        string exchangeTime   = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeTime];
                        string exchangeDate   = (string)dataCollections[rowIndex][ObjectListSchema.ExchangeDate];
                        string tradeSource    = (string)dataCollections[rowIndex][ObjectListSchema.TradeSource];
                        string ttOrderKey     = (string)dataCollections[rowIndex][ObjectListSchema.TTOrderKey];
                        string ttSeriesKey    = (string)dataCollections[rowIndex][ObjectListSchema.TTSeriesKey];

                        // Check whether the account is desired.
                        if (!readAllFillAccounts && !accountName.Equals(m_FillHubName))
                        {
                            continue;
                        }

                        // Check whether the exchange name includes AlgoSE sub string.
                        if (exchangeName.Contains(m_ExchangeName_AlgoSE))
                        {
                            continue;
                        }

                        // Check whether it is a fill event.
                        if (!orderAction.Equals(m_Action_Fill) && !orderAction.Equals(m_Action_PartialFill))
                        {
                            continue;
                        }

                        // Check whether it is a OK status.
                        if (!orderStatus.Equals(m_OrderStatus_OK))
                        {
                            continue;
                        }

                        // Check whether the product type is future.
                        if (product.Equals(m_Product_AutoSpreader))
                        {
                            continue;
                        }

                        // Check whether the contract string contains Calendar string to avoid duplicate fills.
                        foreach (string specialString in m_Contract_Special)
                        {
                            if (contract.Contains(specialString))
                            {
                                isBadRow = true;
                                if (exchangeName.Contains("TOCOM") && specialString.Equals("/") && isBadRow)
                                {
                                    isBadRow = false;
                                }
                                break;
                            }
                        }
                        if (isBadRow)
                        {
                            continue;
                        }

                        // Try parse some necessary variables.
                        DateTime localDateTimeValid = DateTime.MinValue;
                        DateTime exchangeTimeValid  = DateTime.MinValue;
                        DateTime exchangeDateValid  = DateTime.MinValue;
                        double   fillPrice          = double.NaN;
                        if (!DateTime.TryParseExact(localTimeStamp, "HH:mm:ss.fff", null, System.Globalization.DateTimeStyles.None, out localDateTimeValid))
                        {
                            Log.NewEntry(LogLevel.Major, "Failed to parse the utc time of {0}.", localTimeStamp);
                            continue;
                        }
                        if (!DateTime.TryParseExact(exchangeTime, "HH:mm:ss.fff", null, System.Globalization.DateTimeStyles.None, out exchangeTimeValid))
                        {
                            Log.NewEntry(LogLevel.Major, "Failed to parse the exchange time of {0}.", exchangeTime);
                            continue;
                        }
                        if (!DateTime.TryParseExact(exchangeDate, "ddMMMyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out exchangeDateValid))
                        {
                            Log.NewEntry(LogLevel.Major, "Failed to parse the exchange time of {0}.", exchangeDate);
                            continue;
                        }
                        if (!double.TryParse(orderPrice, out fillPrice))
                        {
                            Log.NewEntry(LogLevel.Major, "Failed to parse the order price of {0}.", orderPrice);
                            continue;
                        }
                        localDateTimeValid = targetDateList[fileIndex].Add(localDateTimeValid.TimeOfDay);
                        exchangeTimeValid  = exchangeDateValid.Add(exchangeTimeValid.TimeOfDay);

                        // Edit the market.
                        int validEndIndex = exchangeName.LastIndexOf("-");
                        if (validEndIndex >= 0)
                        {
                            exchangeName = exchangeName.Substring(0, validEndIndex);
                        }

                        // Create fill.
                        Fill fill = new Fill();
                        fill.ExchangeTime = exchangeTimeValid;
                        //TimeZoneInfo localTimeZone = TimeZoneInfo.FindSystemTimeZoneById(m_LocalTimeZoneString);
                        //DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(localDateTimeValid, localTimeZone);
                        fill.LocalTime = localDateTimeValid;
                        fill.Price     = fillPrice;
                        fill.Qty       = orderSide.Equals(m_OrderSide_Buy) ? orderQty : (orderSide.Equals(m_OrderSide_Sell) ? -orderQty : 0);

                        // Create fill event args.
                        InstrumentKey instrumentKey = new InstrumentKey(exchangeName, TradingTechnologies.TTAPI.ProductType.Future, product, ttSeriesKey);
                        FillEventArgs fillEventArgs = new FillEventArgs();
                        fillEventArgs.Fill      = fill;
                        fillEventArgs.AccountID = accountName;
                        //fillEventArgs.FillKey = ttOrderKey;
                        fillEventArgs.Type            = FillType.Historic;
                        fillEventArgs.TTInstrumentKey = instrumentKey;

                        // Add the instrument key to the list.
                        if (startDateTime.AddSeconds(-3) <= localDateTimeValid && localDateTimeValid <= endDateTime.AddSeconds(3))
                        {
                            if (!TTConvert.CheckExistenceOfInstrumentKey(instrumentKeyList, instrumentKey))
                            {
                                instrumentKeyList.Add(instrumentKey);
                            }

                            // Add the fill event args to the list.
                            string rowInfo = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15}.", localTimeStamp, exchangeName, orderStatus, orderAction, orderSide, orderQty, product, contract, orderPrice, accountName, userName, exchangeTime, exchangeDate, tradeSource, ttOrderKey, ttSeriesKey);
                            Log.NewEntry(LogLevel.Minor, "Record:{0}", rowInfo);
                            m_FillEventArgsList.Add(fillEventArgs);
                        }
                    }
                }
                else
                {
                    Log.NewEntry(LogLevel.Major, "Failed to read access file with name:{0}.", targetFileList[fileIndex]);
                    continue;
                }

                Log.NewEntry(LogLevel.Minor, "Complete reading access file with name:{0}.", targetFileList[fileIndex]);
            }

            // Get the last local time of fill for each instrument in initial fill hub.
            m_NeededBookInstrumentList.Clear();
            //foreach (InstrumentKey ttKeyInWaitList in auditTrailFillHub.InitialWaitDictionary.Keys)
            //{
            //    // These fills that do not have books will be requested to create new books if possible. To ensure they have books, create them if necessary here.
            //    if (!auditTrailFillHub.TryCheckExistenceOfInstrumentKey(ttKeyInWaitList) && !TTConvert.CheckExistenceOfInstrumentKey(neededBookInstrumentList, ttKeyInWaitList))
            //    {
            //        neededBookInstrumentList.Add(ttKeyInWaitList);
            //    }
            //}

            // For the fills from the audit trail files, also get instruments that need books.
            foreach (InstrumentKey instrumentKeyInAuditTrail in instrumentKeyList)
            {
                if (!auditTrailFillHub.TryCheckExistenceOfInstrumentKey(instrumentKeyInAuditTrail) && !TTConvert.CheckExistenceOfInstrumentKey(m_NeededBookInstrumentList, instrumentKeyInAuditTrail))
                {
                    m_NeededBookInstrumentList.Add(instrumentKeyInAuditTrail);
                }
            }

            // Clear all trades in the waiting list because they are all included in the audit trail files.
            auditTrailFillHub.InitialWaitDictionary.Clear();

            // Create books if necessary.
            // The instrument that need book creation is those got from FillEventArgs from drop file and the new fills listened in the audit trail file.
            // It is crucial to get all the books ready before updating positions.
            foreach (InstrumentKey key in m_NeededBookInstrumentList)
            {
                OrderHubRequest creatFillBookRequest = new OrderHubRequest(OrderHubRequest.RequestType.RequestCreateFillBook);
                creatFillBookRequest.Data    = new object[1];
                creatFillBookRequest.Data[0] = key;
                auditTrailFillHub.HubEventEnqueue(creatFillBookRequest);
            }

            Log.NewEntry(LogLevel.Minor, "Complete loading audit trail fills.");
            return(true);
        }
Example #11
0
        public async Task TestTags()
        {
            var server = StartServer();
            await server.WaitAssertion(() =>
            {
                var system = EntitySystem.Get <AccessReaderSystem>();

                // test empty
                var reader = new AccessReader();
                Assert.That(system.IsAllowed(reader, new[] { "Foo" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "Bar" }), Is.True);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.True);

                // test deny
                reader = new AccessReader();
                reader.DenyTags.Add("A");
                Assert.That(system.IsAllowed(reader, new[] { "Foo" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "A" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "A", "Foo" }), Is.False);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.True);

                // test one list
                reader = new AccessReader();
                reader.AccessLists.Add(new HashSet <string> {
                    "A"
                });
                Assert.That(system.IsAllowed(reader, new[] { "A" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "B" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "A", "B" }), Is.True);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.False);

                // test one list - two items
                reader = new AccessReader();
                reader.AccessLists.Add(new HashSet <string> {
                    "A", "B"
                });
                Assert.That(system.IsAllowed(reader, new[] { "A" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "B" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "A", "B" }), Is.True);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.False);

                // test two list
                reader = new AccessReader();
                reader.AccessLists.Add(new HashSet <string> {
                    "A"
                });
                reader.AccessLists.Add(new HashSet <string> {
                    "B", "C"
                });
                Assert.That(system.IsAllowed(reader, new[] { "A" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "B" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "A", "B" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "C", "B" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "C", "B", "A" }), Is.True);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.False);

                // test deny list
                reader = new AccessReader();
                reader.AccessLists.Add(new HashSet <string> {
                    "A"
                });
                reader.DenyTags.Add("B");
                Assert.That(system.IsAllowed(reader, new[] { "A" }), Is.True);
                Assert.That(system.IsAllowed(reader, new[] { "B" }), Is.False);
                Assert.That(system.IsAllowed(reader, new[] { "A", "B" }), Is.False);
                Assert.That(system.IsAllowed(reader, new string[] { }), Is.False);
            });
        }
Example #12
0
        /// <summary>
        /// Searches an <see cref="AccessComponent"/> in the entity itself, in its active hand or in its ID slot.
        /// Then compares the found access with the configured access lists to see if it is allowed.
        /// </summary>
        /// <remarks>
        ///     If no access is found, an empty set is used instead.
        /// </remarks>
        /// <param name="entity">The entity to be searched for access.</param>
        public bool IsAllowed(AccessReader reader, EntityUid entity)
        {
            var tags = FindAccessTags(entity);

            return(IsAllowed(reader, tags));
        }