public async Task GetTicker(string coinToCheck) { var exc = new Exchange(); var context = new ExchangeContext(); context.ApiKey = Settings.Default["APIKey"].ToString(); context.Secret = Settings.Default["SecretKey"].ToString(); context.Simulate = true; context.QuoteCurrency = "BTC"; exc.Initialise(context); if (!string.IsNullOrEmpty(coinToCheck)) //only update the prices if there's more than one char typed in. //hopefully this prevents the API from banning our IP address. { var coinTickerInfo = exc.GetTicker(coinToCheck); var updatedPrice_Last = coinTickerInfo.Last; var updatedPrice_Bid = coinTickerInfo.Bid; var updatedPrice_Ask = coinTickerInfo.Ask; lbl_CurrentBuyPriceAmountInBTC.Content = updatedPrice_Bid; lbl_CurrentTickerBuyPriceAmountInBTC.Content = updatedPrice_Bid; lbl_CurrentTickerSalePriceAmountInBTC.Content = updatedPrice_Ask; lbl_SellPriceInBTCAmount.Content = updatedPrice_Ask; } }
public async Task GetBalanceOfACoin(string coinToCheck) { var exc = new Exchange(); var context = new ExchangeContext(); context.ApiKey = Settings.Default["APIKey"].ToString(); context.Secret = Settings.Default["SecretKey"].ToString(); context.Simulate = true; context.QuoteCurrency = "BTC"; exc.Initialise(context); if (!string.IsNullOrEmpty(coinToCheck)) { var CoinBalanceCall = exc.GetBalance(coinToCheck); var CoinCurrentBalance = CoinBalanceCall.Balance; if (coinToCheck.ToUpper() == "BTC") { lbl_BTCBalanceAmount.Content = CoinCurrentBalance.ToString(); } else { lbl_CoinsOwnedAmount.Content = CoinCurrentBalance.ToString(); } } }
public void GetAll_Return_Valu() { //Arrange var options = new DbContextOptionsBuilder <ExchangeContext>() .UseInMemoryDatabase(databaseName: "GetPortfolio") .Options; using (var context = new ExchangeContext(options)) { var trade = new List <Trade> { new Trade { Action = "Buy", NoOfShares = 302, Id = 2, Price = 2332 } }; context.Portfolios.Add(new Portfolio { Id = 1, Name = "Adewale Johnson", Trade = trade }); context.SaveChanges(); //Act IPortfolioRepository repo = new PortfolioRepository(context); var result = repo.GetAll(); //Assert Assert.NotNull(result); } }
//Protfolio private void InitDbContext(ExchangeContext context) { context.Portfolios.Add(new Portfolio { Name = "Test10", Trade = null }); context.Portfolios.Add(new Portfolio { Name = "Test11", Trade = null }); context.Shares.Add(new HourlyShareRate { Rate = Convert.ToDecimal(50.00), Symbol = "TES", TimeStamp = DateTime.Now }); context.Shares.Add(new HourlyShareRate { Rate = Convert.ToDecimal(50.10), Symbol = "SBI", TimeStamp = DateTime.Now }); context.Trades.Add(new Trade { Action = "BUY", NoOfShares = 50, PortfolioId = 1, Price = Convert.ToDecimal(60.10), Symbol = "SAG" }); context.Trades.Add(new Trade { Action = "SELL", NoOfShares = 500, PortfolioId = 2, Price = Convert.ToDecimal(600.10), Symbol = "ABG" }); context.SaveChanges(); }
public static IOrderedQueryable <Order> QueryFree(ExchangeContext dbContext) { return(dbContext.BuyOrders .Where(o => o.IsActive) .OrderByDescending(o => o.Price) .ThenBy(o => o.Date)); }
public StockExchange(ExchangeContext db, ITableRepository <Client> clientTableRepository, ITableRepository <ClientStock> clientStockTableRepository, ITableRepository <Issuer> issuerTableRepository, ITableRepository <Order> orderTableRepository, ITableRepository <PriceHistory> priceHistoryTableRepository, ITableRepository <Stock> stockTableRepository, ITableRepository <TransactionHistory> transactionHistoryTableRepository, ClientService clientService, ClientStockService clientStockService, OrderService orderService, PriceHistoryService priceHistoryService, TransactionHistoryService transactionHistoryService, ILogger logger ) { this.db = db; this.clientTableRepository = clientTableRepository; this.clientStockTableRepository = clientStockTableRepository; this.issuerTableRepository = issuerTableRepository; this.orderTableRepository = orderTableRepository; this.priceHistoryTableRepository = priceHistoryTableRepository; this.stockTableRepository = stockTableRepository; this.transactionHistoryTableRepository = transactionHistoryTableRepository; this.clientService = clientService; this.clientStockService = clientStockService; this.orderService = orderService; this.priceHistoryService = priceHistoryService; this.transactionHistoryService = transactionHistoryService; this.logger = logger; }
public async Task <HttpResponseMessage> InstallAppAsync(string customerId, string userId) { if (string.IsNullOrEmpty(customerId)) { throw new ArgumentNullException(nameof(customerId)); } if (string.IsNullOrEmpty(userId)) { throw new ArgumentNullException(nameof(userId)); } GraphContext graph; ExchangeContext context; IUser user; try { graph = new GraphContext(customerId); user = await graph.Client.Users.GetByObjectId(userId).ExecuteAsync(); context = new ExchangeContext(customerId, user.Mail); context.InstallApp("PartnerCenter.Samples.AOBO.Manifests.HelloWorld.HelloWorld.xml"); return(new HttpResponseMessage(HttpStatusCode.NoContent)); } finally { context = null; graph = null; user = null; } }
private void Recover(ExchangeContext db) { db.Database.Migrate(); // ensure database is created this.SeqNum = 1; if (db.ExecutionReports.Any()) { var activeOrders = db.ExecutionReports.AsNoTracking() .GroupBy(x => x.OrderId) .Select(x => x.MaxBy(y => y.SeqNum)) .Where(x => x.Symbol == this.OrderBook.Symbol && x.OrdStatus == OrdStatus.New || x.OrdStatus == OrdStatus.PartiallyFilled) .Select(x => x.ToOrder()) .ToList(); try { this.SeqNum = db.ExecutionReports.AsNoTracking() .Where(x => x.Symbol == OrderBook.Symbol) .Max(x => x.SeqNum) + 1; } catch (InvalidOperationException) //empty db { this.SeqNum = 1; } OrderBook.Recover(activeOrders, 0); } }
static void Main(string[] args) { try { do { Console.WriteLine("Type \"INITIALIZE\" (in caps) to initialize process."); } while (Console.ReadLine() != "INITIALIZE"); int marketId; do { Console.Write("Enter Market Id > "); } while (!int.TryParse(Console.ReadLine(), out marketId)); Console.WriteLine(marketId); do { Console.Write("Re-Enter Market Id > "); } while (!int.TryParse(Console.ReadLine(), out var f) || f != marketId); Console.WriteLine(marketId); QueueProducer queueProducer = new QueueProducer("engine-in", "fanout", "engine-reader", "#", "localhost", "/", "guest", "guest"); var dbContext = new ExchangeContext(new GlobalQueryFilterRegisterer(), "Host=localhost;Database=Exchange;Username=postgres;Password=root"); var orders = dbContext.Orders.Where(x => x.IsDeleted == false && x.MarketId == marketId && (x.OrderStatus == Entity.Partials.OrderStatus.Accepted || x.OrderStatus == Entity.Partials.OrderStatus.Received)).OrderBy(x => x.CreatedOn).ToList(); foreach (var order in orders) { var orderWrapper = new OrderWrapper(); orderWrapper.Order = new Order(); orderWrapper.Order.OrderId = order.Id; orderWrapper.Order.IsBuy = order.Side; orderWrapper.Order.Price = order.Rate; orderWrapper.Order.OpenQuantity = order.QuantityRemaining; orderWrapper.Order.IsStop = order.StopRate != 0; orderWrapper.OrderCondition = (OrderCondition)((byte)order.OrderCondition); orderWrapper.StopPrice = order.StopRate; orderWrapper.TipQuantity = order.IcebergQuantity > 0 ? order.Quantity : 0; orderWrapper.TotalQuantity = order.IcebergQuantity ?? 0; if (order.CancelOn.HasValue) { DateTime Jan1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); orderWrapper.Order.CancelOn = (int)order.CancelOn.Value.Subtract(Jan1970).TotalSeconds; } var bytes = OrderSerializer.Serialize(orderWrapper); queueProducer.Produce(bytes); } queueProducer.Flush(); queueProducer.Close(); Console.WriteLine("Finished.."); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadLine(); }
private ExchangeContext InMemoryContext() { var options = new DbContextOptionsBuilder <ExchangeContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; var context = new ExchangeContext(options); return(context); }
public pullSnapshotDataResponse pullSnapshotData(pullSnapshotDataRequest request) { DataManager dataManager = new DataManager(); pullSnapshotDataResponse response = null; MessageContainer msg = dataManager.GetData(); if (msg != null) { response = new pullSnapshotDataResponse(); msg.exchangeInformation.exchangeContext.supplierOrCisRequester.internationalIdentifier.nationalIdentifier = "DEMO"; msg.exchangeInformation.exchangeContext.supplierOrCisRequester.internationalIdentifier.country = "SE"; msg.exchangeInformation.dynamicInformation.messageGenerationTimestamp = DateTime.UtcNow; response.pullSnapshotDataOutput = msg; } else { #region Return fail message response = new pullSnapshotDataResponse(); response.pullSnapshotDataOutput = new MessageContainer(); response.pullSnapshotDataOutput.modelBaseVersion = "3"; ExchangeInformation exchangeInfo = new ExchangeInformation(); ExchangeContext exchangeContext = new ExchangeContext(); exchangeContext.codedExchangeProtocol = new _ProtocolTypeEnum() { Value = ProtocolTypeEnum.snapshotPull }; exchangeContext.exchangeSpecificationVersion = "3"; Agent agent = new Agent(); InternationalIdentifier identifier = new InternationalIdentifier { nationalIdentifier = "DEMO", country = "SE" }; agent.internationalIdentifier = identifier; exchangeContext.supplierOrCisRequester = agent; exchangeInfo.exchangeContext = exchangeContext; DynamicInformation dynamicInformation = new DynamicInformation(); _ExchangeStatusEnum exchangeStatusEnum = new _ExchangeStatusEnum { Value = ExchangeStatusEnum.undefined }; dynamicInformation.messageGenerationTimestamp = DateTime.UtcNow; dynamicInformation.exchangeStatus = exchangeStatusEnum; exchangeInfo.dynamicInformation = dynamicInformation; dynamicInformation.returnInformation = new ReturnInformation(); dynamicInformation.returnInformation.returnStatus = new _ExchangeReturnEnum(); dynamicInformation.returnInformation.returnStatus.Value = ExchangeReturnEnum.fail; #endregion } return(response); }
public static ExchangeContext CreateContext(bool withData) { var options = new DbContextOptionsBuilder <ExchangeContext>() .UseInMemoryDatabase("ExchangeUnitTestsDb") .Options; var context = new ExchangeContext(options, new DataSeed()); context.Database.EnsureDeleted(); context.Database.EnsureCreated(); return(context); }
public TriggerRuleWorkflow() { InitializeComponent(); // // policyFromService1 // this.policyFromService.Name = "policyFromService"; this.policyFromService.RuleSetName = RuleSetName; this.Context = (Context)ExchangeContext.Clone(); }
public async Task TradeRepository_GetAsyncTest() { var optionsbuilder = new DbContextOptionsBuilder <ExchangeContext>(); optionsbuilder.UseInMemoryDatabase(databaseName: "XOProjectDb"); var _dbContext = new ExchangeContext(optionsbuilder.Options); ITradeRepository _tradeRepository = new TradeRepository(_dbContext); var result = await _tradeRepository.GetAllTradings(1); Assert.NotNull(result); }
public void TradeRepository_GetAllTest() { var optionsbuilder = new DbContextOptionsBuilder <ExchangeContext>(); optionsbuilder.UseInMemoryDatabase(databaseName: "XOProjectDb"); var _dbContext = new ExchangeContext(optionsbuilder.Options); IPortfolioRepository _portfolioRepository = new PortfolioRepository(_dbContext); var result = _portfolioRepository.GetAll(); Assert.NotNull(result); }
public ControllerTestBase() { var options = new DbContextOptionsBuilder <ExchangeContext>() .UseInMemoryDatabase(databaseName: "TestDB") .Options; _exchangeContext = new ExchangeContext(options); _shareRepository = new ShareRepository(_exchangeContext); _tradeRepository = new TradeRepository(_exchangeContext); _portfolioRepository = new PortfolioRepository(_exchangeContext); }
public static void Main(string[] args) { var dbContext = new ExchangeContext(); var stocks = dbContext.Stocks.ToList(); foreach (var stock in stocks) { Console.WriteLine("{0} - {1}", stock.Symbol, stock.Price); } Console.ReadLine(); }
public void exchangeContextInit(ExchangeContext context) { context.Portfolios.Add(new Portfolio { Name = "John Doe", Trade = null }); context.Trades.Add(new Trade { Symbol = "REL", NoOfShares = 50, Price = 5000, PortfolioId = 1, Action = "BUY" }); context.Trades.Add(new Trade { Symbol = "REL", NoOfShares = 100, Price = 10000, PortfolioId = 1, Action = "BUY" }); context.SaveChanges(); }
public async Task <List <CurrencyTableModel> > GetCurrenciesAsync() { using (var ctx = new ExchangeContext()) { try { var currencies = await ctx.Currencies.ToListAsync(); return(currencies); } catch (Exception ex) { return(null); } } }
private void HandleMessage(NewKeysMessage message) { this.hasBlockedMessagesWaitHandle.Reset(); lock (this.locker) { this.inboundFlow = 0; this.outboundFlow = 0; this.algorithms = this.exchangeContext.NewAlgorithms; this.exchangeContext = null; } this.ContinueSendBlockedMessages(); this.hasBlockedMessagesWaitHandle.Set(); }
// private IServiceScope _scope; public OrderbookService(IServiceProvider serviceProvider, ConnectionFactory rabbitConnection, ExchangeContext db) { // _scope = serviceProvider.CreateScope(); _serviceProvider = serviceProvider; _rabbitConnection = rabbitConnection; _db = db; using (var scope = serviceProvider.CreateScope()) { var config = scope.ServiceProvider.GetRequiredService <IOptionsSnapshot <SpringConfig> >(); var symbol = config.Value.Application.Name.Replace("Exchange_", string.Empty); OrderBook = new OrderBook(symbol); OrderBook.TradeIdGenerator = () => Guid.NewGuid().ToString(); } }
private void HandleMessage(NewKeysMessage message) { _hasBlockedMessagesWaitHandle.Reset(); lock (_locker) { _inboundFlow = 0; _outboundFlow = 0; _algorithms = _exchangeContext.NewAlgorithms; _exchangeContext = null; } ContinueSendBlockedMessages(); _hasBlockedMessagesWaitHandle.Set(); }
static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var logger = new Logger(log4net.LogManager.GetLogger("Logger")); ExchangeContext db = new ExchangeContext(); IDTOMethodsforPriceHistory dTOMethodsforPriceHistory = new DTOMethodsforPriceHistory(db); ITableRepository <Client> clientTableRepository = new ClientTableRepository <Client>(db); ITableRepository <ClientStock> clientStockTableRepository = new ClientStockTableRepository <ClientStock>(db); ITableRepository <Issuer> issuerTableRepository = new IssuerTableRepository <Issuer>(db); ITableRepository <Order> orderTableRepository = new OrderTableRepository <Order>(db); ITableRepository <PriceHistory> priceHistoryTableRepository = new PriceHistoryTableRepository <PriceHistory>(db); ITableRepository <Stock> stockTableRepository = new StockTableRepository <Stock>(db); ITableRepository <TransactionHistory> transactionHistoryTableRepository = new TransactionHistoryTableRepository <TransactionHistory>(db); ClientService clientService = new ClientService(clientTableRepository); ClientStockService clientStockService = new ClientStockService(clientStockTableRepository); OrderService orderService = new OrderService(orderTableRepository); PriceHistoryService priceHistoryService = new PriceHistoryService(priceHistoryTableRepository, dTOMethodsforPriceHistory); TransactionHistoryService transactionHistoryService = new TransactionHistoryService(transactionHistoryTableRepository); StockExchange stockExchange = new StockExchange( db, clientTableRepository, clientStockTableRepository, issuerTableRepository, orderTableRepository, priceHistoryTableRepository, stockTableRepository, transactionHistoryTableRepository, clientService, clientStockService, orderService, priceHistoryService, transactionHistoryService, logger); using (db) { logger.Info("Trading is started"); stockExchange.RunTraiding(); logger.Info("Trading is finished"); }; }
public async Task Get_Analysis_Valid_Maximum() { string symbol = "REL"; var builder = new DbContextOptionsBuilder <ExchangeContext>(); builder.UseInMemoryDatabase(databaseName: "TestTrade3"); var context = new ExchangeContext(builder.Options); exchangeContextInit(context); var repo = new TradeRepository(context); var result = await repo.GetAnalysis(symbol) as List <TradeAnalysis>;; Assert.AreEqual(100, result[0].Maximum); }
private ExchangeContext GetContextWithData() { var options = new DbContextOptionsBuilder <ExchangeContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; var dbContext = new ExchangeContext(options); var share = new HourlyShareRate { Id = 1, Rate = 90, Symbol = "REL", TimeStamp = DateTime.Now }; dbContext.Add(share); dbContext.SaveChanges(); return(dbContext); }
public async Task Get_AllPortfolios_Valid_Count() { var builder = new DbContextOptionsBuilder <ExchangeContext>(); builder.UseInMemoryDatabase(databaseName: "TestPortfolio"); var context = new ExchangeContext(builder.Options); exchangeContextInit(context); var repo = new PortfolioRepository(context); var result = await repo.GetAll() as List <Portfolio>;; var count = result.Count; Assert.AreEqual(1, count); }
public async Task Get_Trades_By_Symbol_Valid_Count() { string symbol = "REL"; var builder = new DbContextOptionsBuilder <ExchangeContext>(); builder.UseInMemoryDatabase(databaseName: "TestTrade2"); var context = new ExchangeContext(builder.Options); exchangeContextInit(context); var repo = new TradeRepository(context); var result = await repo.GetBySymbol(symbol) as List <Trade>;; var count = result.Count; Assert.AreEqual(2, count); }
public async Task Get_AllTrades_Valid_Count() { int portfolioID = 1; var builder = new DbContextOptionsBuilder <ExchangeContext>(); builder.UseInMemoryDatabase(databaseName: "TestTrade1"); var context = new ExchangeContext(builder.Options); exchangeContextInit(context); var repo = new TradeRepository(context); var result = await repo.GetAllTradings(portfolioID) as List <Trade>;; var count = result.Count; Assert.AreEqual(2, count); }
public static void RegisterAutofac() { var builder = new ContainerBuilder(); // register ef var initializeDb = new ExchangeContext(); builder.RegisterType <ExchangeContext>() .AsSelf() .InstancePerLifetimeScope(); // register in current Assembly builder.RegisterControllers(typeof(MvcApplication).Assembly); // register automapper builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .AssignableTo(typeof(Profile)) .As <Profile>(); builder.Register(c => new MapperConfiguration(cfg => { foreach (var profile in c.Resolve <IEnumerable <Profile> >()) { cfg.AddProfile(profile); } })).AsSelf().SingleInstance(); builder.Register(ctx => ctx.Resolve <MapperConfiguration>() .CreateMapper()) .As <IMapper>() .InstancePerLifetimeScope(); // registers all the other DI items builder.RegisterType <TradeRepository>().As <ITradeRepository>(); builder.RegisterType <CurrencyRepository>().As <ICurrencyRepository>(); builder.RegisterType <ParticipantRepository>().As <IParticipantRepository>(); // create a new container with the dependencies defined above var container = builder.Build(); // setting dependency mapper DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
private void Make(ExchangeContext dbContext) { var deal = new List <Order> { Buy, Sell }; Price = deal.OrderBy(o => o.Date).First().Price; Size = deal.Select(o => o.Number).Min(); foreach (Order order in deal) { order.Number -= Size; } dbContext.Add(this); dbContext.SaveChanges(); new Transaction(_dbContext).Try(); }
public ConversationService() { _exchangeContext = new ExchangeContext(); }
public CustomUserIdProvider() { _exchangeContext = new ExchangeContext(); }
public ExchangeBackedByExternalResourcesRepository(ExchangeContext exchangeContext) { this.exchangeContext = exchangeContext; this.dbSet = this.exchangeContext.Set<Exchange>(); }
public AuctionOfferService() { _exchangeContext = new ExchangeContext(); }
public StockService() { _exchangeContext = new ExchangeContext(); }