Ejemplo n.º 1
0
        public void Login()
        {
            // Arrange
            var userLogin = new Contracts.UserLogin()
            {
                Email    = "*****@*****.**",
                Password = "******"
            };
            var user = new Database.User()
            {
                Id        = Guid.NewGuid(),
                Email     = userLogin.Email,
                FirstName = "Unit",
                LastName  = "Test",
                Role      = Database.Role.Trader
            };

            user.UpdatePassword(userLogin.Password);
            _dbContext.Add(user);
            _dbContext.SaveChanges();
            _configurationMock.SetupGet(c => c[It.Is <string>(cv => cv == "JWT-IssuerSigningKey")]).Returns("aYPg2QjKQBY4Uqx8");

            // Act
            var loggedInUser = _userService.Login(userLogin);

            // Assert
            _configurationMock.VerifyGet(c => c["JWT-IssuerSigningKey"], Times.Once());
            Assert.Equal(loggedInUser.Email, userLogin.Email);
        }
Ejemplo n.º 2
0
        public void GetAllInstruments()
        {
            // Arrange
            var instrument1 = new Database.Instrument()
            {
                Name = Contracts.InstrumentName.EUR_USD
            };
            var granularity1 = new Database.InstrumentGranularity()
            {
                Id          = Guid.NewGuid(),
                Instrument  = instrument1,
                Granularity = Contracts.Granularity.H1,
                State       = Database.GranularityState.New
            };

            instrument1.Granularities.Add(granularity1);
            _dbContext.Add(instrument1);

            var instrument2 = new Database.Instrument()
            {
                Name = Contracts.InstrumentName.NZD_USD
            };
            var granularity2 = new Database.InstrumentGranularity()
            {
                Id          = Guid.NewGuid(),
                Instrument  = instrument2,
                Granularity = Contracts.Granularity.M1,
                State       = Database.GranularityState.Tradeable
            };

            instrument2.Granularities.Add(granularity2);
            _dbContext.Add(instrument2);

            _dbContext.SaveChanges();

            // Act
            var instrumentGranularities = _instrumentService.GetAllInstruments();

            // Assert
            instrumentGranularities = instrumentGranularities.OrderBy(instrument => instrument.Name);
            Assert.Equal(2, instrumentGranularities.Count());
            Assert.Equal(instrument1.Name, instrumentGranularities.ElementAt(0).Name);
            Assert.Single(instrumentGranularities.ElementAt(0).Granularities);
            Assert.Equal(granularity1.Granularity, instrumentGranularities.ElementAt(0).Granularities.ElementAt(0).Granularity);
            Assert.Equal(instrument2.Name, instrumentGranularities.ElementAt(1).Name);
            Assert.Single(instrumentGranularities.ElementAt(1).Granularities);
            Assert.Equal(granularity2.Granularity, instrumentGranularities.ElementAt(1).Granularities.ElementAt(0).Granularity);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Create a new connection for the user
        /// </summary>
        /// <param name="userid">Id of the user to create the connection to</param>
        /// <param name="connectionToCreate">The connection object to create</param>
        /// <returns>The created connection</returns>
        public async Task <Contracts.Connection.Connection> CreateConnectionForUser(Guid userid, Contracts.Connection.ConnectionCreation connectionToCreate)
        {
            // First make sure that the connection is ok
            var connectionTest = _mapper.Map <Contracts.Connection.ConnectionTest>(connectionToCreate);
            var testResult     = TestConnection(connectionTest);

            if (!testResult.AccountIds.Contains(connectionToCreate.ExternalAccountId))
            {
                throw new ProblemDetailsException(
                          System.Net.HttpStatusCode.BadRequest,
                          $"The account id '{connectionToCreate.ExternalAccountId}' doesn't exist in the connection."
                          );
            }

            // If it is then
            // 1. Save the connection to the DB
            var connectionToDb = _mapper.Map <Database.Connection.Connection>(connectionToCreate);

            connectionToDb.Type  = testResult.Type;
            connectionToDb.Owner = GetUserFromDb(userid);
            _dbContext.Add(connectionToDb);
            _dbContext.SaveChanges();

            // 2. Save to token to keyvault
            await _connectionsSecretService.CreateConnectionSecret(connectionToDb.Id, connectionToCreate.Secret);

            // Return created connection
            return(_mapper.Map <Contracts.Connection.Connection>(connectionToDb));
        }
Ejemplo n.º 4
0
        public async void CheckInstrumentGranularitiesAndLoadData_WithNewGranularities()
        {
            // Arrange
            var instrument = new Database.Instrument()
            {
                Name = ForexMiner.Heimdallr.Common.Data.Contracts.Instrument.InstrumentName.EUR_USD
            };
            var granularities = new List <Database.InstrumentGranularity>()
            {
                new Database.InstrumentGranularity()
                {
                    Id          = Guid.NewGuid(),
                    Granularity = Granularity.H1,
                    State       = Database.GranularityState.New,
                    Instrument  = instrument
                }
            };

            instrument.Granularities = granularities;
            _dbContext.Add(instrument);
            _dbContext.SaveChanges();

            var oandaApiMock        = new Mock <IOandaApiConnection>();
            var oandaInstrumentMock = new Mock <IInstrument>();

            oandaInstrumentMock.Setup(oi => oi.GetCandlesByTimeAsync(It.IsAny <ClientModel.CandlestickGranularity>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), It.IsAny <IEnumerable <PricingComponent> >())).Returns(
                Task.FromResult(GenerateCandles())
                );
            oandaApiMock.Setup(oa => oa.GetInstrument(It.IsAny <GeriRemenyi.Oanda.V20.Client.Model.InstrumentName>())).Returns(oandaInstrumentMock.Object);
            _oandaApiConnectionFactoryMock.Setup(oacf => oacf.CreateConnection(OandaConnectionType.FxPractice, "FakeToken", It.IsAny <ClientModel.DateTimeFormat>())).Returns(oandaApiMock.Object);

            _httpClientFactoryMock.Setup(hcf => hcf.CreateClient("forex-miner-thor")).Returns(new Mock <HttpClient>().Object);
            _instrumentStorageServiceMock.Setup(iss => iss.StoreInstrumentCandles(It.IsAny <InstrumentWithCandles>()));

            // Act
            await _instrumentHistoryService.CheckInstrumentGranularitiesAndLoadData();

            // Assert
            _oandaApiConnectionFactoryMock.Verify(oacf => oacf.CreateConnection(It.IsAny <OandaConnectionType>(), It.IsAny <string>(), It.IsAny <ClientModel.DateTimeFormat>()), Times.AtLeastOnce());
            _httpClientFactoryMock.Verify(hcf => hcf.CreateClient("forex-miner-thor"), Times.AtLeastOnce());
            _instrumentStorageServiceMock.Verify(iss => iss.StoreInstrumentCandles(It.IsAny <InstrumentWithCandles>()), Times.AtLeastOnce());
        }
Ejemplo n.º 5
0
        public async void GetConnectionsForUser()
        {
            // Arrange
            var userId = Guid.NewGuid();
            var user   = new User()
            {
                Id        = userId,
                Email     = "*****@*****.**",
                FirstName = "Elek",
                LastName  = "Test",
                Role      = Role.Trader
            };

            user.UpdatePassword("SuperSecretivePassword");
            var connetion = new Database.Connection()
            {
                Id                = Guid.NewGuid(),
                Broker            = Database.Broker.Oanda,
                Name              = "Test Oanda Connection",
                ExternalAccountId = "1234",
                Type              = Contracts.ConnectionType.Demo
            };

            user.Connections.Add(connetion);
            _dbContext.Add(user);
            _dbContext.SaveChanges();

            var connectionSecret = "MuchSecretSoHidden";

            _connectionsSecretServiceMock.Setup(css => css.GetConnectionSecret(connetion.Id)).Returns(Task.FromResult(connectionSecret));

            var oandaTradesMock = new Mock <ITrades>();

            oandaTradesMock.Setup(ot => ot.GetOpenTradesAsync())
            .Returns(Task.FromResult <IEnumerable <GeriRemenyi.Oanda.V20.Client.Model.Trade> >(new List <GeriRemenyi.Oanda.V20.Client.Model.Trade>()
            {
                new GeriRemenyi.Oanda.V20.Client.Model.Trade()
                {
                    Id           = 1234,
                    Instrument   = GeriRemenyi.Oanda.V20.Client.Model.InstrumentName.EUR_USD,
                    Price        = 1.2345,
                    OpenTime     = DateTime.UtcNow.ToShortDateString(),
                    CurrentUnits = 10
                }
            }));
            var account = new GeriRemenyi.Oanda.V20.Client.Model.Account()
            {
                Balance = 9999999999,
                Pl      = 100
            };
            var oandaAccountMock = new Mock <IAccount>();

            oandaAccountMock.Setup(oa => oa.GetDetailsAsync()).Returns(Task.FromResult(account));
            oandaAccountMock.SetupGet(oa => oa.Trades).Returns(oandaTradesMock.Object);
            var oandaConnectionMock = new Mock <IOandaApiConnection>();

            oandaConnectionMock.Setup(oc => oc.GetAccount(connetion.ExternalAccountId)).Returns(oandaAccountMock.Object);
            _oandaApiFactoryMock.Setup(ocf => ocf.CreateConnection(GeriRemenyi.Oanda.V20.Sdk.Common.Types.OandaConnectionType.FxPractice, connectionSecret, It.IsAny <DateTimeFormat>()))
            .Returns(oandaConnectionMock.Object);


            // Act
            var userConnections = await _connectionService.GetConnectionsForUser(userId);

            // Assert
            _oandaApiFactoryMock.Verify(ocf => ocf.CreateConnection(GeriRemenyi.Oanda.V20.Sdk.Common.Types.OandaConnectionType.FxPractice, connectionSecret, It.IsAny <DateTimeFormat>()), Times.Once());
            oandaConnectionMock.Verify(oc => oc.GetAccount(connetion.ExternalAccountId), Times.Once());
            oandaAccountMock.Verify(oa => oa.GetDetailsAsync(), Times.Once());
            oandaAccountMock.VerifyGet(oa => oa.Trades, Times.Once());
            oandaTradesMock.Verify(ot => ot.GetOpenTradesAsync(), Times.Once());
            Assert.Single(userConnections);
            Assert.Equal(account.Balance, userConnections.ElementAt(0).Balance);
            Assert.Equal(account.Pl, userConnections.ElementAt(0).ProfitLoss);
        }
Ejemplo n.º 6
0
        public async void Tick()
        {
            // Arrange
            var instrument = new Database.Instrument()
            {
                Name = Contracts.InstrumentName.EUR_USD
            };
            var granularity = new Database.InstrumentGranularity()
            {
                Id          = Guid.NewGuid(),
                Instrument  = instrument,
                Granularity = Contracts.Granularity.M1,
                State       = Database.GranularityState.Tradeable
            };

            instrument.Granularities.Add(granularity);
            _dbContext.Add(instrument);
            _dbContext.SaveChanges();

            _configurationMock.SetupGet(c => c[It.Is <string>(cv => cv == "Oanda-MasterToken")]).Returns("TopSecretOandaToken");
            var oandaLastTwoCandles = new List <Candlestick>()
            {
                new Candlestick()
                {
                    Time     = DateTime.UtcNow.AddMinutes(-1).ToShortDateString(),
                    Volume   = 12345,
                    Complete = true,
                    Bid      = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    },
                    Mid = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    },
                    Ask = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    }
                },
                new Candlestick()
                {
                    Time     = DateTime.UtcNow.ToShortDateString(),
                    Volume   = 12345,
                    Complete = false,
                    Bid      = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    },
                    Mid = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    },
                    Ask = new CandlestickData()
                    {
                        O = 1.2345,
                        H = 1.2345,
                        L = 1.2345,
                        C = 1.2345
                    }
                }
            };
            var oandaInstrumentMock = new Mock <IInstrument>();

            oandaInstrumentMock.Setup(oi => oi.GetLastNCandlesAsync(
                                          CandlestickGranularity.M1,
                                          2,
                                          It.IsAny <IEnumerable <PricingComponent> >()
                                          )).Returns(Task.FromResult <IEnumerable <Candlestick> >(oandaLastTwoCandles));
            var oandaConnectionMock = new Mock <IOandaApiConnection>();

            oandaConnectionMock.Setup(oc => oc.GetInstrument(It.IsAny <InstrumentName>())).Returns(oandaInstrumentMock.Object);
            _oandaApiConnectionFactoryMock.Setup(oacf => oacf.CreateConnection(It.IsAny <OandaConnectionType>(), It.IsAny <string>(), It.IsAny <DateTimeFormat>())).Returns(oandaConnectionMock.Object);

            _instrumentStorageServiceMock.Setup(iss => iss.StoreInstrumentCandles(It.IsAny <Contracts.InstrumentWithCandles>()));

            var thorHttpClientFactoryName = "LokiIsSoOverrated";

            _configurationMock.SetupGet(c => c[It.Is <string>(cv => cv == "forex-miner-thor:Name")]).Returns(thorHttpClientFactoryName);
            _configurationMock.SetupGet(c => c[It.Is <string>(cv => cv == "forex-miner-thor:Content-Type")]).Returns("application/json");
            var httpMessageHandlerMock = new Mock <HttpMessageHandler>();
            var thorResponse           = new HttpResponseMessage()
            {
                StatusCode = System.Net.HttpStatusCode.OK,
                Content    = new StringContent(GetSerializedTradeSignal(instrument.Name))
            };

            httpMessageHandlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(thorResponse);
            var httpClient = new HttpClient(httpMessageHandlerMock.Object)
            {
                BaseAddress = new Uri("https://this-must-be-thor.ai")
            };

            _httpClientFactoryMock.Setup(hcf => hcf.CreateClient(thorHttpClientFactoryName)).Returns(httpClient);

            var connection = new Connection()
            {
                Id                = Guid.NewGuid(),
                Broker            = ForexMiner.Heimdallr.Common.Data.Database.Models.Connection.Broker.Oanda,
                ExternalAccountId = "123456",
                Name              = "This is a test connection",
                Owner             = null,
                Type              = ForexMiner.Heimdallr.Common.Data.Contracts.Connection.ConnectionType.Demo
            };

            _dbContext.Add(connection);
            _dbContext.SaveChanges();

            _connectionsSecretServiceMock.Setup(css => css.GetConnectionSecret(It.IsAny <Guid>()));
            var oandaAccountMock = new Mock <IAccount>();

            oandaAccountMock.Setup(oa => oa.GetDetailsAsync()).Returns(Task.FromResult(
                                                                           new GeriRemenyi.Oanda.V20.Client.Model.Account()
            {
                Balance      = 1000,
                UnrealizedPL = 100
            }
                                                                           ));
            var oandaTradesMock = new Mock <ITrades>();

            oandaTradesMock.Setup(ot => ot.OpenTradeAsync(
                                      It.IsAny <InstrumentName>(),
                                      It.IsAny <GeriRemenyi.Oanda.V20.Sdk.Trade.TradeDirection>(),
                                      It.IsAny <long>(),
                                      It.IsAny <int>()
                                      ));
            oandaAccountMock.SetupGet(oa => oa.Trades).Returns(oandaTradesMock.Object);
            oandaConnectionMock.Setup(oc => oc.GetAccount(It.IsAny <string>())).Returns(oandaAccountMock.Object);

            // Act
            await _tickerService.Tick();

            // Assert
            oandaInstrumentMock.Verify(oi => oi.GetLastNCandlesAsync(CandlestickGranularity.M1, 2, It.IsAny <IEnumerable <PricingComponent> >()), Times.Once());
            _instrumentStorageServiceMock.Verify(iss => iss.StoreInstrumentCandles(It.IsAny <Contracts.InstrumentWithCandles>()), Times.Once());
            _httpClientFactoryMock.Verify(hcf => hcf.CreateClient(thorHttpClientFactoryName), Times.Once());
            _connectionsSecretServiceMock.Verify(css => css.GetConnectionSecret(It.IsAny <Guid>()), Times.Once());
            oandaTradesMock.Verify(ot => ot.OpenTradeAsync(
                                       It.IsAny <InstrumentName>(),
                                       It.IsAny <GeriRemenyi.Oanda.V20.Sdk.Trade.TradeDirection>(),
                                       It.IsAny <long>(),
                                       It.IsAny <int>()
                                       ), Times.Once());
        }