public override Task Execute() { var pendingOrders = _orderReader.GetPending().GroupBy(o => o.Instrument); foreach (var gr in pendingOrders) { if (!_assetDayOffService.ArePendingOrdersDisabled(gr.Key)) { continue; } foreach (var pendingOrder in gr) { try { _tradingEngine.CancelPendingOrder(pendingOrder.Id, OrderCloseReason.CanceledBySystem); } catch (Exception e) { _log.WriteErrorAsync(nameof(PendingOrdersCleaningService), $"Cancelling pending order {pendingOrder.Id}", pendingOrder.ToJson(), e); } } } return(Task.CompletedTask); }
public Task <List <string> > GetAllAccountIdsFiltered([FromBody] ActiveAccountsRequest request) { if (request.IsAndClauseApplied != null && (request.ActiveOrderAssetPairIds == null || request.ActivePositionAssetPairIds == null)) { throw new ArgumentException("isAndClauseApplied might be set only if both filters are set", nameof(request.IsAndClauseApplied)); } List <string> accountIdsByOrders = null; if (request.ActiveOrderAssetPairIds != null) { accountIdsByOrders = _orderReader.GetPending() .Where(x => request.ActiveOrderAssetPairIds.Count == 0 || request.ActiveOrderAssetPairIds.Contains(x.AssetPairId)) .Select(x => x.AccountId) .Distinct() .ToList(); } List <string> accountIdsByPositions = null; if (request.ActivePositionAssetPairIds != null) { accountIdsByPositions = _orderReader.GetPositions() .Where(x => request.ActivePositionAssetPairIds.Count == 0 || request.ActivePositionAssetPairIds.Contains(x.AssetPairId)) .Select(x => x.AccountId) .Distinct() .ToList(); } if (accountIdsByOrders == null && accountIdsByPositions != null) { return(Task.FromResult(accountIdsByPositions.OrderBy(x => x).ToList())); } if (accountIdsByOrders != null && accountIdsByPositions == null) { return(Task.FromResult(accountIdsByOrders.OrderBy(x => x).ToList())); } if (accountIdsByOrders == null && accountIdsByPositions == null) { return(Task.FromResult(_accountsCacheService.GetAll().Select(x => x.Id).OrderBy(x => x).ToList())); } if (request.IsAndClauseApplied ?? false) { return(Task.FromResult(accountIdsByOrders.Intersect(accountIdsByPositions) .OrderBy(x => x).ToList())); } return(Task.FromResult(accountIdsByOrders.Concat(accountIdsByPositions) .Distinct().OrderBy(x => x).ToList())); }
public List <OrderContract> GetPendingOrdersByVolume([FromQuery] decimal volume) { var result = new List <OrderContract>(); var orders = _ordersReader.GetPending(); foreach (var order in orders) { if (Math.Abs(order.Volume) >= volume) { result.Add(order.ToBaseContract()); } } return(result); }
private async Task Handle(BlockAccountsForDeletionCommand command, IEventPublisher publisher) { var executionInfo = await _operationExecutionInfoRepository.GetOrAddAsync( operationName : OperationName, operationId : command.OperationId, factory : () => new OperationExecutionInfo <DeleteAccountsOperationData>( operationName: OperationName, id: command.OperationId, lastModified: _dateService.Now(), data: new DeleteAccountsOperationData { State = OperationState.Initiated } )); //todo think how to remove state saving from commands handler here and for Withdrawal if (executionInfo.Data.SwitchState(OperationState.Initiated, OperationState.Started)) { var failedAccounts = new Dictionary <string, string>(); foreach (var accountId in command.AccountIds) { MarginTradingAccount account = null; try { account = _accountsCacheService.Get(accountId); } catch (Exception exception) { failedAccounts.Add(accountId, exception.Message); continue; } var positionsCount = _orderReader.GetPositions().Count(x => x.AccountId == accountId); if (positionsCount != 0) { failedAccounts.Add(accountId, $"Account contain {positionsCount} open positions which must be closed before account deletion."); continue; } var orders = _orderReader.GetPending().Where(x => x.AccountId == accountId).ToList(); if (orders.Any()) { var(failedToCloseOrderId, failReason) = ((string)null, (string)null); foreach (var order in orders) { try { _tradingEngine.CancelPendingOrder(order.Id, order.AdditionalInfo, command.OperationId, $"{nameof(DeleteAccountsCommandsHandler)}: force close all orders.", OrderCancellationReason.AccountInactivated); } catch (Exception exception) { failedToCloseOrderId = order.Id; failReason = exception.Message; break; } } if (failedToCloseOrderId != null) { failedAccounts.Add(accountId, $"Failed to close order [{failedToCloseOrderId}]: {failReason}."); continue; } } if (account.AccountFpl.WithdrawalFrozenMarginData.Any()) { await _log.WriteErrorAsync(nameof(DeleteAccountsCommandsHandler), nameof(BlockAccountsForDeletionCommand), account.ToJson(), new Exception("While deleting an account it contained some frozen withdrawal data. Account is deleted.")); } if (account.AccountFpl.UnconfirmedMarginData.Any()) { await _log.WriteErrorAsync(nameof(DeleteAccountsCommandsHandler), nameof(BlockAccountsForDeletionCommand), account.ToJson(), new Exception("While deleting an account it contained some unconfirmed margin data. Account is deleted.")); } if (account.Balance != 0) { await _log.WriteErrorAsync(nameof(DeleteAccountsCommandsHandler), nameof(BlockAccountsForDeletionCommand), account.ToJson(), new Exception("While deleting an account it's balance on side of TradingCore was non zero. Account is deleted.")); } if (!await UpdateAccount(account, true, r => failedAccounts.Add(accountId, r), command.Timestamp)) { continue; } } publisher.PublishEvent(new AccountsBlockedForDeletionEvent( operationId: command.OperationId, eventTimestamp: _dateService.Now(), failedAccountIds: failedAccounts )); _chaosKitty.Meow($"{nameof(BlockAccountsForDeletionCommand)}: " + "Save_OperationExecutionInfo: " + $"{command.OperationId}"); await _operationExecutionInfoRepository.Save(executionInfo); } }
public async Task Handle(ProductChangedEvent @event) { switch (@event.ChangeType) { case ChangeType.Creation: case ChangeType.Edition: if ([email protected]) { _log.WriteInfo(nameof(ProductChangedProjection), nameof(Handle), $"ProductChangedEvent received for productId: {@event.NewValue.ProductId}, but it was ignored because it has not been started yet."); return; } break; case ChangeType.Deletion: if ([email protected]) { _log.WriteInfo(nameof(ProductChangedProjection), nameof(Handle), $"ProductChangedEvent received for productId: {@event.OldValue.ProductId}, but it was ignored because it has not been started yet."); return; } break; default: throw new ArgumentOutOfRangeException(); } if (@event.ChangeType == ChangeType.Deletion) { CloseAllOrders(); ValidatePositions(@event.OldValue.ProductId); _assetPairsCache.Remove(@event.OldValue.ProductId); } else { if (@event.NewValue.IsDiscontinued) { CloseAllOrders(); RemoveQuoteFromCache(); } await _tradingInstrumentsManager.UpdateTradingInstrumentsCacheAsync(); var isAdded = _assetPairsCache.AddOrUpdate(AssetPair.CreateFromProduct(@event.NewValue, _mtSettings.DefaultLegalEntitySettings.DefaultLegalEntity)); if (@event.NewValue.TradingCurrency != AssetPairConstants.BaseCurrencyId) { _assetPairsCache.AddOrUpdate(AssetPair.CreateFromCurrency(@event.NewValue.TradingCurrency, _mtSettings.DefaultLegalEntitySettings.DefaultLegalEntity)); } //only for product if (isAdded) { await _scheduleSettingsCacheService.UpdateScheduleSettingsAsync(); } if (@event.ChangeType == ChangeType.Edition && @event.OldValue.IsTradingDisabled != @event.NewValue.IsTradingDisabled) { await HandleTradingDisabled(@event.NewValue, @event.Username); } } void RemoveQuoteFromCache() { var result = _quoteCache.RemoveQuote(@event.OldValue.ProductId); if (result != RemoveQuoteErrorCode.None) { _log.WriteWarning(nameof(ProductChangedProjection), nameof(RemoveQuoteFromCache), result.Message); } } void CloseAllOrders() { try { foreach (var order in _orderReader.GetPending() .Where(x => x.AssetPairId == @event.OldValue.ProductId)) { _tradingEngine.CancelPendingOrder(order.Id, null, null, OrderCancellationReason.InstrumentInvalidated); } } catch (Exception exception) { _log.WriteError(nameof(ProductChangedProjection), nameof(CloseAllOrders), exception); throw; } } void ValidatePositions(string assetPairId) { var positions = _orderReader.GetPositions(assetPairId); if (positions.Any()) { _log.WriteFatalError(nameof(ProductChangedProjection), nameof(ValidatePositions), new Exception( $"{positions.Length} positions are opened for [{assetPairId}], first: [{positions.First().Id}].")); } } }
public async Task Handle(AssetPairChangedEvent @event) { //deduplication is not required, it's ok if an object is updated multiple times if (@event.AssetPair?.Id == null) { await _log.WriteWarningAsync(nameof(AssetPairProjection), nameof(Handle), "AssetPairChangedEvent contained no asset pair id"); return; } if (IsDelete(@event)) { CloseAllOrders(); ValidatePositions(@event.AssetPair.Id); _assetPairsCache.Remove(@event.AssetPair.Id); } else { if (@event.AssetPair.IsDiscontinued) { CloseAllOrders(); } _assetPairsCache.AddOrUpdate(new AssetPair( id: @event.AssetPair.Id, name: @event.AssetPair.Name, baseAssetId: @event.AssetPair.BaseAssetId, quoteAssetId: @event.AssetPair.QuoteAssetId, accuracy: @event.AssetPair.Accuracy, legalEntity: @event.AssetPair.LegalEntity, basePairId: @event.AssetPair.BasePairId, matchingEngineMode: @event.AssetPair.MatchingEngineMode.ToType <MatchingEngineMode>(), stpMultiplierMarkupBid: @event.AssetPair.StpMultiplierMarkupBid, stpMultiplierMarkupAsk: @event.AssetPair.StpMultiplierMarkupAsk, isSuspended: @event.AssetPair.IsSuspended, isFrozen: @event.AssetPair.IsFrozen, isDiscontinued: @event.AssetPair.IsDiscontinued )); } await _scheduleSettingsCacheService.UpdateSettingsAsync(); void CloseAllOrders() { try { foreach (var order in _orderReader.GetPending().Where(x => x.AssetPairId == @event.AssetPair.Id)) { _tradingEngine.CancelPendingOrder(order.Id, null, @event.OperationId, null, OrderCancellationReason.InstrumentInvalidated); } } catch (Exception exception) { _log.WriteError(nameof(AssetPairProjection), nameof(CloseAllOrders), exception); throw; } } void ValidatePositions(string assetPairId) { var positions = _orderReader.GetPositions(assetPairId); if (positions.Any()) { _log.WriteFatalError(nameof(AssetPairProjection), nameof(ValidatePositions), new Exception($"{positions.Length} positions are opened for [{assetPairId}], first: [{positions.First().Id}].")); } } }