Esempio n. 1
0
        public async Task <AccountHistoryResponse> ByTypes([FromQuery] AccountHistoryRequest request)
        {
            request.From = request.From?.ToUniversalTime();
            request.To   = request.To?.ToUniversalTime();
            var clientAccountIds = string.IsNullOrEmpty(request.AccountId)
                ? (await _accountsRepository.GetAllAsync(request.ClientId)).Select(item => item.Id).ToArray()
                : new[] { request.AccountId };

            var accounts = (await _accountsHistoryRepository.GetAsync(clientAccountIds, request.From, request.To))
                           .Where(item => item.Type != AccountHistoryType.OrderClosed);

            var orders =
                (await _ordersHistoryRepository.GetHistoryAsync(request.ClientId, clientAccountIds, request.From,
                                                                request.To))
                .Where(item => item.OpenDate != null &&  // remove cancel pending order rows created before OrderUpdateType was introduced
                       item.OrderUpdateType == OrderUpdateType.Close);

            var openPositions = await _ordersSnapshotReaderService.GetActiveByAccountIdsAsync(clientAccountIds);

            return(new AccountHistoryResponse
            {
                Account = accounts.Select(AccountHistoryExtensions.ToBackendContract)
                          .OrderByDescending(item => item.Date).ToArray(),
                OpenPositions = openPositions.Select(OrderExtensions.ToBackendHistoryContract)
                                .OrderByDescending(item => item.OpenDate).ToArray(),
                PositionsHistory = orders.Select(OrderHistoryExtensions.ToBackendHistoryContract)
                                   .OrderByDescending(item => item.OpenDate).ToArray(),
            });
        }
Esempio n. 2
0
        public override void Start()
        {
            var accounts = _repository.GetAllAsync().GetAwaiter().GetResult()
                           .Select(MarginTradingAccount.Create).GroupBy(x => x.ClientId).ToDictionary(x => x.Key, x => x.ToArray());

            _accountsCacheService.InitAccountsCache(accounts);
            _console.WriteLine($"InitAccountsCache (clients count:{accounts.Count})");

            base.Start();
        }
Esempio n. 3
0
        public async Task OvernightSwapCalculation_Success()
        {
            _bestPriceConsumer.SendEvent(this,
                                         new BestPriceChangeEventArgs(new InstrumentBidAskPair {
                Instrument = "BTCUSD", Bid = 9000M, Ask = 9010M
            }));

            await _accountAssetsRepository.AddOrReplaceAsync(new AccountAssetPair
            {
                TradingConditionId  = MarginTradingTestsUtils.TradingConditionId,
                BaseAssetId         = "USD",
                Instrument          = "BTCUSD",
                LeverageInit        = 100,
                LeverageMaintenance = 150,
                SwapLong            = 100,
                SwapShort           = 100,
                OvernightSwapLong   = 1,
                OvernightSwapShort  = 1
            });

            await _accountAssetsManager.UpdateAccountAssetsCache();

            var accountId = (await _fakeMarginTradingAccountsRepository.GetAllAsync("1"))
                            .First(x => x.ClientId == "1" && x.BaseAssetId == "USD").Id;

            _ordersCache.ActiveOrders.Add(new Order
            {
                Id                 = "1",
                AccountId          = accountId,
                Instrument         = "BTCUSD",
                ClientId           = "1",
                TradingConditionId = "1",
                AccountAssetId     = "USD",
                Volume             = 1,
                OpenDate           = new DateTime(2017, 01, 01, 20, 50, 0),
                CloseDate          = new DateTime(2017, 01, 02, 20, 50, 0),
                MatchedOrders      = new MatchedOrderCollection(new List <MatchedOrder> {
                    new MatchedOrder()
                    {
                        Volume = 1
                    }
                }),
                LegalEntity = "LYKKETEST",
            });

            var accountBalance = (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance;

            _overnightSwapService.CalculateAndChargeSwaps();

            var calc = _overnightSwapCache.GetAll().First();

            Assert.AreEqual(24.68493151M, calc.Value);
            Assert.True(calc.IsSuccess);
            Assert.AreEqual(accountBalance - 24.68493151M, (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance);
        }
Esempio n. 4
0
        public async Task <MarginTradingAccount[]> CreateDefaultAccounts(string clientId, string tradingConditionsId = null)
        {
            var existingAccounts = (await _accountsRepository.GetAllAsync(clientId)).ToList();

            if (existingAccounts.Any())
            {
                var accounts = existingAccounts.Select(MarginTradingAccount.Create).ToArray();
                _accountsCacheService.UpdateAccountsCache(clientId, accounts);
                return(accounts);
            }

            if (string.IsNullOrEmpty(tradingConditionsId))
            {
                tradingConditionsId = GetTradingConditions();
            }

            var baseAssets = GetBaseAssets(tradingConditionsId);

            var newAccounts = new List <MarginTradingAccount>();

            foreach (var baseAsset in baseAssets)
            {
                try
                {
                    var account = await CreateAccount(clientId, baseAsset, tradingConditionsId);

                    await _repository.AddAsync(account);

                    await _rabbitMqNotifyService.AccountCreated(account);

                    newAccounts.Add(account);
                }
                catch (Exception e)
                {
                    await _log.WriteErrorAsync(nameof(AccountManager), "Create default accounts",
                                               $"clientId={clientId}, tradingConditionsId={tradingConditionsId}", e);
                }
            }

            await ProcessAccountsSetChange(clientId, newAccounts);

            return(newAccounts.ToArray());
        }
Esempio n. 5
0
 public async Task <IEnumerable <DataReaderAccountBackendContract> > GetAllAccounts()
 {
     return((await _accountsRepository.GetAllAsync())
            .Select(item => ToBackendContract(item, _dataReaderSettings.IsLive)));
 }
Esempio n. 6
0
        public async Task OvernightSwapCalculation_Success()
        {
            var dsMock = Mock.Get(Container.Resolve <IDateService>());

            dsMock.Setup(d => d.Now()).Returns(new DateTime(2017, 1, 2));

            await _accountAssetsRepository.AddOrReplaceAsync(new AccountAssetPair
            {
                TradingConditionId  = MarginTradingTestsUtils.TradingConditionId,
                BaseAssetId         = "USD",
                Instrument          = "BTCUSD",
                LeverageInit        = 100,
                LeverageMaintenance = 150,
                SwapLong            = 100,
                SwapShort           = 100,
                OvernightSwapLong   = 1,
                OvernightSwapShort  = 1
            });

            await _accountAssetsManager.UpdateAccountAssetsCache();

            var accountId = (await _fakeMarginTradingAccountsRepository.GetAllAsync("1"))
                            .First(x => x.ClientId == "1" && x.BaseAssetId == "USD").Id;

            _ordersCache.ActiveOrders.Add(new Order
            {
                Id                 = "1",
                AccountId          = accountId,
                Instrument         = "BTCUSD",
                ClientId           = "1",
                TradingConditionId = "1",
                AccountAssetId     = "USD",
                Volume             = 1,
                OpenDate           = new DateTime(2017, 01, 01, 20, 50, 0),
                MatchedOrders      = new MatchedOrderCollection(new List <MatchedOrder> {
                    new MatchedOrder()
                    {
                        Volume = 1
                    }
                }),
                LegalEntity = "LYKKETEST",
            });

            _ordersCache.ActiveOrders.Add(new Order
            {
                Id                 = "2",
                AccountId          = accountId,
                Instrument         = "BTCUSD",
                ClientId           = "1",
                TradingConditionId = "1",
                AccountAssetId     = "USD",
                Volume             = 1,
                OpenDate           = new DateTime(2017, 01, 02, 20, 50, 0),
                MatchedOrders      = new MatchedOrderCollection(new List <MatchedOrder> {
                    new MatchedOrder()
                    {
                        Volume = 1
                    }
                }),
                LegalEntity = "LYKKETEST",
            });

            const decimal swapValue = 0.00273973M;

            var initialAccountBalance = (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance;

            _overnightSwapService.CalculateAndChargeSwaps();

            var calculations = _overnightSwapCache.GetAll();

            Assert.AreEqual(1, calculations.Count);             //only order 1 should be calculated
            var singleCalc = calculations.First();

            Assert.AreEqual(swapValue, singleCalc.Value);
            Assert.True(singleCalc.IsSuccess);
            Assert.AreEqual(initialAccountBalance - swapValue, (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance);

            //move few hours later and calculate again
            dsMock.Setup(d => d.Now()).Returns(new DateTime(2017, 1, 2, 2, 0, 0));

            //nothing should change
            calculations = _overnightSwapCache.GetAll();
            Assert.AreEqual(1, calculations.Count);
            Assert.AreEqual(initialAccountBalance - swapValue, (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance);

            _overnightSwapService.CalculateAndChargeSwaps();

            //move to next day and calculate again
            dsMock.Setup(d => d.Now()).Returns(new DateTime(2017, 1, 3));

            _overnightSwapService.CalculateAndChargeSwaps();

            calculations = _overnightSwapCache.GetAll();
            Assert.AreEqual(2, calculations.Count);             // both order 1 and order 2 should be calculated
            Assert.AreEqual(initialAccountBalance - swapValue * 3,
                            (await _fakeMarginTradingAccountsRepository.GetAsync(accountId)).Balance);
        }