Example #1
0
        public async Task WorksCorrectlyForOneThread_InvalidateCacheAsync()
        {
            // arrange
            var(h3, y1) = MakeFakeHttpClientHandler();

            // act

            var httpBuilder   = HttpClientGenerator.BuildForUrl("http://fake.host");
            var cacheManager  = new ClientCacheManager();
            var testInterface = httpBuilder
                                .WithCachingStrategy(new AttributeBasedCachingStrategy())
                                .WithAdditionalDelegatingHandler(h3)
                                .Create(cacheManager)
                                .Generate <ITestInterface>();

            var result = await testInterface.TestMethodWithCache();

            var result1 = await testInterface.TestMethodWithCache();

            cacheManager.InvalidateCacheAsync().Wait();
            var result2 = await testInterface.TestMethodWithCache();

            cacheManager.Dispose();
            // assert
            result.Should().Be(_result1Str);
            result1.Should().Be(_result1Str);
            result2.Should().Be(_result2Str);
        }
Example #2
0
        protected override void Load(ContainerBuilder builder)
        {
            var dataReaderHttpGenerator = HttpClientGenerator
                                          .BuildForUrl(_settings.Services.DataReader.Url)
                                          .WithApiKey(_settings.Services.DataReader.ApiKey)
                                          .Create();

            builder.RegisterInstance(dataReaderHttpGenerator.Generate <Backend.Contracts.IAccountsApi>())
            .As <Backend.Contracts.IAccountsApi>()
            .SingleInstance();
            builder.RegisterInstance(dataReaderHttpGenerator.Generate <Backend.Contracts.ITradeMonitoringReadingApi>())
            .As <Backend.Contracts.ITradeMonitoringReadingApi>()
            .SingleInstance();
            builder.RegisterInstance(dataReaderHttpGenerator.Generate <Backend.Contracts.IAccountHistoryApi>())
            .As <Backend.Contracts.IAccountHistoryApi>()
            .SingleInstance();
            builder.RegisterInstance(dataReaderHttpGenerator.Generate <Backend.Contracts.IAssetPairsReadingApi>())
            .As <Backend.Contracts.IAssetPairsReadingApi>()
            .SingleInstance();

            builder.RegisterLykkeServiceClient(_settings.Services.ClientAccount.Url);

            builder.Register <IEmailSender>(ctx => new EmailSenderClient(_settings.Services.EmailSender.Url, _log))
            .SingleInstance();
        }
Example #3
0
        private static T GetApi <T>(ClientSettings apiSettings)
        {
            var generator = HttpClientGenerator.BuildForUrl(apiSettings.ServiceUrl)
                            .WithoutCaching().WithoutRetries().Create();

            return(generator.Generate <T>());
        }
        /// <summary>
        /// Registers <see cref="IChestClient"/> in service collection.
        /// </summary>
        /// <param name="services">The collection of service descriptors.</param>
        /// <param name="serviceUrl">The service URL.</param>
        /// <param name="apiKey">The authentication API key.</param>
        /// <param name="timeout">The request timeout in second.</param>
        public static void AddChestClient(this IServiceCollection services, string serviceUrl, string apiKey = null,
                                          int?timeout = null)
        {
            if (string.IsNullOrWhiteSpace(serviceUrl))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(serviceUrl));
            }

            var builder = HttpClientGenerator
                          .BuildForUrl(serviceUrl);

            if (timeout.HasValue)
            {
                builder.WithTimeout(TimeSpan.FromSeconds(timeout.Value));
            }

            if (!string.IsNullOrEmpty(apiKey))
            {
                builder.WithApiKey(apiKey);
            }

            var clientGenerator = builder.Create();

            services.AddSingleton <IChestClient>(provider => new ChestClientAdapter(clientGenerator));
        }
Example #5
0
        public async Task Always_WorksWithoutTimeout()
        {
            // arrange
            var log            = new List <string>();
            var fakeHttpClient = new FakeHttpClientHandler(r =>
            {
                Thread.Sleep(333);

                return(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ByteArrayContent(Encoding.UTF8.GetBytes("the result"))
                });
            });
            TimeSpan timeout = TimeSpan.FromMilliseconds(50);

            // act && assert

            var httpClient = HttpClientGenerator.BuildForUrl("http://google.com")
                             //Should be skipped because of timeout
                             .WithRetriesStrategy(new LinearRetryStrategy(TimeSpan.FromSeconds(1), 20))
                             .Create()
                             .Generate <IRealInterface>();

            var result = await httpClient.GetHtmlAsync();
        }
        /// <summary>
        /// Registers <see cref="ISmartVouchersClient"/> in Autofac container using <see cref="SmartVouchersServiceClientSettings"/>.
        /// </summary>
        /// <param name="builder">Autofac container builder.</param>
        /// <param name="settings">SmartVouchers client settings.</param>
        /// <param name="builderConfigure">Optional <see cref="HttpClientGeneratorBuilder"/> configure handler.</param>
        public static void RegisterSmartVouchersClient(
            [NotNull] this ContainerBuilder builder,
            [NotNull] SmartVouchersServiceClientSettings settings,
            [CanBeNull] Func <HttpClientGeneratorBuilder, HttpClientGeneratorBuilder> builderConfigure)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrWhiteSpace(settings.ServiceUrl))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(SmartVouchersServiceClientSettings.ServiceUrl));
            }

            var clientBuilder = HttpClientGenerator.BuildForUrl(settings.ServiceUrl)
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper());

            clientBuilder = builderConfigure?.Invoke(clientBuilder) ?? clientBuilder.WithoutRetries();

            builder.RegisterInstance(new SmartVouchersClient(clientBuilder.Create()))
            .As <ISmartVouchersClient>()
            .SingleInstance();
        }
        private static IAccountsApi GetClient()
        {
            var generator = HttpClientGenerator.BuildForUrl(
                SettingsUtil.Settings.MarginTradingAccountManagementServiceClient.ServiceUrl)
                            .WithoutCaching().WithoutRetries().Create();

            return(generator.Generate <IAccountsApi>());
        }
        private void InitializeClient()
        {
            var clientBuilder = HttpClientGenerator.BuildForUrl(_serviceUrl)
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper())
                                .WithRetriesStrategy(new LinearRetryStrategy(_timeout, _retriesCount));

            Api = clientBuilder.Create().Generate <IPushProviderApi>();
        }
 private static async Task CheckOvernightSwapApiWorking(HttpClientGenerator clientGenerator)
 {
     /*var client = clientGenerator.Generate<IAccountsApi>();
      * await client.List().Dump();
      * await client.Insert(new AccountContract {Id = "smth"}).Dump();
      * await client.GetByClientAndId(TODO, "smth").Dump();
      * await client.Update("smth", new AccountContract {Id = "smth", ClientId = "some client"}).Dump();
      * await client.Delete(TODO, "smth").Dump();*/
 }
Example #10
0
        /// <summary>C-tor</summary>
        public PaymentIntegrationPluginClient(string serviceUrl)
        {
            var clientBuilder = HttpClientGenerator.BuildForUrl(serviceUrl)
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper())
                                .WithoutRetries();
            var httpClientGenerator = clientBuilder.Create();

            Api = httpClientGenerator.Generate <IPaymentIntegrationPluginApi>();
        }
        private static async Task Run()
        {
            var clientGenerator = new HttpClientGenerator("http://localhost:5007", null, null);//"TestClient");

            await CheckOvernightSwapApiWorking(clientGenerator);

            // todo check other apis

            Console.WriteLine("Successfuly finished");
        }
Example #12
0
        private static async Task CheckPositionsAsync(HttpClientGenerator generator)
        {
            var api       = generator.Generate <IPositionsApi>();
            var positions = await api.ListAsync().Dump();

            var anyPosition = positions.FirstOrDefault();

            if (anyPosition != null)
            {
                await api.CloseAsync(anyPosition.Id,
                                     new PositionCloseRequest { Comment = "111", Originator = OriginatorTypeContract.Investor }).Dump();
            }
        }
Example #13
0
        private static async Task CheckOrdersAsync(HttpClientGenerator generator)
        {
            var api    = generator.Generate <IOrdersApi>();
            var orders = await api.ListAsync().Dump();

            if (orders.Any())
            {
                await api.CancelAsync(orders.First().Id, new OrderCancelRequest()
                {
                    AdditionalInfo = "test"
                });
            }
        }
Example #14
0
        // NOTE: Use Demo instances for tests
        private static async Task Run()
        {
            var retryStrategy = new LinearRetryStrategy(TimeSpan.FromSeconds(10), 50);
            var generator     = HttpClientGenerator.BuildForUrl("http://localhost:5000").WithApiKey("margintrading")
                                .WithRetriesStrategy(retryStrategy).Create();

            await CheckMarginParametersAsync(generator);

            //await CheckAccountsAsync(generator);
            //await CheckOrdersAsync(generator);
            //await CheckPricesAsync(generator);

            Console.WriteLine("Successfuly finished");
        }
        private static async Task CheckPositionEventsPaginatedApiAsync(HttpClientGenerator generator)
        {
            var api = generator.Generate <IPositionEventsApi>();

            var accountId = "AA0012";
            var assetId   = "ADIDAS_AG";

            var positionEvents = await api.PositionHistoryByPages(accountId, assetId, skip : 0, take : 20);

            if (!positionEvents.Contents.Any())
            {
                throw new Exception("Failed to retrieve position history events.");
            }
        }
        /// <summary>C-tor</summary>
        public PayrexxIntegrationClient(
            string payrexxBaseUrl,
            string instance,
            string apiKey)
        {
            var clientBuilder = HttpClientGenerator.BuildForUrl(payrexxBaseUrl)
                                .WithAdditionalDelegatingHandler(new QueryParamsHandler(instance, apiKey))
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper());

            clientBuilder = clientBuilder.WithoutRetries();
            var httpClientGenerator = clientBuilder.Create();

            Api = httpClientGenerator.Generate <IPayrexxIntegrationApi>();
        }
Example #17
0
        protected override void Load(ContainerBuilder builder)
        {
            var settingsClientGeneratorBuilder = HttpClientGenerator
                                                 .BuildForUrl(_settings.CurrentValue.MarginTradingSettingsServiceClient.ServiceUrl)
                                                 .WithServiceName <LykkeErrorResponse>(
                $"MT Settings [{_settings.CurrentValue.MarginTradingSettingsServiceClient.ServiceUrl}]");

            if (!string.IsNullOrWhiteSpace(_settings.CurrentValue.MarginTradingSettingsServiceClient.ApiKey))
            {
                settingsClientGeneratorBuilder = settingsClientGeneratorBuilder
                                                 .WithApiKey(_settings.CurrentValue.MarginTradingSettingsServiceClient.ApiKey);
            }

            var settingsClientGenerator = settingsClientGeneratorBuilder.Create();

            builder.RegisterInstance(settingsClientGenerator.Generate <IAssetsApi>());
            builder.RegisterInstance(settingsClientGenerator.Generate <ITradingConditionsApi>());
            builder.RegisterInstance(settingsClientGenerator.Generate <ITradingInstrumentsApi>());
            builder.RegisterInstance(settingsClientGenerator.Generate <IScheduleSettingsApi>());

            var mtCoreClientGenerator = HttpClientGenerator
                                        .BuildForUrl(_settings.CurrentValue.MtBackendServiceClient.ServiceUrl)
                                        .WithApiKey(_settings.CurrentValue.MtBackendServiceClient.ApiKey)
                                        .WithServiceName <LykkeErrorResponse>(
                $"MT Trading Core [{_settings.CurrentValue.MtBackendServiceClient.ServiceUrl}]")
                                        .Create();

            builder.RegisterInstance(mtCoreClientGenerator.Generate <IOrdersApi>());
            builder.RegisterInstance(mtCoreClientGenerator.Generate <IPositionsApi>());
            builder.RegisterInstance(mtCoreClientGenerator.Generate <IAccountsApi>());

            var mtTradingHistoryClientGenerator = HttpClientGenerator
                                                  .BuildForUrl(_settings.CurrentValue.TradingHistoryClient.ServiceUrl)
                                                  .WithServiceName <LykkeErrorResponse>("MT Core History Service")
                                                  .WithOptionalApiKey(_settings.CurrentValue.TradingHistoryClient.ApiKey)
                                                  .Create();

            builder.RegisterInstance(mtTradingHistoryClientGenerator.Generate <IDealsApi>());

            var mdmClientGenerator = HttpClientGenerator
                                     .BuildForUrl(_settings.CurrentValue.MdmServiceClient.ServiceUrl)
                                     .WithServiceName <LykkeErrorResponse>("Mdm Service")
                                     .WithOptionalApiKey(_settings.CurrentValue.MdmServiceClient.ApiKey)
                                     .Create();

            builder.RegisterInstance(mdmClientGenerator.Generate <IBrokerSettingsApi>());

            builder.Populate(_services);
        }
Example #18
0
        private static async Task Run()
        {
            var clientGenerator = HttpClientGenerator.BuildForUrl("http://localhost:5010").Create();

            await CheckAssetPairsApiWorking(clientGenerator);
            await CheckAssetsApiWorking(clientGenerator);
            await CheckMarketsApiWorking(clientGenerator);
            await CheckScheduleSettingsApiWorking(clientGenerator);
            await CheckServiceMaintenanceApiWorking(clientGenerator);
            await CheckTradingConditionsApiWorking(clientGenerator);
            await CheckTradingInstrumentsApiWorking(clientGenerator);
            await CheckTradingRoutesApiWorking(clientGenerator);

            Console.WriteLine("Successfully finished");
        }
        private HttpClientGenerator BuildAccountManagementClientGenerator(IComponentContext ctx)
        {
            var accountManagementClientGeneratorBuilder = HttpClientGenerator
                                                          .BuildForUrl(_settings.CurrentValue.AccountsManagementServiceClient.ServiceUrl)
                                                          .WithAdditionalDelegatingHandler(ctx.Resolve <HttpCorrelationHandler>())
                                                          .WithServiceName <LykkeErrorResponse>(
                $"MT Account Management [{_settings.CurrentValue.AccountsManagementServiceClient.ServiceUrl}]");

            if (!string.IsNullOrWhiteSpace(_settings.CurrentValue.AccountsManagementServiceClient.ApiKey))
            {
                accountManagementClientGeneratorBuilder = accountManagementClientGeneratorBuilder
                                                          .WithApiKey(_settings.CurrentValue.AccountsManagementServiceClient.ApiKey);
            }

            return(accountManagementClientGeneratorBuilder.Create());
        }
        private HttpClientGenerator BuildSettingsClientGenerator(IComponentContext ctx)
        {
            var settingsClientGeneratorBuilder = HttpClientGenerator
                                                 .BuildForUrl(_settings.CurrentValue.SettingsServiceClient.ServiceUrl)
                                                 .WithAdditionalDelegatingHandler(ctx.Resolve <HttpCorrelationHandler>())
                                                 .WithServiceName <LykkeErrorResponse>(
                $"MT Settings [{_settings.CurrentValue.SettingsServiceClient.ServiceUrl}]")
                                                 .WithRetriesStrategy(new LinearRetryStrategy(TimeSpan.FromMilliseconds(300), 3));

            if (!string.IsNullOrWhiteSpace(_settings.CurrentValue.SettingsServiceClient.ApiKey))
            {
                settingsClientGeneratorBuilder = settingsClientGeneratorBuilder
                                                 .WithApiKey(_settings.CurrentValue.SettingsServiceClient.ApiKey);
            }

            return(settingsClientGeneratorBuilder.Create());
        }
Example #21
0
        public async Task ShouldLogRequestResponse()
        {
            // Arrange

            var fakeHttpClientHandler = new FakeHttpClientHandler(r =>
                                                                  new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content = new StringContent("testError")
            }
                                                                  );
            var logFactory = new Mock <ILogFactory>();
            var log        = new Mock <ILog>();

            logFactory
            .Setup(x => x.CreateLog(It.IsAny <object>()))
            .Returns(log.Object);

            var client = HttpClientGenerator.BuildForUrl("http://fake.host")
                         .WithoutCaching()
                         .WithoutRetries()
                         .WithRequestErrorLogging(logFactory.Object)
                         .WithAdditionalDelegatingHandler(fakeHttpClientHandler)
                         .Create()
                         .Generate <ITestInterface>();

            // Act

            try
            {
                await client.TestMethod();
            }
            catch (ApiException ex) when(ex.StatusCode == HttpStatusCode.BadRequest)
            {
            }

            // Arrange

            log.Verify(x =>
                       x.Log <LogEntryParameters>(
                           It.Is <LogLevel>(v => v == LogLevel.Warning),
                           It.IsAny <EventId>(),
                           It.IsAny <LogEntryParameters>(),
                           It.IsAny <Exception>(),
                           It.IsAny <Func <LogEntryParameters, Exception, string> >()),
                       Times.Exactly(2));
        }
Example #22
0
        private Process StartChest()
        {
            var path = string.Format(
                CultureInfo.InvariantCulture,
                "..{0}..{0}..{0}..{0}Chest{0}Chest.csproj",
                Path.DirectorySeparatorChar);

            Process.Start(
                new ProcessStartInfo("dotnet", $"run -p {path} --connectionStrings:chest \"{_connectionString}\"")
            {
                UseShellExecute = true,
            });

            var processId       = default(int);
            var clientGenerator = HttpClientGenerator
                                  .BuildForUrl(ServiceUrl)
                                  .Create();

            var client = clientGenerator.Generate <IIsAlive>();

            var attempt = 0;

            while (true)
            {
                Thread.Sleep(500);
                try
                {
                    throw new NotImplementedException();//todo it's all not working..
                    var response = client.Get().GetAwaiter().GetResult();
                    processId = response.ProcessId;
                    break;
                }
                catch (HttpRequestException)
                {
                    if (++attempt >= 20)
                    {
                        throw;
                    }
                }
            }

            return(Process.GetProcessById(processId));
        }
Example #23
0
        protected override void Load(ContainerBuilder builder)
        {
            var services = new ServiceCollection();

            services.RegisterMtDataReaderClientsPair(
                HttpClientGenerator.BuildForUrl(_settings.CurrentValue.MtDataReaderDemoServiceClient.ServiceUrl)
                .WithApiKey(_settings.CurrentValue.MtDataReaderDemoServiceClient.ApiKey)
                .Create(),
                HttpClientGenerator.BuildForUrl(_settings.CurrentValue.MtDataReaderLiveServiceClient.ServiceUrl)
                .WithApiKey(_settings.CurrentValue.MtDataReaderLiveServiceClient.ApiKey)
                .Create());

            builder.RegisterLykkeServiceClient(_settings.CurrentValue.ClientAccountServiceClient.ServiceUrl);

            var personalDataServiceMock = new Mock <IPersonalDataService>(MockBehavior.Strict);

            builder.RegisterInstance(personalDataServiceMock.Object).As <IPersonalDataService>();

            builder.Populate(services);
        }
        public static void AddMtCoreDalRepositories(this IServiceCollection services,
                                                    string mtCoreAccountManagementEndpoint,
                                                    string mtCoreAccountsApiKey,
                                                    bool backofficeSupportMode)
        {
            if (backofficeSupportMode)
            {
                services.AddSingleton <IAccountsMgmtApi, EmptyAccountsApiStub>();

                return;
            }

            var mtCoreAccountsMgmtClientGenerator = HttpClientGenerator
                                                    .BuildForUrl(mtCoreAccountManagementEndpoint)
                                                    .WithServiceName <MtCoreHttpErrorResponse>("MT Core Account Management Service")
                                                    .WithOptionalApiKey(mtCoreAccountsApiKey)
                                                    .WithoutRetries()
                                                    .Create();

            services.AddSingleton(mtCoreAccountsMgmtClientGenerator.Generate <IAccountsMgmtApi>());
        }
Example #25
0
        /// <summary>
        /// Registers <see cref="IEncryptedFileStorageClient"/> in Autofac container using <see cref="EncryptedFileStorageServiceClientSettings"/>.
        /// </summary>
        /// <param name="builder">Autofac container builder.</param>
        /// <param name="settings">EncryptedFileStorage client settings.</param>
        /// <param name="builderConfigure">Optional <see cref="HttpClientGeneratorBuilder"/> configure handler.</param>
        public static void RegisterEncryptedFileStorageClient(
            [NotNull] this ContainerBuilder builder,
            [NotNull] EncryptedFileStorageServiceClientSettings settings,
            [CanBeNull] Func <HttpClientGeneratorBuilder, HttpClientGeneratorBuilder> builderConfigure)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (string.IsNullOrWhiteSpace(settings.ServiceUrl))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(EncryptedFileStorageServiceClientSettings.ServiceUrl));
            }

            var clientBuilder = HttpClientGenerator.BuildForUrl(settings.ServiceUrl)
                                .WithAdditionalCallsWrapper(new ExceptionHandlerCallsWrapper());

            var apiKey = Environment.GetEnvironmentVariable("EfsApiKey");

            if (string.IsNullOrEmpty(apiKey))
            {
                apiKey = settings.ApiKey;
            }

            if (!string.IsNullOrWhiteSpace(apiKey))
            {
                clientBuilder = clientBuilder.WithApiKey(apiKey);
            }

            clientBuilder = builderConfigure?.Invoke(clientBuilder) ?? clientBuilder.WithoutRetries();

            builder.RegisterInstance(new EncryptedFileStorageClient(clientBuilder.Create()))
            .As <IEncryptedFileStorageClient>()
            .SingleInstance();
        }
Example #26
0
        public async Task WorksCorrectlyForManyThreads_InvalidateCacheAsync()
        {
            // arrange
            var(h3, y1) = MakeFakeHttpClientHandler();

            var bag           = new ConcurrentBag <List <string> >();
            var httpBuilder   = HttpClientGenerator.BuildForUrl("http://fake.host");
            var cacheManager  = new ClientCacheManager();
            var testInterface = httpBuilder
                                .WithCachingStrategy(new AttributeBasedCachingStrategy())
                                .WithAdditionalDelegatingHandler(h3)
                                .Create(cacheManager)
                                .Generate <ITestInterface>();

            var cacheModifyingTasks = Enumerable
                                      .Range(0, 100)
                                      .Select(x => Task.Factory.StartNew(async() =>
            {
                var list    = new List <string>(2);
                var result1 = await testInterface.TestMethodWithCache();
                await cacheManager.InvalidateCacheAsync();
                var result2 = await testInterface.TestMethodWithCache();

                list.Add($"{Thread.CurrentThread.Name} {result1}");
                list.Add($"{Thread.CurrentThread.Name} {result2}");
                bag.Add(list);
            }).Unwrap());

            // act

            await Task.WhenAll(cacheModifyingTasks);

            cacheManager.Dispose();
            var results   = bag.ToArray().SelectMany(x => x);
            var res2Count = results.Count(x => x.Contains(_result2Str));

            // assert
            res2Count.Should().BeGreaterThan(0);
        }
        private static async Task CheckOrderEventsPaginatedApiAsync(HttpClientGenerator generator)
        {
            var api = generator.Generate <IOrderEventsApi>();

            var statuses = new[]
            {
                OrderStatusContract.Executed,
                OrderStatusContract.ExecutionStarted,
            }.ToList();
            var someOrderEvents = await api.OrderHistoryByPages(new OrderEventsFilterRequest
            {
                CreatedTimeStart = DateTime.Parse("2019-01-27T05:27:02.133"),
                CreatedTimeEnd   = DateTime.Parse("2019-01-28T05:27:02.133"),
                Statuses         = statuses,
            }, null);

            var countFalse = someOrderEvents.Contents.Count(x => !statuses.Contains(x.Status));

            if (countFalse != 0)
            {
                throw new Exception($"Failed items: {countFalse}");
            }
        }
Example #28
0
 private static async Task CheckPricesAsync(HttpClientGenerator generator)
 {
     var api = generator.Generate <IPricesApi>();
     await api.GetBestAsync(new InitPricesBackendRequest { AssetIds = new[] { "EURUSD" } }).Dump();
 }
 private static async Task CheckDealsApiAsync(HttpClientGenerator generator)
 {
     var api   = generator.Generate <IDealsApi>();
     var deals = await api.List("AA1000", "ADIDAS_AG").Dump();
 }
Example #30
0
        // NOTE: Use Demo instances for tests
        private static async Task Run()
        {
            var services      = new ServiceCollection();
            var builder       = new ContainerBuilder();
            var retryStrategy = new LinearRetryStrategy(TimeSpan.FromSeconds(10), 50);

            services.RegisterMtBackendClient(HttpClientGenerator.BuildForUrl("http://localhost:5000")
                                             .WithApiKey("margintrading").WithRetriesStrategy(retryStrategy).Create());
            services.RegisterMtDataReaderClient(HttpClientGenerator.BuildForUrl("http://localhost:5008")
                                                .WithApiKey("margintrading").WithRetriesStrategy(retryStrategy).Create());
            builder.Populate(services);
            var container     = builder.Build();
            var backendClient = container.Resolve <IMtBackendClient>();

            await backendClient.ScheduleSettings.ListExclusions().Dump();

            var excl = await backendClient.ScheduleSettings.CreateExclusion(new DayOffExclusionInputContract
            {
                AssetPairRegex = "lol",
                Start          = DateTime.Now.AddDays(-1),
                End            = DateTime.Now.Date,
                IsTradeEnabled = false,
            }).Dump();

            var id = excl.Id;
            var ex = await backendClient.ScheduleSettings.GetExclusion(id).Dump();

            ex.AssetPairRegex = "^btc";
            await backendClient.ScheduleSettings.UpdateExclusion(id, ex).Dump();

            await backendClient.ScheduleSettings.GetExclusion(id).Dump();

            await backendClient.ScheduleSettings.ListCompiledExclusions().Dump();

            await backendClient.ScheduleSettings.DeleteExclusion(id).Dump();

            await backendClient.ScheduleSettings.GetExclusion(id).Dump();

            var s = await backendClient.ScheduleSettings.GetSchedule().Dump();

            s.AssetPairsWithoutDayOff.Add("BTCRABBIT");
            await backendClient.ScheduleSettings.SetSchedule(s).Dump();

            s.AssetPairsWithoutDayOff.Remove("BTCRABBIT");
            await backendClient.ScheduleSettings.SetSchedule(s).Dump();

            var assetPairSettingsInputContract = new AssetPairContract
            {
                Id                     = "BTCUSD.test",
                BasePairId             = "BTCUSD",
                LegalEntity            = "LYKKETEST",
                StpMultiplierMarkupBid = 0.9m,
                StpMultiplierMarkupAsk = 1.1m,
                MatchingEngineMode     = MatchingEngineModeContract.MarketMaker,
                Name                   = "BTCUSD.test name",
                Accuracy               = 123,
                BaseAssetId            = "BTC",
                QuoteAssetId           = "USD",
            };

            await backendClient.AssetPairsEdit.Delete("BTCUSD.test").Dump();

            var result = await backendClient.AssetPairsEdit.Insert("BTCUSD.test", assetPairSettingsInputContract)
                         .Dump();

            CheckAssetPair(result, assetPairSettingsInputContract);

            assetPairSettingsInputContract.MatchingEngineMode = MatchingEngineModeContract.Stp;
            var result2 = await backendClient.AssetPairsEdit.Update("BTCUSD.test", assetPairSettingsInputContract)
                          .Dump();

            CheckAssetPair(result2, assetPairSettingsInputContract);


            var dataReaderClient = container.Resolve <IMtDataReaderClient>();

            var list = await dataReaderClient.AssetPairsRead.List().Dump();

            var ours = list.First(e => e.Id == "BTCUSD.test");

            CheckAssetPair(ours, assetPairSettingsInputContract);

            var get = await dataReaderClient.AssetPairsRead.Get("BTCUSD.test").Dump();

            CheckAssetPair(get, assetPairSettingsInputContract);

            var nonexistentGet = await dataReaderClient.AssetPairsRead.Get("nonexistent").Dump();

            nonexistentGet.RequiredEqualsTo(null, nameof(nonexistentGet));

            var getByMode = await dataReaderClient.AssetPairsRead.List("LYKKETEST", MatchingEngineModeContract.Stp)
                            .Dump();

            var ours2 = getByMode.First(e => e.Id == "BTCUSD.test");

            CheckAssetPair(ours2, assetPairSettingsInputContract);

            var getByOtherMode = await dataReaderClient.AssetPairsRead
                                 .List("LYKKETEST", MatchingEngineModeContract.MarketMaker).Dump();

            getByOtherMode.Count(e => e.Id == "BTCUSD.test").RequiredEqualsTo(0, "getByOtherMode.Count");

            var result3 = await backendClient.AssetPairsEdit.Delete("BTCUSD.test").Dump();

            CheckAssetPair(result3, assetPairSettingsInputContract);

            var nonexistentDelete = await backendClient.AssetPairsEdit.Delete("nonexistent").Dump();

            nonexistentDelete.RequiredEqualsTo(null, nameof(nonexistentDelete));

            #region TradeMonitoring

            var assetSumary = await dataReaderClient.TradeMonitoringRead.AssetSummaryList().Dump();

            var openPositions = await dataReaderClient.TradeMonitoringRead.OpenPositions().Dump();

            var openPosition = openPositions.FirstOrDefault();
            if (openPosition != null)
            {
                string clientId = openPosition.ClientId;
                var    openPositionsByClient =
                    await dataReaderClient.TradeMonitoringRead.OpenPositionsByClient(clientId).Dump();
            }

            var openPositionsByDate = await dataReaderClient.TradeMonitoringRead
                                      .OpenPositionsByDate(DateTime.UtcNow.AddDays(-30), DateTime.UtcNow).Dump();

            var openPositionsByVolume = await dataReaderClient.TradeMonitoringRead.OpenPositionsByVolume(100).Dump();

            var pendingOrders = await dataReaderClient.TradeMonitoringRead.PendingOrders().Dump();

            var pendingOrder = pendingOrders.FirstOrDefault();
            if (pendingOrder != null)
            {
                string clientId = pendingOrder.ClientId;
                var    pendingOrdersByClient =
                    await dataReaderClient.TradeMonitoringRead.PendingOrdersByClient(clientId).Dump();
            }

            var pendingOrdersByDate = await dataReaderClient.TradeMonitoringRead
                                      .PendingOrdersByDate(DateTime.UtcNow.AddDays(-30), DateTime.UtcNow).Dump();

            var pendingOrdersByVolume = await dataReaderClient.TradeMonitoringRead.PendingOrdersByVolume(100).Dump();

            var orderBooksByInstrument = await dataReaderClient.TradeMonitoringRead.OrderBooksByInstrument("BTCUSD");

            #endregion

            var accountAssetPairs = await dataReaderClient.AccountAssetPairsRead
                                    .List()
                                    .Dump();

            var firstAccountAssetPair  = accountAssetPairs.First();
            var secondAccountAssetPair = await dataReaderClient.AccountAssetPairsRead
                                         .Get(firstAccountAssetPair.TradingConditionId, firstAccountAssetPair.BaseAssetId,
                                              firstAccountAssetPair.Instrument)
                                         .Dump();

            firstAccountAssetPair.Should().BeEquivalentTo(secondAccountAssetPair);

            var accountAssetPairsGetByTradingCondition = await dataReaderClient.AccountAssetPairsRead
                                                         .Get(firstAccountAssetPair.TradingConditionId, firstAccountAssetPair.BaseAssetId)
                                                         .Dump();

            foreach (var accountAssetPair in accountAssetPairsGetByTradingCondition)
            {
                var item = accountAssetPairs
                           .Single(x => x.TradingConditionId == accountAssetPair.TradingConditionId &&
                                   x.BaseAssetId == accountAssetPair.BaseAssetId &&
                                   x.Instrument == accountAssetPair.Instrument);
                item.Should().BeEquivalentTo(accountAssetPair);
            }

            firstAccountAssetPair.OvernightSwapLong = 0.1m;
            var updatedAccountAssetPair = await backendClient.TradingConditionsEdit
                                          .InsertOrUpdateAccountAsset(firstAccountAssetPair)
                                          .Dump();

            updatedAccountAssetPair.Result.Should().BeEquivalentTo(firstAccountAssetPair);

            var tc = await backendClient.TradingConditionsEdit.InsertOrUpdate(
                new Contracts.TradingConditions.TradingConditionContract
            {
                Id          = "LYKKETEST",
                LegalEntity = "LYKKEVA",
                IsDefault   = false,
                Name        = "Test Trading Condition",
            }).Dump();

            tc.Result.Id.RequiredEqualsTo("LYKKETEST", "tc.Result.Id");

            var ag = await backendClient.TradingConditionsEdit.InsertOrUpdateAccountGroup(
                new Contracts.TradingConditions.AccountGroupContract
            {
                BaseAssetId           = "BTC",
                TradingConditionId    = tc.Result.Id,
                DepositTransferLimit  = 0.1m,
                ProfitWithdrawalLimit = 0.2m,
                MarginCall            = 0.3m,
                StopOut = 0.4m
            })
                     .Dump();

            ag.Result.StopOut.RequiredEqualsTo(0.4m, "ag.Result.StopOut");

            var aa = await backendClient.TradingConditionsEdit.InsertOrUpdateAccountAsset(new AccountAssetPairContract
            {
                Instrument         = "TSTLKK",
                BaseAssetId        = "BTC",
                TradingConditionId = tc.Result.Id
            })
                     .Dump();

            aa.Result.Instrument.RequiredEqualsTo("TSTLKK", "aa.Result.Instrument");

            var ai = await backendClient.TradingConditionsEdit.AssignInstruments(
                new Contracts.TradingConditions.AssignInstrumentsContract
            {
                BaseAssetId        = "BTC",
                TradingConditionId = tc.Result.Id,
                Instruments        = new string[] { "TSTLKK" }
            })
                     .Dump();

            ai.IsOk.RequiredEqualsTo(true, "ai.IsOk");

            var tclist = await dataReaderClient.TradingConditionsRead.List().Dump();

            await dataReaderClient.TradingConditionsRead.Get(tclist.First().Id).Dump();

            var manualCharge = await backendClient.AccountsBalance.ChargeManually(
                new Contracts.AccountBalance.AccountChargeManuallyRequest
            {
                ClientId  = "232b3b04-7479-44e7-a6b3-ac131d8e6ccd",
                AccountId = "d_f4c745f19c834145bcf2d6b5f1a871f3",
                Amount    = 1,
                Reason    = "API TEST"
            })
                               .Dump();

            var accountGroups = await dataReaderClient.AccountGroups.List().Dump();

            var accountGroup1 = accountGroups.FirstOrDefault();
            if (accountGroup1 != null)
            {
                var accountGroup =
                    (await dataReaderClient.AccountGroups.GetByBaseAsset(accountGroup1.TradingConditionId,
                                                                         accountGroup1.BaseAssetId)).Dump();
                accountGroup.Should().BeEquivalentTo(accountGroup1);
            }

            var assetPairs = await dataReaderClient.Dictionaries.AssetPairs().Dump();

            var matchingEngines = await dataReaderClient.Dictionaries.MatchingEngines().Dump();

            var orderTypes = await dataReaderClient.Dictionaries.OrderTypes().Dump();


            var routes = await dataReaderClient.Routes.List().Dump();

            var route1 = routes.FirstOrDefault();
            if (route1 != null)
            {
                var route = await dataReaderClient.Routes.GetById(route1.Id).Dump();

                route.Should().BeEquivalentTo(route1);
            }

            var isEnabled =
                await dataReaderClient.Settings.IsMarginTradingEnabled("232b3b04-7479-44e7-a6b3-ac131d8e6ccd");

            Console.WriteLine("Successfuly finished");
        }