public async Task <IActionResult> AddBuyerToTrade(int tradeId, [FromBody] BuyerDto buyerdto) { if (tradeId != buyerdto.StockTradeId) { return(BadRequest("Trade id doesnt match")); } StockTrade stockTrade = _stockTraderBrokerService.UpdateBuyerOnStockTrade(buyerdto.StockTradeId, buyerdto.StockBuyerId); if (stockTrade == null) { return(BadRequest($"No trades with the id found")); } string json = JsonConvert.SerializeObject(stockTrade); HttpResponseMessage response = await _client.PostAsync(_tobinApiString, new StringContent(json, Encoding.UTF8, "application/json")); string responseResult = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var stockTradeResponse = JsonConvert.DeserializeObject <StockTrade>(responseResult); _stockTraderBrokerService.DeleteStockTrade(stockTradeResponse.Id); return(Ok(stockTradeResponse)); } else { return((IActionResult)response); } }
public async Task <IActionResult> PutStockTrade(long id, StockTrade stockTrade) { if (id != stockTrade.ID) { return(BadRequest()); } _context.Entry(stockTrade).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StockTradeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task <ActionResult <StockTrade> > PostStockTrade(StockTrade stockTrade) { _context.StockTrades.Add(stockTrade); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetStockTrade), new { id = stockTrade.ID }, stockTrade)); }
public async Task <IActionResult> RequestTrade([FromBody] BuyerDto user) { if (user == null) { return(BadRequest()); } string userJson = JsonConvert.SerializeObject(user); HttpResponseMessage response = await client.PutAsync(TraderBrokerApiRequestTradeUri + "/" + user.StockTradeId + "/buy", new StringContent(userJson, Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { string responseResult = await response.Content.ReadAsStringAsync(); StockTrade stockTradeResponse = JsonConvert.DeserializeObject <StockTrade>(responseResult); if (stockTradeResponse != null && stockTradeResponse.StockTransferComplete != false && stockTradeResponse.TransactionComplete != false) { return(Ok(stockTradeResponse)); } else { return(BadRequest("Something went wrong")); } } return((IActionResult)response); }
public ActionResult Create([Bind(Include = "StockTradeID,Ticker,TradeDate,Account,AmountTraded,BoughtYes,Price,Commission,User")] StockTrade stockTrade) { if (ModelState.IsValid) { db.StockTrades.Add(stockTrade); // Add to stock holdings StockHolding h = new StockHolding(); h = db.StockHoldings.FirstOrDefault(x => x.Ticker == stockTrade.Ticker && x.StockAccount == stockTrade.Account); if (h != null) { // Found stock in this Stock Account h.NumberShares += stockTrade.AmountTraded; db.Entry(h).State = EntityState.Modified; } else { // Add new holding h.Ticker = stockTrade.Ticker; h.NumberShares = stockTrade.AmountTraded; h.StockAccount = stockTrade.Account; db.StockHoldings.Add(h); } db.SaveChanges(); return(RedirectToAction("Index")); } return(View(stockTrade)); }
public void AddStockTrade(StockTrade stockTrade) { if (stockTrade != null) { _dbContext.StockTrades.Add(stockTrade); _dbContext.SaveChanges(); } }
public ActionResult DeleteConfirmed(int id) { StockTrade stockTrade = db.StockTrades.Find(id); db.StockTrades.Remove(stockTrade); db.SaveChanges(); return(RedirectToAction("Index")); }
public async Task <IActionResult> addTransaction([FromBody] StockTrade transaction) { //string json = JsonConvert.SerializeObject(transaction); User buyer = new User { Id = (int)transaction.StockBuyerId }; User seller = new User { Id = transaction.StockSellerId }; UsersDto usersDto = new UsersDto { Seller = seller, Buyer = buyer }; var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = new Uri(UsersApiUri + "/GetTransactionUsers"), Content = new StringContent(JsonConvert.SerializeObject(usersDto), Encoding.UTF8, "application/json") }; HttpResponseMessage responseUsers = await client.SendAsync(request); string responseResultUsers = await responseUsers.Content.ReadAsStringAsync(); if (responseUsers.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } UsersDto usersDtoResponse = JsonConvert.DeserializeObject <UsersDto>(responseResultUsers); usersDtoResponse.Buyer.Balance -= ((transaction.StockPrice * transaction.StockAmount) + (Double)transaction.TaxAmount); usersDtoResponse.Seller.Balance += transaction.StockPrice * transaction.StockAmount; string usersDtoString = JsonConvert.SerializeObject(usersDtoResponse); HttpResponseMessage responseUsersUpdate = await client.PutAsync(UsersApiUri + "/", new StringContent(usersDtoString, Encoding.UTF8, "application/json")); string responseSellerResultUpdate = await responseUsersUpdate.Content.ReadAsStringAsync(); if (responseUsersUpdate.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } transaction.TransactionComplete = true; string tradeDtoString = JsonConvert.SerializeObject(transaction); HttpResponseMessage responsePSO = await client.PostAsync(PSOApiUri, new StringContent(tradeDtoString, Encoding.UTF8, "application/json")); if (responsePSO.StatusCode != HttpStatusCode.OK) { return(BadRequest(responsePSO.Content)); } transaction.StockTransferComplete = true; return(Ok(transaction)); }
public ActionResult Edit([Bind(Include = "StockTradeID,Ticker,TradeDate,Account,AmountTraded,BoughtYes,Price,Commission,User")] StockTrade stockTrade) { if (ModelState.IsValid) { db.Entry(stockTrade).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(stockTrade)); }
static void Main(string[] args) { var stock = new StockTrade(); var bsc = new BuysStockOrder(stock); var ssc = new SellStockOrder(stock); var agent = new Agent(); agent.PlaceOrder(bsc); agent.PlaceOrder(ssc); }
public TaxRegistration CreatetaxRegistrationFromTransaction(StockTrade transaction) { double tax = ((transaction.StockAmount * transaction.StockPrice) / 100) * taxPercentage; transaction.TaxAmount = tax; return(new TaxRegistration { Approved = false, TaxAmount = tax, StockTransactionId = transaction.Id, }); }
public bool TransferStocks(StockTrade trade, Stock stock) { var transferComplete = false; if (trade.TransferStockId > 0 && trade.TransferStockId == stock.Id) { var seller = _publicShareOwnerRepository.GetStockTrader(trade.StockSellerId); var buyer = _publicShareOwnerRepository.GetStockTrader(trade.StockBuyerId); if (seller != null && buyer != null) { var portefolioSeller = JsonConvert.DeserializeObject <List <KeyValuePair <int, int> > >(seller.Portefolio.StockShares); var index = portefolioSeller.FindIndex(x => x.Key == stock.Id); if (index == -1) { return(false); } var stockShare = portefolioSeller[index]; if (stockShare.Key == stock.Id && stockShare.Value >= trade.StockAmount) { var updatedShare = new KeyValuePair <int, int>(stock.Id, stockShare.Value - trade.StockAmount); seller.Portefolio.TotalAmount -= trade.StockAmount; seller.Portefolio.TotalPrice -= stock.Price * trade.StockAmount; portefolioSeller.RemoveAt(index); portefolioSeller.Add(updatedShare); seller.Portefolio.StockShares = JsonConvert.SerializeObject(portefolioSeller); _publicShareOwnerRepository.UpdateStockTrader(seller); var portefolioBuyer = JsonConvert.DeserializeObject <List <KeyValuePair <int, int> > >(buyer.Portefolio.StockShares); index = portefolioBuyer.FindIndex(x => x.Key == stock.Id); if (index != -1) { stockShare = portefolioBuyer[index]; updatedShare = new KeyValuePair <int, int>(stock.Id, stockShare.Value + trade.StockAmount); portefolioBuyer.RemoveAt(index); buyer.Portefolio.StockShares = JsonConvert.SerializeObject(portefolioBuyer); } else { updatedShare = new KeyValuePair <int, int>(stock.Id, trade.StockAmount); } buyer.Portefolio.TotalAmount += trade.StockAmount; buyer.Portefolio.TotalPrice += stock.Price * trade.StockAmount; portefolioBuyer.Add(updatedShare); buyer.Portefolio.StockShares = JsonConvert.SerializeObject(portefolioBuyer); _publicShareOwnerRepository.UpdateStockTrader(buyer); transferComplete = true; } } } return(transferComplete); }
public void Start() { StockTrade st = new StockTrade(); Command buyStock = new BuyStockOrder(st); Command sellStock = new SellStockOrder(st); Agent agent = new Agent(); agent.SetCommand(buyStock); agent.SetCommand(sellStock); agent.DoAction(); agent.Undo(); }
public void AddStockTrade(SellerDto sellerDto) { StockTrade stockTrade = new StockTrade { StockSellerId = sellerDto.StockSellerId, TransferStockId = sellerDto.TransferStockId, StockAmount = sellerDto.StockAmount, StockPrice = sellerDto.StockPrice, StockTransferComplete = false, TransactionComplete = false }; _repo.AddStockTrade(stockTrade); }
public void Test_BLL_VirtualTrader_Trading_doublePeak_GetBestROI() { var actual = trading.GetBestTradeYield(doublePeak_3days_1day_decimal_array); var expected = new StockTrade() { BuyPrice = 2, BuyWeek = 6, SellPrice = 16, SellWeek = 7 }; Assert.IsTrue(actual.BuyWeek == expected.BuyWeek); Assert.IsTrue(actual.BuyPrice == expected.BuyPrice); Assert.IsTrue(actual.SellWeek == expected.SellWeek); Assert.IsTrue(actual.SellPrice == expected.SellPrice); }
// GET: StockTrades/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } StockTrade stockTrade = db.StockTrades.Find(id); if (stockTrade == null) { return(HttpNotFound()); } return(View(stockTrade)); }
private static int FindMerrillStockTrade(ReconciliationLib.HugoDataSet.MerrillStockTradesDataTable merrillStockTrades, List <int> matchedMerrillTradeIds, StockTrade hugoStockTrade) { foreach (ReconciliationLib.HugoDataSet.MerrillStockTradesRow merrillRow in merrillStockTrades.Rows) { StockTrade merrillStockTrade = new StockTrade(merrillRow); if (!matchedMerrillTradeIds.Contains(merrillStockTrade.TradeId.Value)) { if (merrillStockTrade.Equals(hugoStockTrade)) { return(merrillRow.TradeId); } } } return(-1); }
public static void Main() { IStockTrade receiver = new StockTrade("MSFT", 1200); OrderCommand buyCommand = new BuyOrderCommand(receiver); OrderCommand sellCommand = new SellOrderCommand(receiver); Agent agent = new Agent(); agent.PlaceOrder(buyCommand); agent.PlaceOrder(buyCommand); agent.PlaceOrder(buyCommand); agent.ExecuteOrder(); agent.Revert(3); }
public StockTrade UpdateBuyerOnStockTrade(int stockTradeId, int buyerId) { StockTrade stockTrade = _repo.GetById(stockTradeId); if (stockTrade != null) { stockTrade.StockBuyerId = buyerId; _repo.UpdateStockTrade(stockTrade); return(stockTrade); } else { return(null); } }
public static bool BuyStock(StockTrade trade) { if (trade.Price > CurrentUser.AvailableMoney) { return(false); } if (CurrentUser.StockAmount.ContainsKey(trade.StockCode) && CurrentUser.StockAmount[trade.StockCode].HoldHandAmount > 3) { return(false); } //生成交易记录 var stockRecord = new TradingRecord() { StockCode = trade.StockCode, StockName = trade.StockName, UserId = CurrentUser.UserId, TradingTpye = TradingTpye.Buy, Price = trade.Price, Amount = AmountUnitity.BuyAmount(trade.Price), DataDate = DateTime.Now.ToString("yyyy-MM-dd"), IsChecked = false }; stockRecord.CalculateServiceCharge(); Console.WriteLine($"买入股票{trade.StockName}{stockRecord.Amount}股,单价{trade.Price},手续费共{stockRecord.TotalServiceCharge}"); CurrentUser.AvailableMoney = CurrentUser.AvailableMoney - stockRecord.TotalPrice - stockRecord.TotalServiceCharge; //减去手续费 TradingRecordCore.Insert(stockRecord); if (CurrentUser.StockAmount.ContainsKey(trade.StockCode)) { CurrentUser.StockAmount[trade.StockCode].HoldAmount += stockRecord.Amount; } else { CurrentUser.StockAmount.Add(trade.StockCode, new StockAmount() { HoldAmount = stockRecord.Amount, AvailableAmount = 0, }); } return(true); }
// add order to history (buyer, seller) private async Task <bool> addOrderToHistory(StockOrder stockBuy, StockOrder stockSell) { StockTrade strade = new StockTrade(); strade.BuyerID = stockBuy.UserID; strade.SellerID = stockSell.UserID; strade.StockID = stockBuy.StockID; strade.StockCount = stockBuy.StockCount; strade.Price = stockSell.PriceLimit; strade.Created = DateTime.Now; await _context.StockTrades.AddAsync(strade); await _context.SaveChangesAsync(); return(true); }
public StockTrade GetBestTradeYield(decimal [] dailySharePrices) { KeyValuePair <int, decimal>[] orderedByMinFirst = OrderByMinFirst(dailySharePrices .Take(dailySharePrices.Length - 1).ToArray()); KeyValuePair <int, decimal>[] orderedByMaxFirst = OrderByMaxFirst(dailySharePrices .Skip(1).Take(dailySharePrices.Length - 1).ToArray()); StockTrade stockTrade = new StockTrade(); int indexBestBuy = 0; decimal strongestChange = 0; foreach (var kvp in orderedByMinFirst) { indexBestBuy = kvp.Key; // search for higher price values only after the index of the current lowest price: var higherLaterBestPrice = orderedByMaxFirst .Where(p => p.Key > indexBestBuy - 1 && p.Value > kvp.Value) .OrderByDescending(p => p.Value) .ThenBy(q => q.Key).FirstOrDefault(); decimal difference = higherLaterBestPrice.Value - kvp.Value; // if we can get same ROI in shorter time.. if (difference > strongestChange || (difference == strongestChange && stockTrade.SellWeek - stockTrade.BuyWeek > higherLaterBestPrice.Key - kvp.Key)) { stockTrade.ROI = difference; stockTrade.BuyPrice = kvp.Value; stockTrade.SellPrice = higherLaterBestPrice.Value; stockTrade.BuyWeek = indexBestBuy; stockTrade.SellWeek = higherLaterBestPrice.Key; strongestChange = difference; } } // normalise week index to week numbers: stockTrade.BuyWeek += 1; stockTrade.SellWeek += 2; return(stockTrade); }
/// <summary> /// 获取当日成交 /// </summary> public List <StockTrade> GetTodayTrades(ChildAccount child) { var result = Core.ServiceManager.QueryTrades(child.Parent); if (result.Result) { var list = new List <StockTrade>(); var lines = result.Data.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in lines) { list.Add(StockTrade.Parse(line)); } var childStockCodes = Core.StockManager.GetStockCodes(child.ChildID); return(list.Where(e => childStockCodes.Contains(e.StockCode)).ToList()); } throw new Exception(result.Error); }
public ActionResult Populate() { int max = 1000000; Random rnd = new Random(); var symbolList = GetSymbolList(); for (int i = 0; i <= max; i++) { Db.TransactAsync(() => { StockTrade row = Db.Insert <StockTrade>(); row.Amount = rnd.Next(10, 1000); row.StockSymbol = symbolList.OrderBy(e => Guid.NewGuid()).First(); }); } return(Content("Populated!")); }
public static bool SellStock(StockTrade trade) { if (!CurrentUser.StockAmount.ContainsKey(trade.StockCode) || CurrentUser.StockAmount[trade.StockCode].AvailableAmount > 0) { return(false); } var firstAvailableTrade = TradingRecordCore.GetLatestBuyRecord(CurrentUser.UserId, trade.StockCode); if (firstAvailableTrade == null || firstAvailableTrade.Amount <= 0) { return(false); } //生成交易记录 var stockRecord = new TradingRecord() { StockCode = trade.StockCode, StockName = trade.StockName, UserId = CurrentUser.UserId, TradingTpye = TradingTpye.Sell, Price = trade.Price, Amount = firstAvailableTrade.Amount, DataDate = DateTime.Now.ToString("yyyy-MM-dd"), IsChecked = true }; stockRecord.CalculateServiceCharge(); Console.WriteLine($"卖出股票{trade.StockName}{stockRecord.Amount}股,单价{trade.Price},手续费共{stockRecord.TotalServiceCharge}"); CurrentUser.AvailableMoney = CurrentUser.AvailableMoney + stockRecord.TotalPrice - stockRecord.TotalServiceCharge; //减去手续费 CurrentUser.StockAmount[trade.StockCode].HoldAmount -= stockRecord.Amount; CurrentUser.StockAmount[trade.StockCode].AvailableAmount -= stockRecord.Amount; TradingRecordCore.Insert(stockRecord); TradingRecordCore.SetChecked(firstAvailableTrade.Id); return(true); }
public void Start() { if (fileStr.Length > 0) { fileStr = RemoveEmptyValues(fileStr); decimal [] dailySharePrices = ConvertCsvToSharePrices(fileStr); if (dailySharePrices.Any()) { StockTrade stockTrade = GetBestTradeYield(dailySharePrices); resultText = string.Format("{0}({1}),{2}({3})", stockTrade.BuyWeek, stockTrade.BuyPrice, stockTrade.SellWeek, stockTrade.SellPrice); if (stockTrade.BuyPrice >= stockTrade.SellPrice) { resultText += "\r\n[unable to return profit.]"; } Console.WriteLine(resultText); } } }
public async Task <IActionResult> TransferStocks([FromBody] StockTrade trade) { if (trade == null || trade.StockTransferComplete == true) { return(BadRequest("Trade object is null or stock transfer is already complete")); } HttpResponseMessage response = await client.GetAsync(getTradedShare + '/' + trade.TransferStockId); string responseResult = await response.Content.ReadAsStringAsync(); var transferStock = JsonConvert.DeserializeObject <Stock>(responseResult); if (_publicShareOwnerService.TransferStocks(trade, transferStock)) { trade.StockTransferComplete = true; return(Ok(trade)); } else { return(BadRequest("Failed to transfer stocks")); } }
private static int AddStockTrades() { // get all trades ReconciliationLib.HugoDataSet.MerrillStockTradesDataTable merrillStockTrades = ReconciliationLib.Utilities.GetMerrillStockTrades(null, false); ReconciliationLib.HugoDataSet.HugoStockTradesDataTable hugoStockTrades = ReconciliationLib.Utilities.GetHugoStockTrades(null, false); // get matched Merrill trade ids List <int> matchedMerrillTradeIds = new List <int>(); foreach (ReconciliationLib.HugoDataSet.HugoStockTradesRow hugoRow in hugoStockTrades.Rows) { int merrillTradeId = FindMerrillStockTrade(merrillStockTrades, matchedMerrillTradeIds, new StockTrade(hugoRow)); if (merrillTradeId >= 0) { matchedMerrillTradeIds.Add(merrillTradeId); } } // add all unmatched trades int nAddedTrades = 0; foreach (ReconciliationLib.HugoDataSet.MerrillStockTradesRow merrillRow in merrillStockTrades.Rows) { StockTrade stockTrade = new StockTrade(merrillRow); if (!matchedMerrillTradeIds.Contains(stockTrade.TradeId.Value)) { if (VerifyStockTrade(stockTrade)) { if (null != ReconciliationLib.Utilities.AddStockTrade(stockTrade)) { nAddedTrades++; } } } } return(nAddedTrades); }
public async Task <IActionResult> AddTransactionAsync([FromBody] StockTrade transaction) { if (transaction == null) { return(BadRequest()); } var newtaxRegistration = _tobinService.CreatetaxRegistrationFromTransaction(transaction); string json = JsonConvert.SerializeObject(transaction); HttpResponseMessage response = await client.PostAsync(TransactionBase + TransactionApiPostString, new StringContent(json, Encoding.UTF8, "application/json")); string responseResult = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { _dbContext.addTaxRegistration(newtaxRegistration); return(Ok(responseResult)); } else { return(BadRequest()); } }
public BuyStockOrder(StockTrade stock) { this.stock = stock; }
public SellStockOrder(StockTrade stock) { _stock = stock; }
public BuysStockOrder(StockTrade stock) { _stock = stock; }