Beispiel #1
0
        /// <inheritdoc />
        public void ScheduleNext()
        {
            //need to know in which OvernightMarginJobType we are now and the moment of next change
            var platformTradingSchedule = _scheduleSettingsCacheService.GetPlatformTradingSchedule();

            _overnightMarginParameterContainer.SetOvernightMarginParameterState(false);

            var      currentDateTime = _dateService.Now();
            DateTime nextStart;

            (DateTime Warn, DateTime Start, DateTime End)operatingInterval = default;

            //no disabled trading schedule items.. doing nothing
            if (platformTradingSchedule.All(x => x.Enabled())
                //OR no disabled intervals in current compilation, schedule recheck
                || !TryGetOperatingInterval(platformTradingSchedule, currentDateTime, out operatingInterval))
            {
                nextStart = currentDateTime.Date.AddDays(1);
            }
            //schedule warning
            else if (currentDateTime < operatingInterval.Warn)
            {
                nextStart = operatingInterval.Warn;
            }
            //schedule overnight margin parameter start
            else if (currentDateTime < operatingInterval.Start)
            {
                HandleOvernightMarginWarnings();
                nextStart = operatingInterval.Start;
            }
            //schedule overnight margin parameter drop
            else if (currentDateTime < operatingInterval.End)
            {
                _overnightMarginParameterContainer.SetOvernightMarginParameterState(true);
                nextStart = operatingInterval.End;

                PlanEodJob(operatingInterval.Start, operatingInterval.End, currentDateTime);
            }
            else
            {
                _log.WriteFatalErrorAsync(nameof(OvernightMarginService), nameof(ScheduleNext),
                                          new Exception(
                                              $"Incorrect platform trading schedule! Need to fix it and restart the service. Check time: [{currentDateTime:s}], detected operation interval: [{operatingInterval.ToJson()}]"))
                .Wait();
                return;
            }

            _log.WriteInfo(nameof(OvernightMarginService), nameof(ScheduleNext),
                           $"Planning next check to [{nextStart:s}]."
                           + $" Current margin parameter state: [{_overnightMarginParameterContainer.GetOvernightMarginParameterState()}]."
                           + $" Check time: [{currentDateTime:s}]."
                           + (operatingInterval != default ? $" Detected operation interval: [{operatingInterval.ToJson()}]." : ""));
            JobManager.AddJob(ScheduleNext, s => s
                              .WithName(nameof(OvernightMarginService)).NonReentrant().ToRunOnceAt(nextStart));
        }
Beispiel #2
0
        /// <inheritdoc />
        public async Task <string> MakeTradingDataSnapshot(DateTime tradingDay, string correlationId, SnapshotStatus status = SnapshotStatus.Final)
        {
            if (!_scheduleSettingsCacheService.TryGetPlatformCurrentDisabledInterval(out var disabledInterval))
            {
                //TODO: remove later (if everything will work and we will never go to this branch)
                _scheduleSettingsCacheService.MarketsCacheWarmUp();

                if (!_scheduleSettingsCacheService.TryGetPlatformCurrentDisabledInterval(out disabledInterval))
                {
                    throw new Exception(
                              $"Trading should be stopped for whole platform in order to make trading data snapshot. Current schedule: {_scheduleSettingsCacheService.GetPlatformTradingSchedule()?.ToJson()}");
                }
            }

            if (disabledInterval.Start.AddDays(-1) > tradingDay.Date || disabledInterval.End < tradingDay.Date)
            {
                throw new Exception(
                          $"{nameof(tradingDay)}'s Date component must be from current disabled interval's Start -1d to End: [{disabledInterval.Start.AddDays(-1)}, {disabledInterval.End}].");
            }

            if (Lock.CurrentCount == 0)
            {
                throw new InvalidOperationException("Trading data snapshot creation is already in progress");
            }

            // We must be sure all messages have been processed by history brokers before starting current state validation.
            // If one or more queues contain not delivered messages the snapshot can not be created.
            _queueValidationService.ThrowExceptionIfQueuesNotEmpty(true);

            // Before starting snapshot creation the current state should be validated.
            var validationResult = await _snapshotValidationService.ValidateCurrentStateAsync();

            if (!validationResult.IsValid)
            {
                var ex = new InvalidOperationException(
                    $"The trading data snapshot might be corrupted. The current state of orders and positions is incorrect. Check the dbo.BlobData table for more info: container {LykkeConstants.MtCoreSnapshotBlobContainer}, correlationId {correlationId}");
                await _log.WriteFatalErrorAsync(nameof(SnapshotService),
                                                nameof(MakeTradingDataSnapshot),
                                                validationResult.ToJson(),
                                                ex);

                await _blobRepository.WriteAsync(LykkeConstants.MtCoreSnapshotBlobContainer, correlationId, validationResult);
            }
            else
            {
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          "The current state of orders and positions is correct.");
            }

            await Lock.WaitAsync();

            try
            {
                var orders     = _orderReader.GetAllOrders();
                var ordersJson = orders.Select(o => o.ConvertToSnapshotContract(_orderReader, status)).ToJson();
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Preparing data... {orders.Length} orders prepared.");

                var positions     = _orderReader.GetPositions();
                var positionsJson = positions.Select(p => p.ConvertToSnapshotContract(_orderReader, status)).ToJson();
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Preparing data... {positions.Length} positions prepared.");

                var accountStats = _accountsCacheService.GetAll();
                var accountsJson = accountStats.Select(a => a.ConvertToSnapshotContract(status)).ToJson();
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Preparing data... {accountStats.Count} accounts prepared.");

                var bestFxPrices     = _fxRateCacheService.GetAllQuotes();
                var bestFxPricesData = bestFxPrices.ToDictionary(q => q.Key, q => q.Value.ConvertToContract()).ToJson();
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Preparing data... {bestFxPrices.Count} best FX prices prepared.");

                var bestPrices     = _quoteCacheService.GetAllQuotes();
                var bestPricesData = bestPrices.ToDictionary(q => q.Key, q => q.Value.ConvertToContract()).ToJson();
                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Preparing data... {bestPrices.Count} best trading prices prepared.");

                var msg = $"TradingDay: {tradingDay:yyyy-MM-dd}, Orders: {orders.Length}, positions: {positions.Length}, accounts: {accountStats.Count}, best FX prices: {bestFxPrices.Count}, best trading prices: {bestPrices.Count}.";

                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Starting to write trading data snapshot. {msg}");

                var snapshot = new TradingEngineSnapshot(
                    tradingDay,
                    correlationId,
                    _dateService.Now(),
                    ordersJson: ordersJson,
                    positionsJson: positionsJson,
                    accountsJson: accountsJson,
                    bestFxPricesJson: bestFxPricesData,
                    bestTradingPricesJson: bestPricesData,
                    status: status);

                await _tradingEngineSnapshotsRepository.AddAsync(snapshot);

                await _log.WriteInfoAsync(nameof(SnapshotService), nameof(MakeTradingDataSnapshot),
                                          $"Trading data snapshot was written to the storage. {msg}");

                return($"Trading data snapshot was written to the storage. {msg}");
            }
            finally
            {
                Lock.Release();
            }
        }