internal bool SendClearingOrder(string time, uint number) { if (SellOrder.ContainsValue(number) && SellOrder.Remove(SellOrder.First(o => o.Value == number).Key) && Residue.Remove(number)) { if (verify) { statement.Enqueue(new Conclusion { Time = ConvertDateTime(time), Division = string.Concat(sell, cancel), Price = string.Empty, OrderNumber = number.ToString("N0") }); } return(true); } if (BuyOrder.ContainsValue(number) && BuyOrder.Remove(BuyOrder.First(o => o.Value == number).Key) && Residue.Remove(number)) { if (verify) { statement.Enqueue(new Conclusion { Time = ConvertDateTime(time), Division = string.Concat(buy, cancel), Price = string.Empty, OrderNumber = number.ToString("N0") }); } return(true); } return(false); }
/// <summary> /// 验证权限:公司 /// </summary> /// <param name="userModel"></param> /// <param name="order"></param> /// <param name="msg"></param> /// <returns></returns> protected static bool CheckAuthFinanceOrder(UserModel userModel, BuyOrder order, out string msg) { var statusFinished = new List <int>() { (int)BuyOrderStatusEnum.PurchasePay, (int)BuyOrderStatusEnum.StockInPay, }; if (statusFinished.Exists(p => p == order.Status)) { msg = "订单已付款完结,操作失败"; return(false); } var status = new List <int>() { (int)BuyOrderStatusEnum.PurchaseUnpay, (int)BuyOrderStatusEnum.StockInUnpay, }; if (!status.Exists(p => p == order.Status)) { msg = "订单已锁定,操作失败"; return(false); } msg = null; return(true); }
internal void SetBuyConclusion(string time, double price, int residue) { var key = price.ToString("F2"); if (BuyOrder.TryGetValue(key, out uint number)) { if (Residue[number] + residue > 0) { Residue[number] = Residue[number] + residue; return; } if (BuyOrder.Remove(key) && Residue.Remove(number)) { if (verify) { statement.Enqueue(new Conclusion { Time = ConvertDateTime(time), Division = string.Concat(buy, conclusion), Price = price.ToString("F2"), OrderNumber = number.ToString("N0") }); } Quantity += 1; SetConclusion(price); } } }
private void CreateRandomBuyOrder(Trader trader) { if (trader.BuyOrders.Count >= trader.maxBuyOrders) { return; } BuyOrder order = new BuyOrder { Trader = trader }; var items = Program.dataBase.items.ToList(); if (items.Count > 0) { int num = rand.Next(0, items.Count); Item item = items[num]; int count = 5; int price = ((int)(trader.Money / trader.maxBuyOrders) / count); long changeTime = DateTime.Now.AddMinutes(5).DateToLong(); long expireTime = DateTime.Now.AddDays(3).DateToLong(); order.Item = item; order.price = price; order.count = count; order.allowChangeTime = changeTime; order.expireTime = expireTime; trader.Money -= (price * count); Program.dataBase.buyOrders.Add(order); Program.dataBase.SaveChanges(); } }
public bool Update() { BuyOrder cache = null; if (Id.HasValue) { cache = Repository?.BuyOrders?.FirstOrDefault(x => x.Id == Id.Value); } var result = false; if (cache != null) { cache.Id = Id.Value; cache.NumbersToBuy = NumbersToBuy; cache.BuyPrice = BuyPrice; cache.BuyComment = BuyComment; cache.BuyDate = BuyDate; try { Repository?.SubmitChanges(); result = true; } catch (Exception) { //throw; } } return(result); }
public BuyOrderForm(BuyOrder order) : base() { InitializeComponent(); this.order = order; LoadFields(); }
public async Task <string> Buy([FromBody] BuyOrder buyOrder) { Console.Out.WriteLine("BuyService recieved order:" + buyOrder.BuyerId + "\n" + buyOrder.MaxPrice + "\n" + buyOrder.Quantity + "\n" + buyOrder.TickerSymbol); HttpResponseMessage response; try { response = await BrokerService.SubmitBuyOrder(buyOrder); } catch (Exception e) { return(e.Message); } if (response.IsSuccessStatusCode) { Console.Out.WriteLine("BuyService: " + Resource.order_submitted_ok); return(Resource.order_submitted_ok); } Console.Out.WriteLine("BuyService: " + Resource.order_submitted_error); return(Resource.order_submitted_error); }
public int TrySell(IBuyerSeller seller, Item item, int count, decimal price) { DealResult result = DealResult.Success; var list = Program.dataBase.buyOrders; BuyOrder buyOrder = list.Aggregate((i1, i2) => i1.price < i2.price ? i1 : i2); if (count > buyOrder.count) { count = buyOrder.count; result = DealResult.Partial; } decimal summ = price * count; seller.Money += summ; Cargo cargo = buyOrder.Trader.Cargos.FirstOrDefault(c => c.itemId == item.id); cargo.count += count; buyOrder.count -= count; if (buyOrder.count == 0) { buyOrder.Trader.BuyOrders.Remove(buyOrder); Program.dataBase.buyOrders.Remove(buyOrder); } Program.dataBase.SaveChanges(); return((int)result); }
public void AddBuyOrder() { var isAddBuyOrder = !string.IsNullOrWhiteSpace(FieldAddBuyOrder); if (isAddBuyOrder) { var buyOrder = new BuyOrder { BuyComment = FieldBuyComment }; decimal fieldBuyPrice; var isSuccess = decimal.TryParse(FieldBuyPrice, NumberStyles.Float, CultureInfo.InvariantCulture, out fieldBuyPrice); buyOrder.BuyPrice = isSuccess ? fieldBuyPrice : (decimal?)null; long numbersToBuy; isSuccess = long.TryParse(FieldNumbersToBuy, NumberStyles.Integer, CultureInfo.InvariantCulture, out numbersToBuy); buyOrder.NumbersToBuy = isSuccess ? numbersToBuy : (long?)null; if (fieldBuyPrice != 0 && numbersToBuy != 0) { buyOrder.Buy(); } } }
void Awake() { variables = GameObject.FindObjectOfType(typeof(Variables)) as Variables; shareHolder = GameObject.FindObjectOfType(typeof(ShareHolder)) as ShareHolder; lastTradesList = GameObject.FindObjectOfType(typeof(LastTradesList)) as LastTradesList; buyOrder = GameObject.FindObjectOfType(typeof(BuyOrder)) as BuyOrder; sellOrder = GameObject.FindObjectOfType(typeof(SellOrder)) as SellOrder; }
public void MarketplaceTest_Buy() { var target = new Marketplace("Iron Market"); var order = new BuyOrder("Iron Ore", 1ul, 100ul, new Account(100ul)); target.Buy(order); Assert.AreEqual(1, target.BuyOrders.Count); }
public Deal(BuyOrder buyOrder, SellOrder sellOrder, decimal price, int qty) { BuyOrderDate = buyOrder.CreatedAt; SellOrderDate = sellOrder.CreatedAt; Price = price; Qty = qty; SellerEmail = sellOrder.Email; BuyerEmail = buyOrder.Email; }
public async Task <IActionResult> Buy([FromBody] BuyOrder buyOrder) { Console.Out.WriteLine($"Received buyorder with " + $"{nameof(buyOrder.Quantity)}={buyOrder.Quantity}, " + $"{nameof(buyOrder.TickerSymbol)}={buyOrder.TickerSymbol}, " + $"{nameof(buyOrder.MaxPrice)}={buyOrder.MaxPrice}"); var buyRecord = SaveOrderToDatabase(buyOrder); var sellRecord = FindMatchingOrder(buyRecord); if (sellRecord == null) { Response.StatusCode = 202; var noMatchFoundWillBuyLater = "No match found. Will buy later."; Console.Out.WriteLine(noMatchFoundWillBuyLater); return(Json(new { status = noMatchFoundWillBuyLater })); } var changeOwnershipObject = new ChangeOwnershipObject { BuyerId = buyRecord.BuyerId, Quantity = sellRecord.Quantity, SellerId = sellRecord.SellerId, TickerSymbol = sellRecord.TickerSymbol }; if (await _registryService.ChangeOwnershipAsync(changeOwnershipObject) == false) { Response.StatusCode = 503; var couldNotChangeOwnership = "Could not change ownership."; Console.Out.WriteLine(couldNotChangeOwnership); return(Json(new { status = couldNotChangeOwnership })); } UpdateRecordsOnMatch(sellRecord, buyRecord); var taxNotifyObject = new TaxNotifyObject { SellerId = sellRecord.SellerId, TotalPrice = sellRecord.Price * sellRecord.Quantity }; if (await _taxService.InformTaxTobin(taxNotifyObject) == false) { Response.StatusCode = 503; var taxWasNotApplied = "Tax was not applied."; Console.Out.WriteLine(taxWasNotApplied); return(Json(new { status = taxWasNotApplied })); } Response.StatusCode = 201; var matchFoundWasBought = "Match found. Was bought."; Console.Out.WriteLine(matchFoundWasBought); return(Json(new { status = matchFoundWasBought })); }
/// <summary> /// Imports an enumeration of API objects. /// </summary> /// <param name="src">The orders to import.</param> /// <param name="issuedFor">Whether the orders were issued for a character or /// corporation.</param> /// <param name="ended">The location to place ended orders.</param> /// <returns>The list of expired orders.</returns> internal void Import(IEnumerable <EsiOrderListItem> src, IssuedFor issuedFor, ICollection <MarketOrder> ended) { var now = DateTime.UtcNow; // Mark all orders for deletion // If they are found again on the API feed, they will not be deleted and those set // as ignored will be left as ignored foreach (var order in Items) { order.MarkedForDeletion = true; } var newOrders = new List <MarketOrder>(Items.Count); foreach (var srcOrder in src) { var limit = srcOrder.Issued.AddDays(srcOrder.Duration + MarketOrder. MaxExpirationDays); var orderFor = AdjustIssuer(issuedFor, srcOrder); if (limit >= now && orderFor != IssuedFor.None && !Items.Any(x => x.TryImport( srcOrder, orderFor, ended))) { // New order if (srcOrder.IsBuyOrder) { var order = new BuyOrder(srcOrder, orderFor, m_character); if (order.Item != null) { newOrders.Add(order); } } else { var order = new SellOrder(srcOrder, orderFor, m_character); if (order.Item != null) { newOrders.Add(order); } } } } // Add the items that are no longer marked for deletion foreach (var order in Items) { if (order.MarkedForDeletion) { ended.Add(order); } else { newOrders.Add(order); } } Items.Clear(); Items.AddRange(newOrders); }
public Order BuyPumpkin(decimal price, Guid clientId) { if (!_clientsRepository.Exist(clientId)) { return(null); } var newBuyOrder = new BuyOrder(price, clientId); return(_ordersRepository.Add(newBuyOrder)); }
void Start() { buyOrder = GameObject.FindObjectOfType(typeof(BuyOrder)) as BuyOrder; sellOrder = GameObject.FindObjectOfType(typeof(SellOrder)) as SellOrder; shareHolder = GameObject.FindObjectOfType(typeof(ShareHolder)) as ShareHolder; variables = GameObject.FindObjectOfType(typeof(Variables)) as Variables; InvokeRepeating("Buy", 3, 5); InvokeRepeating("Sell", 5, 3); InvokeRepeating("Limit", 3, 3); }
public static async Task <HttpResponseMessage> SubmitBuyOrder(BuyOrder buyOrder) { HttpClient.DefaultRequestHeaders.Accept.Clear(); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var srlzd = JsonConvert.SerializeObject(buyOrder); var httpOrder = new StringContent(srlzd, Encoding.UTF8, "application/json"); var httpResponse = await HttpClient.PostAsync("/buy", httpOrder); return(httpResponse); }
void Start() { variables = GameObject.FindObjectOfType(typeof(Variables)) as Variables; buyOrder = GameObject.FindObjectOfType(typeof(BuyOrder)) as BuyOrder; sellOrder = GameObject.FindObjectOfType(typeof(SellOrder)) as SellOrder; loanController = GameObject.FindObjectOfType(typeof(LoanController)) as LoanController; shareHolder = GameObject.FindObjectOfType(typeof(ShareHolder)) as ShareHolder; InvokeRepeating("Buy", 3, 2); InvokeRepeating("Sell", 3, 2); InvokeRepeating("GiveLoan", 10, 10); }
public override String ToString() { return("{TransactionId: " + TransactionId + ", " + "CreatedTimestamp: " + CreatedTimestamp + ", " + "BuyOrder: " + BuyOrder.ToString() + ", " + "SellOrder: " + SellOrder.ToString() + ", " + "Ticker: " + Ticker + ", " + "Quantity: " + Quantity + ", " + "Price: " + Price.ToString("0.0000000000") + ", " + "}"); }
/// <summary> /// 验证权限:公司 /// </summary> /// <param name="userModel"></param> /// <param name="order"></param> /// <param name="msg"></param> /// <returns></returns> protected static bool CheckAuthOrder(UserModel userModel, BuyOrder order, out string msg) { if (order == null) { msg = "订单不存在,操作失败"; return(false); } msg = null; return(true); }
private static BuyOrder ToBuyOrder(Order order) { var buyOrder = new BuyOrder { ItemName = order.InvType.TypeName, ItemId = order.TypeId, MaxPrice = (long)order.MaxBuyPrice, Quantity = order.BuyQuantity, //UpdateTime = DateTime.UtcNow, }; return(buyOrder); }
public async Task <IActionResult> PutBuyOrder(long id, BuyOrder buyOrderItem) { if (id != buyOrderItem.Id) { return(BadRequest()); } _context.Entry(buyOrderItem).State = EntityState.Modified; await _context.SaveChangesAsync(); return(NoContent()); // StatCode 204 (No Content) }
/// <summary> /// 入库 /// </summary> /// <param name="userModel"></param> /// <param name="request"></param> /// <param name="msg"></param> /// <returns></returns> public bool StockIn(UserModel userModel, BuyOrder request, out string msg) { if (request == null || request.BuyOrderId == Guid.Empty) { msg = "参数错误"; return(false); } var order = Da.Get <BuyOrder>(request.BuyOrderId); var b1 = CheckAuthOrder(userModel, order, out msg); if (!b1) { return(false); } var status = new List <int>() { (int)BuyOrderStatusEnum.Purchase, (int)BuyOrderStatusEnum.PurchaseUnpay, (int)BuyOrderStatusEnum.PurchasePay, }; if (!status.Contains(order.Status)) { msg = "操作失败"; return(false); } if (order.Status == (int)BuyOrderStatusEnum.Purchase || order.Status == (int)BuyOrderStatusEnum.PurchaseUnpay) { order.Status = (int)BuyOrderStatusEnum.StockInUnpay; } else if (order.Status == (int)BuyOrderStatusEnum.PurchasePay) { order.Status = (int)BuyOrderStatusEnum.StockInPay; } else { LogHelper.Fatal("其他状态不能操作出库"); msg = "操作失败"; return(false); } // order.StockInQcUserName = request.StockInQcUserName; order.StockInRemark = request.StockInRemark; order.StockInUserName = userModel.UserNickName; order.StockInDate = DateTime.Now; return(Da.StockIn(order)); }
private async Task AddBuyOrderToDbAsync(BuyOrder order) { try { // Read the item to see if it exists. ReadItemAsync will throw an exception if the item does not exist and return status code 404 (Not found). ItemResponse <BuyOrder> searchResponse = await container.ReadItemAsync <BuyOrder>(order.id.ToString(), new PartitionKey(order.PartnerId)); } catch (CosmosException ex) when(ex.StatusCode == HttpStatusCode.NotFound) { // Create an item in the container representing the users search. Note we provide the value of the partition key for the item ItemResponse <BuyOrder> searchResponse = await container.CreateItemAsync(order, new PartitionKey(order.PartnerId)); } }
public IActionResult CreateBuyOrder(CreateOrderDto createOrderDto) { if (!ModelState.IsValid) { var errorMessage = string.Join(";", ModelState.Values.SelectMany(e => e.Errors.ToString())); return(BadRequest(errorMessage)); } BuyOrder buyOrder = createOrderDto.ToBuyOrderEntity(); _addBuyOrderUseCase.AddBuyOrder(buyOrder); return(Redirect("/")); }
/// <summary> /// Imports an enumeration of API objects. /// </summary> /// <param name="src">The orders to import.</param> /// <param name="issuedFor">Whether the orders were issued for a character or /// corporation.</param> /// <param name="ended">The location to place ended orders.</param> /// <returns>The list of expired orders.</returns> internal void Import(IEnumerable <EsiOrderListItem> src, IssuedFor issuedFor, ICollection <MarketOrder> ended) { var now = DateTime.UtcNow; // Mark all orders for deletion // If they are found again on the API feed, they will not be deleted and those set // as ignored will be left as ignored foreach (MarketOrder order in Items) { order.MarkedForDeletion = true; } var newOrders = new LinkedList <MarketOrder>(); foreach (EsiOrderListItem srcOrder in src) { var limit = srcOrder.Issued.AddDays(srcOrder.Duration + MarketOrder. MaxExpirationDays); var orderFor = issuedFor; // Orders in corporation endpoint are unconditionally for corp, the character // endpoint has a special field since *some* are for corp, why... if (srcOrder.IsCorporation) { orderFor = IssuedFor.Corporation; } if (limit >= now && !Items.Any(x => x.TryImport(srcOrder, orderFor, ended))) { // New order if (srcOrder.IsBuyOrder) { BuyOrder order = new BuyOrder(srcOrder, orderFor, m_character); if (order.Item != null) { newOrders.AddLast(order); } } else { SellOrder order = new SellOrder(srcOrder, orderFor, m_character); if (order.Item != null) { newOrders.AddLast(order); } } } } // Add the items that are no longer marked for deletion newOrders.AddRange(Items.Where(x => !x.MarkedForDeletion)); Items.Clear(); Items.AddRange(newOrders); }
protected void AddButton_Click(object sender, EventArgs e) { if (side.Text.ToString().Equals("old")) { return; } else { string str0 = getStringText(BuyOrderID.Text.ToString()); string str1 = getStringText(BuyOrderDate.Text.ToString()); string str2 = getStringText(Delegate.Text.ToString()); int storeHouseID = int.Parse(StoreHouseID.Text.ToString()); int houseDetailID = int.Parse(HouseDetailID.Text.ToString()); string str3 = getStringText(SignDate.Text.ToString()); string str4 = getStringText(TradeDate.Text.ToString()); string str5 = getStringText(TradeAddress.Text.ToString()); float totalPrice = float.Parse(TotalPrice.Text.ToString()); string str6 = getStringText(Description.Text.ToString()); BuyOrder b = new BuyOrder(); b.BuyOrderID = str0; b.BuyOrderDate = str1; b.Delegate = str2; b.Description = str6; b.HouseDetailID = houseDetailID; b.Identitys = 0; //采购订单 b.SignDate = str3; b.State = 0; //未审核 b.StoreHouseID = storeHouseID; b.TotalPrice = totalPrice; b.TradeAddress = str5; b.TradeDate = str4; b.UserName = getUserName(); if (Leyp.SQLServerDAL.Buy.Factory.getBuyOrderDAL().insertNewEntity(b)) { side.Text = "old"; Button1.Visible = true; Image1.ImageUrl = "../images/Good.gif"; Label1.Text = "表头已经保存"; AddButton.Visible = false; Jscript.AjaxAlert(this, "添加成功!"); return; } else { Jscript.AjaxAlert(this, "添加失败!"); return; } } }
/// <summary> /// In this method we validate the buy order. For the purpose of this task we are simply checking the currency pair is valid /// and the minimum accepted exchange rate has a value. /// This could be extended to check the Expiry Date hasnt passed or the partner id is valid etc. /// </summary> internal static bool IsBuyOrderValid(BuyOrder order) { bool isBuyOrderValid = false; if (OrderHelper.IsValidCurrencyPair(order.CurrencyPair)) { if (order.MinAcceptedExchangeRate > 0) { isBuyOrderValid = true; } } return(isBuyOrderValid); }
private BuyRecord SaveOrderToDatabase(BuyOrder order) { var buyRecord = new BuyRecord() { BuyerId = order.BuyerId, MaxPrice = order.MaxPrice, Quantity = order.Quantity, TickerSymbol = order.TickerSymbol }; _context.BuyRecords.Add(buyRecord); _context.SaveChanges(); return(buyRecord); }
public void Save(BuyOrder order) { var dbOrder = _dbContext.BuyOrders.FirstOrDefault(o => o.Id == order.Id); if (dbOrder != null) { dbOrder.Qty = order.Qty; } else { _dbContext.BuyOrders.Add(order); } _dbContext.SaveChanges(); }