示例#1
0
        private QuoteService CreateQuoteService()
        {
            var userId       = Guid.Parse(User.Identity.GetUserId());
            var quoteService = new QuoteService(userId);

            return(quoteService);
        }
示例#2
0
        /// <summary>
        /// Program's asynchronous startup.
        /// </summary>
        /// <returns></returns>
        public async Task RunAsync()
        {
            GlobalConfiguration.Initialize();
            ConfigureAppSettings();
            ConfigureLogger();
            QuoteService.TryLoadQuotes();

            ApiCalls            api    = new(Configuration, logger);
            DiscordSocketClient client = new(new DiscordSocketConfig()
            {
                /* TODO: Remove GuildMessages after it becomes privileged intent and all commands are replaced by slash commands */
                GatewayIntents = GatewayIntents.GuildMessages | GatewayIntents.Guilds | GatewayIntents.GuildMessages | GatewayIntents.GuildMessageReactions | GatewayIntents.GuildMessageTyping | GatewayIntents.DirectMessages | GatewayIntents.DirectMessageReactions | GatewayIntents.DirectMessageTyping,
            });
            CommandService           commandsService          = new();
            InteractionService       interactionService       = new(client);
            FergunInteractiveService fergunInteractiveService = new(client);

            using ServiceProvider services = ConfigureServices(client, commandsService, interactionService, fergunInteractiveService, api);

            string commandPrefix = Configuration["commandPrefix"];
            string token         = GlobalConfiguration.GetToken(Configuration);

            PrintCurrentVersion();
            await RegisterEventsAsync(client, api, commandsService, interactionService, fergunInteractiveService, services);

            await client.LoginAsync(TokenType.Bot, token);

            await client.StartAsync();

            await client.SetGameAsync(GlobalConfiguration.GetStatusText(), type : ActivityType.Listening);

            await Task.Delay(Timeout.Infinite);
        }
示例#3
0
        /// <summary>
        /// 调用控件线程方法
        /// </summary>
        /// <param name="args">参数</param>
        public override void OnInvoke(object args)
        {
            CMessage message = (CMessage)args;

            if (message.m_serviceID == m_quoteService.ServiceID)
            {
                LatestDataInfo            dataInfo = new LatestDataInfo();
                List <SecurityLatestData> datas    = new List <SecurityLatestData>();
                QuoteService.GetLatestDatas(ref dataInfo, datas, message.m_body, message.m_bodyLength);
                int datasSize = datas.Count;
                for (int i = 0; i < datasSize; i++)
                {
                    m_latestDatas[datas[i].m_securityCode] = datas[i];
                }
                datas.Clear();
            }
            else if (message.m_serviceID == m_userSecurityService.ServiceID)
            {
                if (message.m_functionID < UserSecurityService.FUNCTIONID_USERSECURITY_GETVISITSCOUNT)
                {
                    LoadCells();
                }
            }
            Invalidate();
        }
示例#4
0
        private static async Task CreateQuotes(
            string filePath,
            AuthorService authorService,
            QuoteService quoteService,
            bool splitIntoChunks)
        {
            var quotes  = JsonConvert.DeserializeObject <Dictum.Business.Models.Domain.Quote[]>(File.ReadAllText(filePath));
            var authors = quotes.Select(x => x.Author).Distinct();
            await Task.WhenAll(authors.Select(authorService.GetOrCreate));

            if (splitIntoChunks)
            {
                var chunks = quotes
                             .Select((quote, index) => new { quote, index })
                             .GroupBy(x => x.index / ChunkSize)
                             .Select(x => x.Select(y => y.quote));

                foreach (var chunk in chunks)
                {
                    await Task.WhenAll(chunk.Select(quoteService.CreateQuote));

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            else
            {
                await Task.WhenAll(quotes.Select(quoteService.CreateQuote));
            }
        }
示例#5
0
        public virtual ActionResult Quote(Domain.Model.Quote model)
        {
            QuoteService srv = new QuoteService(_commandProcessor, _queryProcessor, _currentUserFactory);

            if (Request.IsAjaxRequest())
            {
                if (model.ContractCalculations != null)
                {
                    foreach (EWS.Domain.Model.QuoteCalculation calc in model.ContractCalculations)
                    {
                        calc.QuoteCalculationItems = srv.Recalculate(calc, calc.QuoteCalculationItems, model.StartDate);
                    }
                }
                else
                {
                    model = srv.GetModel <Domain.Model.Quote>(model.Id);
                }
                return(View("_", model.ContractCalculations));
            }
            else
            {
                srv.SaveQuote(model);
            }


            return(RedirectToActionPermanent(MVC.Quote.FinaliseQuote(model.Id)));
        }
示例#6
0
 private static void HandleDisplayMode(NasdaqStock stock, SpeechRecognizedEventArgs e)
 {
     if (e.Result.Semantics["Modifier"].Value.ToString() == "close of")
     {
         string ticker         = stock.ticker;
         var    myQuoteService = new QuoteService();
         var    requestedQuote = myQuoteService.Quote(ticker).Return(QuoteReturnParameter.PreviousClose);
         using (SpeechSynthesizer synth = new SpeechSynthesizer())
         {
             // Configure the audio output.
             synth.SetOutputToDefaultAudioDevice();
             // Speak a string synchronously.
             synth.Speak("The last close of " + e.Result.Semantics["CompanyName"].Value.ToString() + "was" + requestedQuote.PreviousClose.ToString() + "dollars");
         }
     }
     else if (e.Result.Semantics["Modifier"].Value.ToString() == "ask of")
     {
         string ticker         = stock.ticker;
         var    myQuoteService = new QuoteService();
         var    requestedQuote = myQuoteService.Quote(ticker).Return(QuoteReturnParameter.Ask);
         using (SpeechSynthesizer synth = new SpeechSynthesizer())
         {
             // Configure the audio output.
             synth.SetOutputToDefaultAudioDevice();
             // Speak a string synchronously.
             synth.Speak("The last ask of " + e.Result.Semantics["CompanyName"].Value.ToString() + "was" + requestedQuote.Ask.ToString() + "dollars");
         }
     }
 }
        public override bool Arrange()
        {
            Service = new QuoteService(TestConstants.Configuration);

            Input = new QuoteCreateInput("57 luscombe st, brunswick, melbourne", "105 collins st, 3000");

            Input.Booking.DropoffDetail.Email = "*****@*****.**";

            Input.Booking.Reference            = "ABC123";
            Input.Booking.DeliveryInstructions = "Ring when you get to the street";
            Input.Booking.ItemsRequirePurchase = true;
            Input.Booking.Items.Add("Test item description 1", "SKU1", 1, 10);
            Input.Booking.Items.Add("Test item description 2", "SKU2", 1, 10);
            Input.Booking.PickupTime        = DateTime.Now.AddHours(1);
            Input.Booking.DropoffWindow     = TimeFrame.Create(DateTime.Now, DateTime.Now.AddDays(1));
            Input.Booking.CustomerFee       = 10;
            Input.Booking.CustomerReference = "CUST123";
            Input.Booking.Tax = 20;
            Input.Booking.TaxInclusivePrice = true;
            Input.Booking.Tip = 30;
            Input.Booking.DriverFeePercentage = 0.8m;
            Input.Booking.DriverMatchCode     = "MATCH123";
            Input.Booking.DeliverySequence    = 40;
            Input.Booking.Constraints.Add("Constraint 1", "true");
            Input.Booking.Constraints.Add("Constraint 2", "false");
            Input.Booking.DeliveryRouteIdentifier = "ID123";
            Input.Booking.Webhooks.Add("job/created", "http://tempuri.org");
            Input.Booking.Webhooks.Add("job/updated", "http://tempuri.org");
            Input.Booking.Template = "Template 1";

            return(true);
        }
示例#8
0
        public void GivenARequestToBorrow_WhenItCantBeAccepted_ThenReturnNULL()
        {
            var lenders = new List <Lender>()
            {
                new Lender()
                {
                    Name = "Bob", Rate = 0.075M, Available = 640
                },
                new Lender()
                {
                    Name = "Jane", Rate = 0.069M, Available = 480
                },
                new Lender()
                {
                    Name = "Fred", Rate = 0.071M, Available = 520
                },
                new Lender()
                {
                    Name = "Angela", Rate = 0.071M, Available = 60
                }
            };

            var amountToBorrow = 15000;

            var quoteService = new QuoteService(new LenderService(), new PaymentService());
            var quote        = quoteService.GetQuote(lenders, amountToBorrow);

            quote.ShouldBeNull();
        }
示例#9
0
        public List <Quote> GetQuotes(QuotesBody body)
        {
            //Create the quote service
            var quote_service = new QuoteService();

            string[] symbols = body.symbols.ToArray();

            //Get a quote
            var quotes = quote_service.Quote(symbols).Return(QuoteReturnParameter.Symbol,
                                                             QuoteReturnParameter.Name,
                                                             QuoteReturnParameter.LatestTradePrice,
                                                             QuoteReturnParameter.LatestTradeTime);

            List <Quote> quotes_list = new List <Quote>();

            //Get info from the quotes
            foreach (var quote in quotes)
            {
                Quote q = new Quote
                {
                    Symbol           = quote.Symbol,
                    Name             = quote.Name,
                    LatestTradePrice = quote.LatestTradePrice,
                    LatestTradeTime  = quote.LatestTradeTime
                };

                quotes_list.Add(q);
            }

            return(quotes_list);
        }
示例#10
0
        public void GivenARequestToBorrow_WhenItCanBeAccepted_ThenCalculateTheQuote()
        {
            var lenders = new List <Lender>()
            {
                new Lender()
                {
                    Name = "Bob", Rate = 0.075M, Available = 640
                },
                new Lender()
                {
                    Name = "Jane", Rate = 0.069M, Available = 480
                },
                new Lender()
                {
                    Name = "Fred", Rate = 0.071M, Available = 520
                },
                new Lender()
                {
                    Name = "Angela", Rate = 0.071M, Available = 60
                }
            };

            var amountToBorrow = 1000;

            var quoteService = new QuoteService(new LenderService(), new PaymentService());
            var quote        = quoteService.GetQuote(lenders, amountToBorrow);

            quote.Rate.ShouldBe(0.07M);
            quote.Amount.ShouldBe(1000);
            quote.MonthlyRepayment.ShouldBe(30.78M, 0.01M);
            quote.TotalRepayment.ShouldBe(1108.10M, 0.01M);
        }
示例#11
0
        public async Task GetQuoteAsync_WhenCandleIsNull_ShouldThrowApiException()
        {
            // Arrange
            var          today  = DateTime.Today;
            const string symbol = CompanySymbol;
            var          exchangeRateService      = new Mock <IExchangeRateService>();
            var          externalFinancialService = new Mock <IExternalFinanceService>();

            externalFinancialService
            .Setup(x => x.GetCandleAsync(It.IsAny <string>(), It.IsAny <DateTime>()))
            .ReturnsAsync((Candle)null);

            var service = new QuoteService(_globalizationService, exchangeRateService.Object, externalFinancialService.Object);

            // Act
            var exception =
                await Should.ThrowAsync <ApiException>(async() =>
                                                       await service.GetQuoteAsync(
                                                           new QuoteRequest {
                Region = UsRegionName, Symbol = symbol, Date = today
            }));

            // Assert
            this.ShouldSatisfyAllConditions(
                () =>
            {
                exception.Code.ShouldBe(HttpStatusCode.NotFound);
                exception.Errors.ShouldBe(
                    $"Quote data not found [{symbol}/{today:yyyy-MM-dd}].");
            });
        }
示例#12
0
        public async Task QotdAsync(CommandContext ctx,
                                    [Description("str-topic")] string?category = null)
        {
            Quote?quote = await QuoteService.GetQuoteOfTheDayAsync(category);

            if (quote is null)
            {
                throw new CommandFailedException(ctx, "cmd-err-quote");
            }

            await ctx.RespondWithLocalizedEmbedAsync(emb => {
                if (string.IsNullOrWhiteSpace(category))
                {
                    emb.WithLocalizedTitle("str-qotd");
                }
                else
                {
                    emb.WithLocalizedTitle("str-qotd-cat", category);
                }
                emb.WithColor(this.ModuleColor);
                emb.WithLocalizedDescription("fmt-qotd", quote.Content, quote.Author);
                emb.WithImageUrl(quote.BackgroundImageUrl);
                emb.WithUrl(quote.Permalink);
                emb.WithLocalizedFooter("fmt-powered-by", null, "theysaidso.com");
            });
        }
示例#13
0
 public TwitchBotApplication(Configuration appConfig, TwitchInfoService twitchInfo, SongRequestBlacklistService songRequestBlacklist,
                             FollowerService follower, BankService bank, FollowerSubscriberListener followerListener, ManualSongRequestService manualSongRequest, PartyUpService partyUp,
                             GameDirectoryService gameDirectory, QuoteService quote, BankHeist bankHeist, TwitchChatterListener twitchChatterListener, IrcClient irc,
                             BossFight bossFight, SongRequestSettingService songRequestSetting, InGameUsernameService ign, LibVLCSharpPlayer libVLCSharpPlayer)
 {
     _appConfig    = appConfig;
     _botConfig    = appConfig.GetSection("TwitchBotConfig") as TwitchBotConfigurationSection;
     _greetedUsers = new List <string>();
     _twitchInfo   = twitchInfo;
     _follower     = follower;
     _followerSubscriberListener = followerListener;
     _bank = bank;
     _songRequestBlacklist = songRequestBlacklist;
     _manualSongRequest    = manualSongRequest;
     _gameDirectory        = gameDirectory;
     _quote                 = quote;
     _bankHeist             = bankHeist;
     _twitchChatterListener = twitchChatterListener;
     _bossFight             = bossFight;
     _songRequestSetting    = songRequestSetting;
     _ign = ign;
     _libVLCSharpPlayer = libVLCSharpPlayer;
     _irc     = irc;
     _partyUp = partyUp;
 }
        public Task <CurrentQuote> GetQuote(string companySymbol)
        {
            //Create the quote service
            var quoteService = new QuoteService();

            //Get a quote
            var find   = quoteService.Quote(companySymbol);
            var quotes = find.Return(
                QuoteReturnParameter.Symbol,
                QuoteReturnParameter.Name,
                QuoteReturnParameter.LatestTradePrice,
                QuoteReturnParameter.EPS,
                QuoteReturnParameter.EPSEstimateCurrentYear,
                QuoteReturnParameter.EPSEstimateNextYear,
                QuoteReturnParameter.PERatio,
                QuoteReturnParameter.PEGRatio);

            var currentQuote = new CurrentQuote
            {
                Symbol           = quotes.Symbol.ToString().Trim('"'),
                Name             = quotes.Name.ToString().Trim('"'),
                LatestTradePrice = double.Parse(quotes.LatestTradePrice, CultureInfo.InvariantCulture),
                EPS = double.Parse(quotes.EPS, CultureInfo.InvariantCulture),
                EPSEstimateCurrentYear = double.Parse(quotes.EPSEstimateCurrentYear, CultureInfo.InvariantCulture),
                EPSEstimateNextYear    = double.Parse(quotes.EPSEstimateNextYear, CultureInfo.InvariantCulture),
                PERatio  = double.Parse(quotes.PERatio, CultureInfo.InvariantCulture),
                PEGRatio = double.Parse(quotes.PEGRatio, CultureInfo.InvariantCulture)
            };

            return(Task.FromResult(currentQuote));
        }
        public ActionResult Index(CheckoutShippingViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.quote = GetQuote();

                Mapper.CreateMap <CheckoutShippingViewModel, Address>();

                if (model.quote.Address == null)
                {
                    AddressService.CreateAddress(model.quote.QuoteID, Mapper.Map <Address>(model));
                }
                else
                {
                    Address UpdatedAddress = Mapper.Map <Address>(model);
                    UpdatedAddress.AddressID = model.quote.Address.AddressID;
                    AddressService.UpdateAddress(UpdatedAddress);
                }

                Quote quote = GetQuote();
                quote.ShippingCharge = quote.CalculateShipping();
                QuoteService.UpdateQuote(quote);

                string URL = PayPal.ConfirmSale(GetQuote());

                return(Redirect(URL));
            }

            return(Index());
        }
        public ActionResult Index()
        {
            CheckoutShippingViewModel model = new CheckoutShippingViewModel();

            Cart cart = GetOrSetCart();

            if (cart.Items == null || cart.Items.Length == 0)
            {
                return(RedirectToAction("Index", "Cart"));
            }

            model.quote = QuoteService.CreateQuote(cart);

            model.quote.Address = new Address();

            model.Countries = CountryCodeService.GetCountries().Select(x => new SelectListItem()
            {
                Value    = x.Code,
                Text     = x.Name,
                Selected = x.Code == model.quote.Address.Country
            });

            HttpCookie newQuoteCookie = new HttpCookie("QuoteKey");

            newQuoteCookie.Value   = model.quote.QuoteKey.ToString();
            newQuoteCookie.Expires = DateTime.Now.AddDays(1);
            ControllerContext.HttpContext.Response.Cookies.Set(newQuoteCookie);

            return(View(model));
        }
示例#17
0
        public async Task GetQuoteAsync_WhenRegionCurrencySymbolIsUsd_ShouldReturnCandleCloseAsQuote()
        {
            // Arrange
            const decimal candleClose              = 100m;
            var           exchangeRateService      = new Mock <IExchangeRateService>();
            var           externalFinancialService = new Mock <IExternalFinanceService>();

            externalFinancialService
            .Setup(x => x.GetCandleAsync(It.IsAny <string>(), It.IsAny <DateTime>()))
            .ReturnsAsync(new Candle(DateTimeOffset.UtcNow, 0, 0, 0, candleClose, 1));

            var service = new QuoteService(_globalizationService, exchangeRateService.Object, externalFinancialService.Object);

            // Act
            var result =
                await service.GetQuoteAsync(
                    new QuoteRequest
            {
                Region = UsRegionName,
                Symbol = CompanySymbol,
                Date   = DateTime.Today
            });

            // Assert
            result.ShouldBe(candleClose);
        }
        public void Should_Returns_Null_When_Get_Any_Quote_By_Non_Exists_Actor()
        {
            var fakeService = new QuoteService(fakeContext.Object, new RandomService());
            var actual      = fakeService.GetAnyQuote("Brian");

            Assert.Null(actual);
        }
示例#19
0
        private async void ExchangeCliked(object sender, EventArgs e)
        {
            Currency currencyFrom = Model.OperationExchangeFromCurrency;
            Currency currencyTo   = Model.OperationExchangeToCurrency;
            decimal  amount       = Model.OperationExchangeAmount;

            Task <Quote> getQuoteTask = QuoteService.FetchQuoteAsync(currencyFrom, currencyTo);
            Quote        quote        = await getQuoteTask;

            if (quote != null)
            {
                Result result = App.QuotesGraph.UpsertQuote(quote);
                if (result != Result.Inserted && result != Result.Updated)
                {
                    SetMessage(false, "EXCHANGE QUOTE UPSERT FAILED");
                    return;
                }
            }
            else
            {
                quote = new Quote(currencyFrom, currencyTo);
                Result result = App.QuotesGraph.GetQuote(quote);
                if (result != Result.Found)
                {
                    SetMessage(false, "EXCHANGE QUOTE NOT FOUND LOCALLY");
                    return;
                }
            }
            if (!App.Account.Exchange(amount, currencyFrom, quote.Value, currencyTo))
            {
                SetMessage(false, "EXCHANGE FAILED");
                return;
            }
            SetMessage(true, "EXCHANGE SUCCESSFUL");
        }
示例#20
0
        public void Get_Frase_Dia()
        {
            // Arrange
            var frase = new Frase
            {
                Id        = 1,
                Texto     = "El testing es un belleza",
                Autor     = "Juan David Pareja Soto",
                Categoria = new Categoria
                {
                    Id     = 1,
                    Nombre = "Frases Motivacionales"
                },
                Fecha = new DateTime(2019, 10, 25)
            };

            var context   = new Mock <QuoteDbContext>();
            var dbSetMock = ServiceTestsHelper.GetMockDbSet <Frase>(frase);

            context.Setup(x => x.Set <Frase>()).Returns(dbSetMock.Object);
            var repository = new Repository <Frase>(context.Object);

            // Act
            var service  = new QuoteService(repository);
            var fraseDia = service.GetByDate(new DateTime(2019, 10, 25));


            //Assert
            Assert.Equal(frase, fraseDia);
        }
示例#21
0
        public virtual ActionResult ChooseContract(Models.SearchContracts model)
        {
            QuoteService srv = new QuoteService(_commandProcessor, _queryProcessor, _currentUserFactory);

            model.Contracts = srv.GetContracts(model.Keyword);
            return(View(model));
        }
示例#22
0
        private static async Task Main(string[] args)
        {
            var configuration   = CreateConfiguration();
            var languageService = new LanguageService(new LanguageRepository(configuration));
            var authorService   = new AuthorService(languageService, new AuthorRepository(configuration));
            var quoteService    = new QuoteService(authorService, languageService, new QuoteRepository(configuration));

            var quotesDirectory = configuration["QuotesDirectory"];
            var quoteFiles      = Directory
                                  .GetFiles(quotesDirectory, "*.json")
                                  .OrderBy(Path.GetFileNameWithoutExtension);

            foreach (var quoteFile in quoteFiles)
            {
                await Spinner.StartAsync($"Importing: {Path.GetFileName(quoteFile)}",
                                         () => CreateQuotes(quoteFile, authorService, quoteService, SplitIntoChunks));

                var newQuoteFilePath      = Path.Combine(quotesDirectory, "processed", Path.GetFileName(quoteFile));
                var newQuoteDirectoryPath = Path.GetDirectoryName(newQuoteFilePath);
                if (!Directory.Exists(newQuoteDirectoryPath))
                {
                    Directory.CreateDirectory(newQuoteDirectoryPath);
                }
                File.Move(quoteFile, newQuoteFilePath);
            }
        }
示例#23
0
        public virtual ActionResult Quote(int QuoteID)
        {
            QuoteService srv = new QuoteService(_commandProcessor, _queryProcessor, _currentUserFactory);

            Domain.Model.Quote model = srv.GetModel <Domain.Model.Quote>(QuoteID);
            return(View(model));
        }
        public void Should_Returns_Any_Quote_When_Get_Any_Quote()
        {
            var fakeService = new QuoteService(fakeContext.Object, new RandomService());
            var actual      = fakeService.GetAnyQuote();

            Assert.NotNull(actual);
        }
示例#25
0
        public ListResponeMessage <QuoteInfo> GetListWithCondition(string quoteCode    = "",
                                                                   string proposalCode = "", int customerID = 0, DateTime?fromDate = null,
                                                                   DateTime?toDate     = null, int pageSize = 10, int pageIndex    = 0, string _userID = "")
        {
            ListResponeMessage <QuoteInfo> ret = new ListResponeMessage <QuoteInfo>();

            try
            {
                QuoteSeachCriteria _criteria = new QuoteSeachCriteria();
                _criteria.ProposalCode = proposalCode;
                _criteria.QuoteCode    = quoteCode;
                _criteria.CustomerID   = customerID;
                _criteria.FromDate     = fromDate;
                _criteria.ToDate       = toDate;
                _criteria.pageSize     = pageSize;
                _criteria.pageIndex    = pageIndex;

                ret.isSuccess    = true;
                ret.data         = QuoteService.GetInstance().getAllQuote(pageSize, pageIndex, _criteria, _userID);
                ret.totalRecords = ret.data.Count;
            }
            catch (Exception ex)
            {
                ret.isSuccess     = false;
                ret.err.msgCode   = "005";
                ret.err.msgString = ex.ToString();
            }
            return(ret);
        }
示例#26
0
        private void sellBtn_Click(object sender, EventArgs e)
        {
            var    quote_service = new QuoteService();
            float  quote;
            string checkcsvloc;
            int    shares;
            float  totalinvest;

            String ticker = this.tickerTBox.Text.Replace(" ", "");


            if (ticker == null)
            {
                MessageBox.Show("Ticker box is empty");
                return;
            }
            else
            {
                quote = quote_service.Quote(ticker).Return(QuoteReturnParameter.Open);
            }

            if (sharesTBox.Text != "0")
            {
                checkcsvloc = checkTicker(csvLoc, ticker);

                if (checkcsvloc != null)
                {
                    var strLines = File.ReadLines(csvLoc);
                    foreach (var line in strLines)
                    {
                        if (line.Split(',')[1].Equals(ticker))
                        {
                            shares      = Int32.Parse(line.Split(',')[2]) - Int32.Parse(this.sharesTBox.Text);
                            totalinvest = float.Parse(line.Split(',')[3]) - (quote * float.Parse(this.sharesTBox.Text));



                            line.Split(',')[2] = shares.ToString();
                            line.Split(',')[3] = totalinvest.ToString();
                        }
                        else
                        {
                            MessageBox.Show("Something when wrong with buy a share\n");
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("You currently do not own any shares in thsi company");
                    return;
                }
            }
            else
            {
                MessageBox.Show("You cannot buy 0 or less shares");
                return;
            }
        }
示例#27
0
        private static void UpdatePortfolio(Dictionary <string, Tuple <int, int> > buyOrSellInfo, DateTime forDate)
        {
            foreach (var item in buyOrSellInfo)
            {
                var stock  = item.Key;
                var isSell = (item.Value.Item2 > DistinctSelles);
                var isBuy  = (item.Value.Item1 >= DistinctByers) && !isSell;


                var repository  = new Repository.Repository();
                var stockEntity = repository.GetPortfolio().Result.FirstOrDefault(s => s.Stock.Equals(stock));
                var ticker      = repository.GetTickers().FirstOrDefault(t => t.FullName.Equals(stock));
                //post in not one of the stocks in list to follow
                if (ticker == null)
                {
                    continue;
                }
                var price = QuoteService.GetHistoricalPrice(ticker.TickerName, forDate);
                if (price.Last == null)
                {
                    continue;
                }

                var addBuyToPortfolio  = (stockEntity == null && isBuy);
                var addSellToPortfolio = stockEntity != null && isSell;
                var calcPrice          = Double.Parse(price.Last, System.Globalization.CultureInfo.InvariantCulture);
                var number             = 10000 / Double.Parse(price.Last,
                                                              System.Globalization.CultureInfo.
                                                              InvariantCulture);

                if (addBuyToPortfolio)
                {
                    repository.StoreTransaction(stock, forDate, "Köp", number, calcPrice, 10000, 0);
                    repository.AddPostToPortfolio(new Portfolio
                    {
                        Stock        = stock,
                        BuyPrice     = calcPrice,
                        BuyAmount    = 10000,
                        BuyNumber    = number,
                        BuyDate      = forDate,
                        CurrentPrice = calcPrice
                    }
                                                  );
                }
                else if (addSellToPortfolio)
                {
                    if (forDate > stockEntity.BuyDate)
                    {
                        var entity = repository.Context.Portfolio.First(i => i.Id.Equals(stockEntity.Id));
                        repository.Context.Portfolio.Remove(entity);
                        repository.SaveChanges();
                        var todaysPrice = Double.Parse(QuoteService.GetTodaysPrice(ticker.TickerName).Last, System.Globalization.CultureInfo.InvariantCulture);
                        repository.StoreTransaction(stock, forDate, "Försäljning", stockEntity.BuyNumber, todaysPrice,
                                                    (calcPrice * stockEntity.BuyNumber),
                                                    (calcPrice * stockEntity.BuyNumber) - 10000);
                    }
                }
            }
        }
示例#28
0
        public virtual ActionResult EnterCurrent(int ContractID)
        {
            QuoteService srv = new QuoteService(_commandProcessor, _queryProcessor, _currentUserFactory);

            Domain.Model.EnterCurrentQuote model = srv.GetModel <Domain.Model.EnterCurrentQuote>(ContractID.ToString());
            LoadContractTermData(srv);
            return(View(model));
        }
示例#29
0
        public SingleResponeMessage <QuoteInfo> GetByCode(string code, string _userID)
        {
            SingleResponeMessage <QuoteInfo> ret = new SingleResponeMessage <QuoteInfo>();

            ret.isSuccess = true;
            ret.item      = QuoteService.GetInstance().GetQuoteDetailsBycode(code, _userID);
            return(ret);
        }
示例#30
0
        public SingleResponeMessage <QuoteInfo> Get(int id, string _userID)
        {
            SingleResponeMessage <QuoteInfo> ret = new SingleResponeMessage <QuoteInfo>();

            ret.isSuccess = true;
            ret.item      = QuoteService.GetInstance().getQuote(id, _userID);
            return(ret);
        }
示例#31
0
    protected async void QuoteButton_OnClick(object sender, EventArgs e)
    {
        var symbols = txtSymbols.Text;

        try
        {
            AlterWindowState();
            var qs = new QuoteService();
            var quotes = qs.GetStockQuoteAsync(symbols.Trim().ToUpperInvariant());
            UpdateGrid(await quotes);            
        }
        finally
        {
            AlterWindowState(false);
        }
    }