Ejemplo n.º 1
0
        static void MatchOffers(
            IStocksForSaleRepository forSaleRepo,
            IBuyOfferRepository buyOffersRepo,
            IStocksRepository ownerRepo,
            IMessageBus bus)
        {
            var forSaleTask   = forSaleRepo.Read();
            var buyOffersTask = buyOffersRepo.Read();

            Task.WhenAll(forSaleTask, buyOffersTask).GetAwaiter().GetResult();
            var stocksForSale = forSaleTask.Result.ToList();
            var buyOffers     = buyOffersTask.Result.ToList();

            foreach (var offer in buyOffers)
            {
                try
                {
                    var matchingForSale = stocksForSale.FirstOrDefault(s =>
                                                                       string.Equals(s.Stock, offer.Stock, StringComparison.CurrentCultureIgnoreCase) &&
                                                                       s.Price == offer.Price &&
                                                                       s.Amount == offer.Amount);

                    if (matchingForSale == null)
                    {
                        continue;
                    }

                    // made a sale, yay
                    stocksForSale.Remove(matchingForSale);
                    Task.WhenAll(
                        buyOffersRepo.Delete(offer.BuyerId, offer.Stock, offer.Amount, offer.Price),
                        forSaleRepo.Delete(matchingForSale.SellerId, matchingForSale.Stock, matchingForSale.Amount,
                                           matchingForSale.Price),
                        ownerRepo.Delete(matchingForSale.SellerId, offer.Stock, offer.Amount),
                        ownerRepo.Write(offer.BuyerId, offer.Stock, offer.Amount),
                        bus.Publish(new StockTradeHappenedEventDto()
                    {
                        BuyerId  = offer.BuyerId,
                        SellerId = matchingForSale.SellerId,
                        Amount   = offer.Amount,
                        Price    = offer.Price,
                        Stock    = offer.Stock
                    })).GetAwaiter().GetResult();
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Problem occured while matching offers: {e.Message}");
                    throw;
                }
            }
        }
Ejemplo n.º 2
0
 public BuyOfferService(IBuyOfferRepository buyOfferRepository)
 {
     _buyOfferRepository = buyOfferRepository;
 }