コード例 #1
0
        [TestCase("01/01/9999", 0, "Cool, Joe jr.", "TX", 8.19, 100, "Carpet", 12.5, 6.3, 1250, 630, 153.97, 2033.97, true)] //AddOrder Should succeed!!!
        public void CanCreateValidOrder(DateTime oOrderDate, int oOrderNumber, string oCustomerName, string oState, decimal oTaxRate, decimal oArea, string oProductType, decimal oCostPerSquareFoot, decimal oLaborCostPerSquareFoot, decimal oFileMaterialCost, decimal oFileLaborCost, decimal oFileTax, decimal oFileTotal, bool expected)
        {
            Order addedOrder = new Order();

            addedOrder.OrderDate               = oOrderDate;
            addedOrder.OrderNumber             = oOrderNumber;
            addedOrder.CustomerName            = oCustomerName;
            addedOrder.OrderStateTax.StateCode = oState;
            addedOrder.OrderStateTax.TaxRate   = oTaxRate;
            addedOrder.Area = oArea;
            addedOrder.OrderProduct.ProductType            = oProductType;
            addedOrder.OrderProduct.CostPerSquareFoot      = oCostPerSquareFoot;
            addedOrder.OrderProduct.LaborCostPerSquareFoot = oLaborCostPerSquareFoot;
            addedOrder.FileMaterialCost = oFileMaterialCost;
            addedOrder.FileLaborCost    = oFileLaborCost;
            addedOrder.FileTax          = oFileTax;
            addedOrder.FileTotal        = oFileTotal;

            OrderManager  myOM   = OrderManagerFactory.Create(addedOrder.OrderDate);
            OrderResponse actual = new OrderResponse();

            actual = myOM.AddOrder(addedOrder);
            Assert.AreEqual(expected, actual.Success);
        }
コード例 #2
0
        public async Task <IActionResult> GenerateGeneralReport(DocumentPagination p)
        {
            var documents = await documentRepository.Get(p);

            var orders = new List <OrderResponse>();

            foreach (Document document in documents)
            {
                var docType     = document.Type;
                var serie       = document.Serie;
                var correlative = document.Correlative;
                var order       = new OrderResponse
                {
                    Document = document,
                    Tax      = await taxRepository.Find(docType, serie, correlative),
                    Detail   = await detailRepository.Find(docType, serie, correlative)
                };
                orders.Add(order);
            }
            ;

            var binary = reportService.GenerateOrdersReport(orders);
            // HttpResponseMessage response = new HttpResponseMessage();
            // response.Content = new ByteArrayContent(binary);
            // response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            // response.Content.Headers.ContentDisposition.FileName = $"Reporte-Ventas-{DateTime.Now.ToString("dd/MM/yyy hh:m:ss")}";
            // response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
            // return response;
            var hardcoded = Convert.ToBase64String(binary);

            return(Json(new StandardResponse
            {
                Status = 200,
                Data = hardcoded
            }));
        }
コード例 #3
0
        public Task <OrderResponse> PutLimitOrder(SideType side, ProductType productType, decimal price, decimal size, Guid?clientId, bool?postOnly)
        {
            var done = new BookDone
            {
                ProductType   = productType,
                OrderId       = Guid.NewGuid(),
                Price         = price,
                Side          = side,
                RemainingSize = size,
                Reason        = OrderReason.Filled
            };
            var reponse = new OrderResponse
            {
                CreatedAt   = DateTime.UtcNow,
                Price       = price,
                Size        = size,
                ProductType = productType,
                Id          = done.OrderId,
                Side        = side
            };

            _waitingOrder.Enqueue(done);
            return(Task.FromResult(reponse));
        }
コード例 #4
0
        /// <summary>
        /// 下单消息处理
        /// </summary>
        /// <param name="response">下单返回信息</param>
        /// <param name="request">下单请求</param>
        public void ProcessDoOrder(OrderResponse response, StockOrderRequest request)
        {
            XHMessage message = new XHMessage();

            message.BuySell        = request.BuySell == GTA.VTS.Common.CommonObject.Types.TransactionDirection.Buying ? "买" : "卖";
            message.CapitalAccount = request.FundAccountId;
            message.Code           = request.Code;
            message.EntrustAmount  = request.OrderAmount.ToString();
            message.EntrustNumber  = response.OrderId;
            message.EntrustPrice   = request.OrderPrice.ToString();
            message.EntrustType    = request.OrderWay == TypesOrderPriceType.OPTLimited ? "限价" : "市价";
            message.OrderMessage   = response.OrderMessage;
            message.OrderStatus    = "未报02";
            message.TradeAmount    = "0";
            message.TradeTime      = "";

            listLock.EnterWriteLock();
            try
            {
                xhMessageList.Add(message);
            }
            finally
            {
                listLock.ExitWriteLock();
            }

            if (!response.IsSuccess)
            {
                message.EntrustNumber = System.Guid.NewGuid().ToString();
                message.OrderStatus   = "废单06";
            }

            xhMessageCache.Add(message.EntrustNumber, message);

            HasChanged = true;
        }
コード例 #5
0
        public OrderResponse DeletingOrder(Order order)
        {
            OrderResponse response = new OrderResponse();

            if (order == null)
            {
                response.Success = false;
                return(response);
            }
            else
            {
                if (!_orderRepository.DeleteOrder(order))
                {
                    response.Success = false;
                    response.Message = "Order not found!";
                }
                else
                {
                    response.Success = true;
                }
            }

            return(response);
        }
コード例 #6
0
 internal static void Execute(DisplayMode mode, bool clearScreen, bool wait, out OrderResponse response, out OrderManager myOM)
 {
     response = null;
     myOM     = null;
     Console.Clear();
     if (!ConsoleIO.GetDateValue("Enter the date for your order ", null, out DateTime orderDate))
     {
         return;
     }
     if (!ConsoleIO.GetInt("Enter the order number: ", 1, 999999, out int orderNumber))
     {
         return;
     }
     myOM     = OrderManagerFactory.Create(orderDate);
     response = myOM.GetOrder(orderNumber);
     if (response.Success)
     {
         ConsoleIO.DisplayOrder(mode, response.Order, clearScreen, wait, ConsoleColor.Blue);
     }
     else
     {
         ConsoleIO.DisplayText(response.Message + "\nPress any key to continue...", false, true, ConsoleColor.Red);
     }
 }
コード例 #7
0
        public void Execute()
        {
            OrderManager manager = OrderManagerFactory.Create();

            Console.Clear();

            string userInput = SystemIO.OrderDateRequest();

            DateTime order = Convert.ToDateTime(userInput);

            OrderResponse response = manager.LookupOrder(order);

            if (response.Success)
            {
                SystemIO.DisplayOrderDetails(response.Order);
            }
            else
            {
                Console.WriteLine("An error occured: ");
                Console.WriteLine(response.Message);
            }

            Console.ReadKey();
        }
コード例 #8
0
        public async Task <IActionResult> Create([FromBody] OrderCreateRequest requestModel)
        {
            DateTime utcNow = DateTime.UtcNow;
            //map to entity
            Order order = OrderMapper.MapFromOrderCreateRequestToOrder(requestModel, utcNow);

            db.Orders.Add(order);

            await db.SaveChangesAsync();

            Order createdOrder = await db.Orders.IncludeAll().AsNoTracking().SingleOrDefaultAsync(o => o.Id == order.Id);

            var filePath = _excelService.CreateAndSaveFile(createdOrder);

            if (!string.IsNullOrEmpty(filePath))
            {
                _emailService.SendEmail(filePath, createdOrder.Category.Name);
            }

            //map to response
            OrderResponse orderResponse = OrderMapper.MapFromOrderToOrderResponse(order);

            return(CreatedAtAction(nameof(GetById), new { id = order.Id }, orderResponse));
        }
コード例 #9
0
 private CryptoOrderStatus ConvertOrderStatus(OrderResponse user)
 {
     /*
      *  switch (user.OrderStatus)
      *  {
      *      case OrderStatus.Undefined:
      *          break;
      *      case OrderStatus.All:
      *          break;
      *      case OrderStatus.Pending:
      *          return CryptoOrderStatus.Pending;
      *
      *      case OrderStatus.Rejected:
      *      case OrderStatus.Canceled:
      *          return CryptoOrderStatus.Canceled;
      *
      *      case OrderStatus.PartiallyFilled:
      *      {
      *          return user.Amount == 0 ? CryptoOrderStatus.Canceled : CryptoOrderStatus.PartiallyFilled;
      *      }
      *
      *      case OrderStatus.Active:
      *      case OrderStatus.Open:
      *          return CryptoOrderStatus.Active;
      *
      *      case OrderStatus.Done:
      *      case OrderStatus.Settled:
      *      case OrderStatus.Executed:
      *          return CryptoOrderStatus.Executed;
      *
      *      default:
      *          throw new ArgumentOutOfRangeException(nameof(user.OrderStatus), user.OrderStatus, null);
      *  }
      */
     return(CryptoOrderStatus.Undefined);
 }
コード例 #10
0
        private bool HandleObjectMessage(string msg)
        {
            var response = BitmexJsonSerializer.Deserialize <JObject>(msg);

            // ********************
            // ADD OBJECT HANDLERS BELOW
            // ********************

            return

                (TradeResponse.TryHandle(response, Streams.TradesSubject) ||
                 BookResponse.TryHandle(response, Streams.BookSubject) ||
                 QuoteResponse.TryHandle(response, Streams.QuoteSubject) ||
                 LiquidationResponse.TryHandle(response, Streams.LiquidationSubject) ||
                 PositionResponse.TryHandle(response, Streams.PositionSubject) ||
                 OrderResponse.TryHandle(response, Streams.OrderSubject) ||
                 WalletResponse.TryHandle(response, Streams.WalletSubject) ||


                 ErrorResponse.TryHandle(response, Streams.ErrorSubject) ||
                 SubscribeResponse.TryHandle(response, Streams.SubscribeSubject) ||
                 InfoResponse.TryHandle(response, Streams.InfoSubject) ||
                 AuthenticationResponse.TryHandle(response, Streams.AuthenticationSubject));
        }
コード例 #11
0
        public void XMLValidation_DealerAuthorized_InvalidAuthorization()
        {
            //Arrange
            string        outputFile       = @"../../XML_UnitTest_files/Response.xml";
            OrderResponse orderResponseObj = new OrderResponse();
            Order         objOrder         = new Order();

            objOrder.objDealer = new Dealer();
            objOrder.objDealer.dealeraccesskey = "kkklas8882kk23nllfjj88290";
            objOrder.objDealer.dealerid        = "XXX-1234-ABCD-1234";
            var isAuthorized = false;


            //Mock
            var mockPartManager        = new Mock <IPartManager>();
            var mockSecurity           = new Mock <ISecurity>();
            ActionController actionObj = new ActionController(mockPartManager.Object, mockSecurity.Object);

            mockSecurity.Setup(x => x.IsDealerAuthorized(objOrder.objDealer.dealerid, objOrder.objDealer.dealeraccesskey)).Returns(isAuthorized);
            mockSecurity.Setup(x => x.PopulateSecurity());
            mockPartManager.Setup(x => x.PopulatePartManager());

            //Act
            actionObj.ValidateXML(outputFile, objOrder);
            XmlSerializer deserializer = new XmlSerializer(typeof(OrderResponse));
            TextReader    reader       = new StreamReader(outputFile, System.Text.Encoding.UTF8);
            object        obj          = deserializer.Deserialize(reader);
            OrderResponse XmlData      = (OrderResponse)obj;

            reader.Close();

            //Result

            Assert.IsTrue(XmlData.result == "failure");
            Assert.IsTrue(XmlData.errormessage == "Not authorized");
        }
コード例 #12
0
        private void Handle3DSResponse(OrderResponse response)
        {
            Session["orderCode"] = response.orderCode;
            Response.Clear();

            StringBuilder sb = new StringBuilder();

            sb.Append("<html>");
            sb.AppendFormat(@"<body onload='document.forms[""submitForm""].submit()'>");
            sb.AppendFormat("<form name='submitForm' action='{0}' method='post'>", response.redirectURL);
            sb.AppendFormat("<input type='hidden' name='PaReq' value='{0}'>", response.oneTime3DsToken);
            sb.AppendFormat("<input type='hidden' name='TermUrl' id='termUrl' value='{0}'>", response.redirectURL);
            sb.AppendFormat("<input type='hidden' name='TermUrl' id='termUrl' value='{0}'>", "");
            sb.Append("<script>\n" +
                      "  document.getElementById('termUrl').value =\n" +
                      "  window.location.href.replace('CreateOrder', 'AuthorizeOrder');" +
                      "</script>");
            sb.Append("</form>");
            sb.Append("</body>");
            sb.Append("</html>");

            Response.Write(sb.ToString());
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
コード例 #13
0
        /// <summary>
        /// Handles a request to submit a new order
        /// </summary>
        private OrderResponse HandleSubmitOrderRequest(SubmitOrderRequest request)
        {
            OrderTicket ticket;
            var         order = Order.CreateOrder(request);

            // ensure the order is tagged with a currency
            var security = _algorithm.Securities[order.Symbol];

            order.PriceCurrency = security.SymbolProperties.QuoteCurrency;

            // rounds off the order towards 0 to the nearest multiple of lot size
            order.Quantity = RoundOffOrder(order, security);

            if (!_orders.TryAdd(order.Id, order))
            {
                Log.Error("BrokerageTransactionHandler.HandleSubmitOrderRequest(): Unable to add new order, order not processed.");
                return(OrderResponse.Error(request, OrderResponseErrorCode.OrderAlreadyExists, "Cannot process submit request because order with id {0} already exists"));
            }
            if (!_orderTickets.TryGetValue(order.Id, out ticket))
            {
                Log.Error("BrokerageTransactionHandler.HandleSubmitOrderRequest(): Unable to retrieve order ticket, order not processed.");
                return(OrderResponse.UnableToFindOrder(request));
            }

            // rounds the order prices
            RoundOrderPrices(order, security);

            // save current security time and prices
            order.OrderSubmissionData = new OrderSubmissionData(security.GetLastData());

            // update the ticket's internal storage with this new order reference
            ticket.SetOrder(order);

            if (order.Quantity == 0)
            {
                order.Status = OrderStatus.Invalid;
                var response = OrderResponse.ZeroQuantity(request);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Unable to add order for zero quantity"));
                return(response);
            }

            // check to see if we have enough money to place the order
            HasSufficientBuyingPowerForOrderResult hasSufficientBuyingPowerResult;

            try
            {
                hasSufficientBuyingPowerResult = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder(_algorithm.Portfolio, security, order);
            }
            catch (Exception err)
            {
                Log.Error(err);
                _algorithm.Error(string.Format("Order Error: id: {0}, Error executing margin models: {1}", order.Id, err.Message));
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Error executing margin models"));
                return(OrderResponse.Error(request, OrderResponseErrorCode.ProcessingError, "Error in GetSufficientCapitalForOrder"));
            }

            if (!hasSufficientBuyingPowerResult.IsSufficient)
            {
                order.Status = OrderStatus.Invalid;
                var errorMessage = $"Order Error: id: {order.Id}, Insufficient buying power to complete order (Value:{order.GetValue(security).SmartRounding()}), Reason: {hasSufficientBuyingPowerResult.Reason}";
                var response     = OrderResponse.Error(request, OrderResponseErrorCode.InsufficientBuyingPower, errorMessage);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, errorMessage));
                return(response);
            }

            // verify that our current brokerage can actually take the order
            BrokerageMessageEvent message;

            if (!_algorithm.BrokerageModel.CanSubmitOrder(security, order, out message))
            {
                // if we couldn't actually process the order, mark it as invalid and bail
                order.Status = OrderStatus.Invalid;
                if (message == null)
                {
                    message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidOrder", "BrokerageModel declared unable to submit order: " + order.Id);
                }
                var response = OrderResponse.Error(request, OrderResponseErrorCode.BrokerageModelRefusedToSubmitOrder, "OrderID: " + order.Id + " " + message);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "BrokerageModel declared unable to submit order"));
                return(response);
            }

            // set the order status based on whether or not we successfully submitted the order to the market
            bool orderPlaced;

            try
            {
                orderPlaced = _brokerage.PlaceOrder(order);
            }
            catch (Exception err)
            {
                Log.Error(err);
                orderPlaced = false;
            }

            if (!orderPlaced)
            {
                // we failed to submit the order, invalidate it
                order.Status = OrderStatus.Invalid;
                var errorMessage = "Brokerage failed to place order: " + order.Id;
                var response     = OrderResponse.Error(request, OrderResponseErrorCode.BrokerageFailedToSubmitOrder, errorMessage);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Brokerage failed to place order"));
                return(response);
            }

            return(OrderResponse.Success(request));
        }
コード例 #14
0
        private void ProcessInvoiceNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            foreach (var file in manager)
            {
                try
                {
                    using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data)))
                    {
                        string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv";
                        string filePath = Path.Combine(logPath, fileName);
                        using (FileStream s = File.Create(filePath))
                        {
                            s.Write(fileStream.ToArray(), 0, (int)fileStream.Length);
                        }

                        using (System.IO.TextReader readFile = new StreamReader(filePath))
                        {
                            string line = string.Empty;

                            using (MemoryStream salesLines = new MemoryStream(),
                                   salesInvoiceTotal = new MemoryStream(),
                                   salesInvoiceGrandTotal = new MemoryStream())
                            {
                                using (
                                    StreamWriter sw = new StreamWriter(salesLines),
                                    sw2 = new StreamWriter(salesInvoiceTotal),
                                    sw3 = new StreamWriter(salesInvoiceGrandTotal))
                                {
                                    int lineCount = 0;
                                    while ((line = readFile.ReadLine()) != null)
                                    {
                                        lineCount++;

                                        if (line.Contains("SalesInvoiceLine") || lineCount == 1)
                                        {
                                            sw.WriteLine(line);
                                        }
                                        else if (line.Contains("SalesInvoiceTotal"))
                                        {
                                            sw2.WriteLine(line);
                                        }
                                        else if (line.Contains("SalesInvoiceGrandTotal"))
                                        {
                                            sw3.WriteLine(line);
                                        }
                                        else if (!line.Contains("SalesInvoiceLine") && lineCount > 1 && !line.Contains("SalesInvoiceGrandTotal"))
                                        {
                                            sw3.WriteLine(line);
                                        }
                                    }

                                    sw.Flush();
                                    salesLines.Position = 0;
                                    sw2.Flush();
                                    salesInvoiceTotal.Position = 0;
                                    sw3.Flush();
                                    salesInvoiceGrandTotal.Position = 0;

                                    var parser                  = GetInvoiceCSVFile(salesLines, typeof(VSNInvoice)).ToList();
                                    var invoiveTotalParser      = GetInvoiceCSVFile(salesInvoiceTotal, typeof(VSNInvoiceTotal));
                                    var invoiceGrandTotalParser = GetInvoiceCSVFile(salesInvoiceGrandTotal, typeof(VSNInvoiceGrandTotal));

                                    var firstOrderInInvoice = parser.FirstOrDefault();
                                    var invoiceTotals       = invoiveTotalParser.ToList();
                                    int orderLineCounter    = 0;

                                    var totalAmount   = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATIncluded.ToString()]));
                                    var totalExVat    = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()]));
                                    var vatAmount     = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVAT.ToString()]));
                                    var vatPercentage = invoiceTotals.Sum(x => decimal.Parse(x[VSNInvoiceTotal.VATPercentage.ToString()]));
                                    var shipmentCost  = invoiceTotals.Where(x => x[VSNInvoiceTotal.SalesInvoiceTotal.ToString()].Trim().ToLower() == "orderkosten").Sum(x => decimal.Parse(x[VSNInvoiceTotal.AmountVATExcluded.ToString()]));

                                    #region InvoiceNotification
                                    var           vsnResponseType = responseType.ToString();
                                    var           vsnInvoiceID    = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()];
                                    OrderResponse response        = unit.Scope.Repository <OrderResponse>().GetSingle(x => x.VendorID == vendor.VendorID && x.InvoiceDocumentNumber == vsnInvoiceID && x.ResponseType == vsnResponseType);

                                    if (response == null)
                                    {
                                        response = new OrderResponse()
                                        {
                                            Currency     = "EUR",
                                            ResponseType = responseType.ToString(),
                                            //OrderID = orderID,
                                            VendorDocumentNumber     = string.Empty,
                                            InvoiceDate              = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.InvoiceDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                            InvoiceDocumentNumber    = firstOrderInInvoice[VSNInvoice.SalesInvoiceID.ToString()],
                                            ShippingNumber           = firstOrderInInvoice[VSNInvoice.PacklistID.ToString()],
                                            PaymentConditionCode     = firstOrderInInvoice[VSNInvoice.PatymentConditionName.ToString()],
                                            ReqDeliveryDate          = DateTime.ParseExact(firstOrderInInvoice[VSNInvoice.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                            PaymentConditionDiscount = firstOrderInInvoice[VSNInvoice.DiscountPercentage.ToString()],
                                            TotalAmount              = totalAmount,
                                            TotalExVat    = totalExVat,
                                            VatAmount     = vatAmount,
                                            VatPercentage = vatPercentage,
                                            ShipmentCost  = shipmentCost
                                        };
                                    }

                                    foreach (var p in parser)
                                    {
                                        try
                                        {
                                            int    lineReference  = 0;
                                            string referenceField = p[VSNInvoice.LineCustomerReference.ToString()];
                                            if (referenceField.Contains('/'))
                                            {
                                                int.TryParse(referenceField.Split('/')[0], out lineReference);
                                            }
                                            else
                                            {
                                                int.TryParse(referenceField, out lineReference);
                                            }

                                            OrderLine oLine = unit.Scope.Repository <OrderLine>().GetSingle(x => x.OrderLineID == lineReference);

                                            if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                            {
                                                OrderResponseLine rLine = new OrderResponseLine()
                                                {
                                                    OrderResponse = response,
                                                    Backordered   = 0,
                                                    Cancelled     = 0,
                                                    Ordered       = oLine.GetDispatchQuantity(),
                                                    Invoiced      = int.Parse(p[VSNInvoice.Quantity.ToString()]),
                                                    Barcode       = p[VSNInvoice.EANNumberProduct.ToString()],
                                                    OrderLine     = oLine,
                                                    Price         = decimal.Parse(p[VSNInvoice.PriceDiscountIncluded.ToString()]),
                                                    VatAmount     = decimal.Parse(p[VSNInvoice.LineTotal.ToString()]),
                                                    vatPercentage = decimal.Parse(p[VSNInvoice.VATPercentage.ToString()]),
                                                    CarrierCode   = p[VSNInvoice.DeliveryMethodName.ToString()],
                                                    Processed     = false,
                                                    Shipped       = 0,
                                                    Remark        = p[VSNInvoice.CustomerReference.ToString()]
                                                };

                                                unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                                orderLineCounter++;
                                            }

                                            #endregion
                                        }
                                        catch (Exception)
                                        {
                                            log.AuditError("Failed to invoice line for VSN");
                                        }
                                    }

                                    if (orderLineCounter > 0)
                                    {
                                        response.VendorID       = vendor.VendorID;
                                        response.ReceiveDate    = DateTime.Now;
                                        response.VendorDocument = parser + invoiveTotalParser.Document + invoiceGrandTotalParser.Document;
                                        response.DocumentName   = fileName;
                                        if (!response.VendorDocumentDate.HasValue)
                                        {
                                            response.VendorDocumentDate = DateTime.Now;
                                        }

                                        response.ReceiveDate = DateTime.Now;

                                        unit.Scope.Repository <OrderResponse>().Add(response);
                                    }

                                    unit.Save();
                                    manager.Delete(file.FileName);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.AuditError("Error reading file", ex);
                }
            }
        }
        private async Task <ExternalTrade> ExecuteLimitOrderAsync(string assetPairId, decimal volume, decimal?price, Side side)
        {
            var startedAt = DateTime.UtcNow;

            string instrument = await GetInstrumentAsync(assetPairId);

            OrderResponse orderResponse = await WrapAsync(async() =>
            {
                var orderStartedAt = DateTime.UtcNow;

                var orderRequest = new OrderRequest();

                orderRequest.ClientOrderId = Guid.NewGuid().ToString();
                orderRequest.Side          = side;
                orderRequest.Instrument    = instrument;
                orderRequest.OrderType     = OrderType.MKT;
                orderRequest.Quantity      = volume;
                orderRequest.ValidUntil    = DateTime.UtcNow.AddSeconds(3);

                _log.Info("Order request", orderRequest);

                OrderResponse order = await _client.OrderAsync(orderRequest);

                var orderFinishedAt = DateTime.UtcNow;

                _log.Info("Order response", orderRequest);

                Trade orderTrade = order.Trades.Single();

                _log.Info("Order time", new
                {
                    AssetPairId     = assetPairId,
                    Volume          = volume,
                    TradeId         = orderTrade.TradeId,
                    ClientOrderId   = orderRequest.ClientOrderId,
                    OrderId         = order.OrderId,
                    OrderStartedAt  = orderStartedAt,
                    OrderFinishedAt = orderFinishedAt,
                    Latency         = (orderFinishedAt - orderStartedAt).TotalMilliseconds
                });

                return(order);
            });

            var finishedAt = DateTime.UtcNow;

            var trade = orderResponse.Trades.Single();

            var hedgingFinishedAt = DateTime.UtcNow;

            _log.Info("Total hedge trade time", new
            {
                TradeId              = trade.TradeId,
                TradeCreated         = trade.Created,
                OrderId              = orderResponse.OrderId,
                ClientOrderId        = orderResponse.ClientOrderId,
                OrderCreated         = orderResponse.Created,
                HedgeTradeStartedAt  = startedAt,
                HedgeTradeFinishedAt = finishedAt,
                HedgeTradeTotalTime  = (finishedAt - startedAt).TotalMilliseconds
            });

            PrometheusMetrics.HedgeB2C2OrderRequestLatency.Inc((finishedAt - startedAt).TotalMilliseconds);

            return(new ExternalTrade
            {
                Id = trade.TradeId,
                LimitOrderId = trade.Order,
                AssetPairId = trade.Instrument,
                Type = trade.Side == Side.Sell ? TradeType.Sell : TradeType.Buy,
                Time = trade.Created,
                Price = trade.Price,
                Volume = trade.Quantity,
                RequestId = trade.RfqId
            });
        }
コード例 #16
0
        public OrderResponse PlacePayPalOrder(ref OBE_Order oOrder, string cardNumber, int year)
        {
            OrderResponse oValue = new OrderResponse();

            try
            {
                OBE_VerificationPayPal oVerificationPayPal = new OBE_VerificationPayPal();
                GetVerificationObject(ref oVerificationPayPal);
                DoDirectPaymentResponseType       oDPayment      = new DoDirectPaymentResponseType();
                GetTransactionDetailsResponseType oDTransDetails = new GetTransactionDetailsResponseType();
                PayPalAPI.PayPalAPI oPayPalAPI = new PayPalAPI.PayPalAPI(oVerificationPayPal.User, oVerificationPayPal.Password, oVerificationPayPal.Signature, oVerificationPayPal.Enviroment);


                try
                {
                    if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
                    {
                        if (HttpContext.Current.Session["WarrantyCheckout"] == null)
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2, oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }

                        //made up address as we don't require it for warrantyCheckout process.
                        else
                        {
                            //oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, "123 main st.", "123 main st.",
                            //HttpContext.Current.Session["city"].ToString(), "ON", "L8W1P1", "Canada", oOrder.CreditCard.CardType.ToString(),
                            //cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);

                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2,
                                                                   oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                    }
                    else
                    {
                        if (HttpContext.Current.Session["WarrantyCheckout"] == null)
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2, oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }

                        //made up address as we don't require it for warrantyCheckout process.
                        else
                        {
                            //oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, "123 main st.", "123 main st.",
                            //HttpContext.Current.Session["city"].ToString(), "ON", "L8W1P1", "Canada", oOrder.CreditCard.CardType.ToString(),
                            //cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);


                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oOrder.BillingCustomer.Address.Address1, oOrder.BillingCustomer.Address.Address2,
                                                                   oOrder.BillingCustomer.Address.City, oOrder.BillingCustomer.Address.ProvState, oOrder.BillingCustomer.Address.POCode, oOrder.BillingCustomer.Address.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);



                            HttpContext.Current.Session["WarrantyCheckout"] = null;
                        }
                    }
                    try
                    {
                        if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                        {
                            oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                        }

                        //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, false, oDTransDetails);
                    }
                    catch (Exception ex)
                    {
                    }

                    oValue = GetPayPalReceipt(oDPayment);

                    if (oValue.ResponseCode == 0 | oValue.ResponseCode == RETURNCODE.RET_CODE_SUCCESS)
                    {
                        oValue.ResponseCode = RETURNCODE.RET_CODE_SUCCESS;
                    }
                    else
                    {
                        if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString().Replace(",", "."), ".", oOrder.CreditCard.NameOnCard, oVerificationPayPal.Address1, oVerificationPayPal.Address2, oVerificationPayPal.City, oVerificationPayPal.Prov, oVerificationPayPal.POCode, oVerificationPayPal.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                        else
                        {
                            oDPayment = oPayPalAPI.DoDirectPayment(Math.Round(((decimal)oOrder.Subtotal + oOrder.GST.Amount + oOrder.PST.Amount + (decimal)oOrder.ShippingCost), 2).ToString(), ".", oOrder.CreditCard.NameOnCard, oVerificationPayPal.Address1, oVerificationPayPal.Address2, oVerificationPayPal.City, oVerificationPayPal.Prov, oVerificationPayPal.POCode, oVerificationPayPal.Country, oOrder.CreditCard.CardType.ToString(),
                                                                   cardNumber, oOrder.CreditCard.CVV, Int32.Parse(oOrder.CreditCard.ExpiryMonth), year, com.paypal.soap.api.PaymentActionCodeType.Authorization, oVerificationPayPal.Currency);
                        }
                        try
                        {
                            if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                            {
                                oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                            }

                            //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, true, oDTransDetails);
                        }
                        catch (Exception ex)
                        {
                        }


                        oValue = GetPayPalReceipt(oDPayment);

                        if (oValue.ResponseCode == 0 | oValue.ResponseCode == RETURNCODE.RET_CODE_SUCCESS)
                        {
                            oValue.ResponseCode = RETURNCODE.RET_CODE_SUCCESS;
                        }
                        else
                        {
                            oValue.ResponseCode = RETURNCODE.RET_CODE_UNKNOWN_ERROR;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if ((oDPayment.TransactionID != null) && !string.IsNullOrEmpty(oDPayment.TransactionID))
                    {
                        oDTransDetails = oPayPalAPI.GetTransactionDetails(oDPayment.TransactionID);
                    }

                    //AddPayPalTransaction(oOrder, oDPayment, com.paypal.soap.api.PaymentActionCodeType.Sale, oVerificationPayPal, false, oDTransDetails);

                    oValue.ResponseCode = RETURNCODE.RET_CODE_UNKNOWN_ERROR;
                    oValue.Message      = "Unknown Verisign Error";
                }
            }
            catch (Exception ex)
            {
                oValue.ResponseCode = RETURNCODE.RET_CODE_DB_UNKNOWN_ERROR;
                oValue.Message      = "Unknown Verisign DB Error";
            }

            if (HttpContext.Current.Session["Language"] != null && HttpContext.Current.Session["Language"].ToString() == "FR")
            {
                if (oValue.Message.ToString() == "This transaction cannot be processed. Please enter a valid credit card number and type.")
                {
                    oValue.Message = "Cette transaction ne peut pas être traitée. Veuillez saisir un numéro et un type de carte de crédit valides.";
                }
            }


            return(oValue);
        }
コード例 #17
0
        public OrderResponse TestConnection(int companyID, string password)
        {
            var newResponse = new OrderResponse();
               newResponse.is_error = false;
               try
               {
                    Company currentCompany = Company.GetCompany(companyID);

                    if (currentCompany == null)
                    {
                         newResponse.is_error = true;
                         newResponse.errorMessage = "NoCompany";
                    }
                    else
                    {
                         if (password != currentCompany.api_key)
                         {
                              newResponse.is_error = true;
                              newResponse.errorMessage = "IncorrectPassword";
                         }
                    }
               }
               catch (Exception ex)
               {
                    newResponse.is_error = true;
                    newResponse.errorMessage = "GenericError";
                    //LogHelper.WriteError(ex.ToString());
               }
               return newResponse;
        }
コード例 #18
0
 private static bool ValiderEcartTemps(OrderResponse ordre)
 {
     return(ordre.Side == OrderSide.Buy && (DateTime.Now.Subtract(ordre.CreatedAt.ToLocalTime()) > TimeSpan.FromHours(tempsAttenteAchat)));
 }
コード例 #19
0
        /// <summary>
        /// Perform preorder checks to ensure we have sufficient capital,
        /// the market is open, and we haven't exceeded maximum realistic orders per day.
        /// </summary>
        /// <returns>OrderResponse. If no error, order request is submitted.</returns>
        private OrderResponse PreOrderChecksImpl(SubmitOrderRequest request)
        {
            //Most order methods use security objects; so this isn't really used.
            // todo: Left here for now but should review
            Security security;

            if (!Securities.TryGetValue(request.Symbol, out security))
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.MissingSecurity, "You haven't requested " + request.Symbol.ToString() + " data. Add this with AddSecurity() in the Initialize() Method."));
            }

            //Ordering 0 is useless.
            if (request.Quantity == 0 || request.Symbol == null || request.Symbol == QuantConnect.Symbol.Empty || Math.Abs(request.Quantity) < security.SymbolProperties.LotSize)
            {
                return(OrderResponse.ZeroQuantity(request));
            }

            if (!security.IsTradable)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.NonTradableSecurity, "The security with symbol '" + request.Symbol.ToString() + "' is marked as non-tradable."));
            }

            var price = security.Price;

            //Check the exchange is open before sending a market on close orders
            if (request.OrderType == OrderType.MarketOnClose && !security.Exchange.ExchangeOpen)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.ExchangeNotOpen, request.OrderType + " order and exchange not open."));
            }

            //Check the exchange is open before sending a exercise orders
            if (request.OrderType == OrderType.OptionExercise && !security.Exchange.ExchangeOpen)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.ExchangeNotOpen, request.OrderType + " order and exchange not open."));
            }

            if (price == 0)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.SecurityPriceZero, request.Symbol.ToString() + ": asset price is $0. If using custom data make sure you've set the 'Value' property."));
            }

            // check quote currency existence/conversion rate on all orders
            Cash quoteCash;
            var  quoteCurrency = security.QuoteCurrency.Symbol;

            if (!Portfolio.CashBook.TryGetValue(quoteCurrency, out quoteCash))
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.QuoteCurrencyRequired, request.Symbol.Value + ": requires " + quoteCurrency + " in the cashbook to trade."));
            }
            if (security.QuoteCurrency.ConversionRate == 0m)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.ConversionRateZero, request.Symbol.Value + ": requires " + quoteCurrency + " to have a non-zero conversion rate. This can be caused by lack of data."));
            }

            // need to also check base currency existence/conversion rate on forex orders
            if (security.Type == SecurityType.Forex)
            {
                Cash baseCash;
                var  baseCurrency = ((Forex)security).BaseCurrencySymbol;
                if (!Portfolio.CashBook.TryGetValue(baseCurrency, out baseCash))
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.ForexBaseAndQuoteCurrenciesRequired, request.Symbol.Value + ": requires " + baseCurrency + " and " + quoteCurrency + " in the cashbook to trade."));
                }
                if (baseCash.ConversionRate == 0m)
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.ForexConversionRateZero, request.Symbol.Value + ": requires " + baseCurrency + " and " + quoteCurrency + " to have non-zero conversion rates. This can be caused by lack of data."));
                }
            }

            //Make sure the security has some data:
            if (!security.HasData)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.SecurityHasNoData, "There is no data for this symbol yet, please check the security.HasData flag to ensure there is at least one data point."));
            }

            //We've already processed too many orders: max 100 per day or the memory usage explodes
            if (Transactions.OrdersCount > _maxOrders)
            {
                Status = AlgorithmStatus.Stopped;
                return(OrderResponse.Error(request, OrderResponseErrorCode.ExceededMaximumOrders, string.Format("You have exceeded maximum number of orders ({0}), for unlimited orders upgrade your account.", _maxOrders)));
            }

            if (request.OrderType == OrderType.OptionExercise)
            {
                if (security.Type != SecurityType.Option)
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.NonExercisableSecurity, "The security with symbol '" + request.Symbol.ToString() + "' is not exercisable."));
                }

                if (security.Holdings.IsShort)
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.UnsupportedRequestType, "The security with symbol '" + request.Symbol.ToString() + "' has a short option position. Only long option positions are exercisable."));
                }

                if (request.Quantity > security.Holdings.Quantity)
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.UnsupportedRequestType, "Cannot exercise more contracts of '" + request.Symbol.ToString() + "' than is currently available in the portfolio. "));
                }

                if (request.Quantity <= 0.0m)
                {
                    OrderResponse.ZeroQuantity(request);
                }
            }

            if (request.OrderType == OrderType.MarketOnClose)
            {
                var nextMarketClose = security.Exchange.Hours.GetNextMarketClose(security.LocalTime, false);
                // must be submitted with at least 10 minutes in trading day, add buffer allow order submission
                var latestSubmissionTime = nextMarketClose.AddMinutes(-15.50);
                if (!security.Exchange.ExchangeOpen || Time > latestSubmissionTime)
                {
                    // tell the user we require a 16 minute buffer, on minute data in live a user will receive the 3:44->3:45 bar at 3:45,
                    // this is already too late to submit one of these orders, so make the user do it at the 3:43->3:44 bar so it's submitted
                    // to the brokerage before 3:45.
                    return(OrderResponse.Error(request, OrderResponseErrorCode.MarketOnCloseOrderTooLate, "MarketOnClose orders must be placed with at least a 16 minute buffer before market close."));
                }
            }

            // passes all initial order checks
            return(OrderResponse.Success(request));
        }
コード例 #20
0
        public OrderResponse DownloadInvoices(int companyID, string password)
        {
            var newResponse = new OrderResponse();
               newResponse.is_error = false;
               try
               {
                    Company currentCompany = Company.GetCompany(companyID);

                    if (currentCompany == null)
                    {
                         newResponse.is_error = true;
                         newResponse.errorMessage = "NoCompany";
                    }
                    else
                    {
                         if (password != currentCompany.api_key)
                         {
                              newResponse.is_error = true;
                              newResponse.errorMessage = "IncorrectPassword";
                         }
                         else
                         {
                              var invoices = Invoice.GetInvoicesForDownloadByCustomer(currentCompany.company_id);

                              if (invoices.Count == 0)
                              {
                                   newResponse.statusMessage = "No invoices to download";
                              }

                              else
                              {
                                   newResponse.localInvoices = new List<LocalInvoice>();
                                   foreach (var invoice in invoices)
                                   {
                                        var newInvoice = new LocalInvoice();
                                        newInvoice.invoice_id = invoice.invoice_id;
                                        newInvoice.supplierID = invoice.supplier_id;
                                        newInvoice.supplierName = invoice.supplierName;
                                        if (String.IsNullOrEmpty(invoice.local_code))
                                        {
                                             newInvoice.supplier_code = invoice.invoice_id.ToString();
                                        }
                                        else
                                        {
                                             newInvoice.supplier_code = invoice.local_code;
                                        }

                                        if (invoice.purchaseorder_ != null)
                                        {
                                             newInvoice.purchaseorder_code = invoice.purchaseorder_.local_code;
                                        }

                                        newInvoice.freight_inc = invoice.freight;
                                        newInvoice.tax = invoice.tax;
                                        newInvoice.total_inc = invoice.total;
                                        newInvoice.creation_datetime = invoice.creation_datetime;

                                        var newItemList = new List<LocalInvoiceItem>();

                                        foreach (var item in invoice.InvoiceItemsByinvoice_)
                                        {
                                             var newItem = new LocalInvoiceItem();

                                             newItem.barcode = item.barcode;
                                             newItem.quantity = item.quantity;
                                             newItem.cost_ex = item.cost_price;
                                             newItem.RRP = item.RRP;
                                             newItem.isGST = item.is_GST;
                                             newItem.description = item.description;

                                             newItemList.Add(newItem);
                                        }

                                        newInvoice.itemList = newItemList;

                                        newResponse.localInvoices.Add(newInvoice);
                                   }
                                   newResponse.statusMessage = newResponse.localInvoices.Count + " Invoices available";
                              }
                         }
                    }
               }
               catch (Exception ex)
               {
                    newResponse.is_error = true;
                    newResponse.errorMessage = "GenericError";
                    LogHelper.WriteError(ex.ToString());
               }
               return newResponse;
        }
コード例 #21
0
        /// <summary>
        /// Handles a request to update order properties
        /// </summary>
        private OrderResponse HandleUpdateOrderRequest(UpdateOrderRequest request)
        {
            Order       order;
            OrderTicket ticket;

            if (!_orders.TryGetValue(request.OrderId, out order) || !_orderTickets.TryGetValue(request.OrderId, out ticket))
            {
                Log.Error("BrokerageTransactionHandler.HandleUpdateOrderRequest(): Unable to update order with ID " + request.OrderId);
                return(OrderResponse.UnableToFindOrder(request));
            }

            if (!CanUpdateOrder(order))
            {
                return(OrderResponse.InvalidStatus(request, order));
            }

            // rounds off the order towards 0 to the nearest multiple of lot size
            var security = _algorithm.Securities[order.Symbol];

            order.Quantity = RoundOffOrder(order, security);

            // verify that our current brokerage can actually update the order
            BrokerageMessageEvent message;

            if (!_algorithm.LiveMode && !_algorithm.BrokerageModel.CanUpdateOrder(_algorithm.Securities[order.Symbol], order, request, out message))
            {
                // if we couldn't actually process the order, mark it as invalid and bail
                order.Status = OrderStatus.Invalid;
                if (message == null)
                {
                    message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidOrder", "BrokerageModel declared unable to update order: " + order.Id);
                }
                var response = OrderResponse.Error(request, OrderResponseErrorCode.BrokerageModelRefusedToUpdateOrder, "OrderID: " + order.Id + " " + message);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "BrokerageModel declared unable to update order"));
                return(response);
            }

            // modify the values of the order object
            order.ApplyUpdateOrderRequest(request);

            // rounds the order prices
            RoundOrderPrices(order, security);

            ticket.SetOrder(order);

            bool orderUpdated;

            try
            {
                orderUpdated = _brokerage.UpdateOrder(order);
            }
            catch (Exception err)
            {
                Log.Error(err);
                orderUpdated = false;
            }

            if (!orderUpdated)
            {
                // we failed to update the order for some reason
                var errorMessage = "Brokerage failed to update order with id " + request.OrderId;
                _algorithm.Error(errorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Brokerage failed to update order"));
                return(OrderResponse.Error(request, OrderResponseErrorCode.BrokerageFailedToUpdateOrder, errorMessage));
            }

            return(OrderResponse.Success(request));
        }
コード例 #22
0
        public OrderResponse AddOrder(DateTime date)
        {
            OrderResponse response = new OrderResponse();


            if (date < DateTime.Today)
            {
                response.Success = false;
                response.Message = $"{date} is not valid.  Please enter a future date.";
                return(response);
            }

            else
            {
                response.Success = true;
            }
            Order order = new Order();

            order.OrderDate = date;

            order.OrderFileDate = date.ToString("MMddyyyy");

            do
            {
                Console.Write("Enter Customer Name: ");
                order.CustomerName = Console.ReadLine();
            } while (order.CustomerName == "");


            do
            {
                Console.Write("Enter State Abbreviation: ");
                order.State = Console.ReadLine().ToUpper();
            } while (order.State == "" || order.State.Length != 2);

            ReadTaxData readTax = new ReadTaxData();

            //check state.txt
            readTax.InRepo(order.State);
            if (!readTax.InRepo(order.State))
            {
                response.Message = "We do not sell in that state!";
                response.Success = false;
                return(response);
            }

            else
            {
                Tax stateTax = new Tax();
                stateTax      = readTax.StateTax(order.State);
                order.TaxRate = (stateTax.TaxRate / 100);
            }


            Product newProduct = new Product();

            do
            {
                //print list of products with foreach loop
                //DisplayProducts display = new DisplayProducts();
                //display.Show();
                FileProductRepository prodRepo = new FileProductRepository();
                prodRepo.DisplayProducts();
                //Console.Write("Enter a choice from the list above: ");
                //add validation
                newProduct                   = prodRepo.ChooseProduct();
                order.ProductType            = newProduct.ProductType;
                order.CostPerSquareFoot      = newProduct.CostPerSquareFoot;
                order.LaborCostPerSquareFoot = newProduct.LaborCostPerSquareFoot;
            } while (order.ProductType != newProduct.ProductType);


            while (order.Area <= 100)
            {
                decimal orderArea;
                Console.Write("Enter the area of the order in square feet (greater than 100 sqft): ");
                string input = Console.ReadLine();

                if (decimal.TryParse(input, out orderArea))
                {
                    order.Area = orderArea;
                }
            }

            order.LaborCost    = order.LaborCostPerSquareFoot * order.Area;
            order.MaterialCost = order.CostPerSquareFoot * order.Area;
            order.Tax          = (order.LaborCost + order.MaterialCost) * order.TaxRate;
            order.Total        = order.LaborCost + order.MaterialCost + order.Tax;

            response.Success = true;
            response.Order   = order;


            //order = response.Order;
            //IOrder newOrder = OrderRulesFactory.Create(ChangeOrder.Add);

            //    response = newOrder.Update(order, order.OrderDate);


            //if(response.Success)
            //{
            //    _displayOrder.Show(order);


            //    Console.Write("Save this order (Y/N)? ");
            //    string saveOrder = Console.ReadLine().ToUpper();
            //    if (saveOrder == "Y")
            //    {
            //        _orderRepository.SaveOrder(order, order.OrderFileDate);
            //        Console.WriteLine();
            //        Console.WriteLine("Order saved!");
            //        response.Success = true;
            //    }
            //}
            return(response);
        }
コード例 #23
0
        public OrderResponse EditOrder(DateTime date, int orderNumber)
        {
            OrderResponse response = new OrderResponse();
            Order         order    = new Order();

            //if (date > DateTime.Today)
            //{
            //    response.Success = false;
            //    response.Message = $"{date} is not valid.  Please enter a past date.";
            //    return response;
            //}

            if (orderNumber < 1)
            {
                response.Success = false;
                response.Message = "You must enter a valid order number!";
                return(response);
            }

            else
            {
                response.Success = true;
            }


            OrderLookupResponse findOrderResponse = new OrderLookupResponse()
            {
                Order = _orderRepository.LoadOrder(date, orderNumber)
            };

            if (findOrderResponse.Order == null)
            {
                findOrderResponse.Success = false;
                findOrderResponse.Message = $"{orderNumber} is not a valid order number!";
            }
            else
            {
                findOrderResponse.Success = true;
            }

            if (findOrderResponse.Success)
            {
                order = findOrderResponse.Order;

                order.OrderFileDate = order.OrderDate.ToString("MMddyyyy");

                string editField = "To change value, edit here (to keep, press Enter): ";

                Console.WriteLine($"Customer Name: {order.CustomerName}");
                Console.Write(editField);
                string input = Console.ReadLine();
                if (input != "")
                {
                    order.CustomerName = input;
                }

                Console.WriteLine($"State Abbreviation: {order.State}");
                Console.Write(editField);
                input = Console.ReadLine();
                if (input != "")
                {
                    order.State = input.ToUpper();
                }


                ReadTaxData readTax = new ReadTaxData();
                //check state.txt
                readTax.InRepo(order.State);
                if (!readTax.InRepo(order.State))
                {
                    response.Message = "We do not sell in that state!";
                    return(response);
                }

                else
                {
                    Tax stateTax = new Tax();
                    stateTax      = readTax.StateTax(order.State);
                    order.TaxRate = (stateTax.TaxRate / 100);
                }

                Console.WriteLine($"Product: {order.ProductType}");
                Console.Write("Would you like to change your product? (Y/N): ");

                input = Console.ReadLine();
                if (input == "Y")
                {
                    Product newProduct = new Product();
                    //print list of products with foreach loop
                    FileProductRepository prodRepo = new FileProductRepository();
                    prodRepo.DisplayProducts();

                    //Console.Write("Enter a choice from the list above: ");
                    newProduct                   = prodRepo.ChooseProduct();
                    order.ProductType            = newProduct.ProductType;
                    order.CostPerSquareFoot      = newProduct.CostPerSquareFoot;
                    order.LaborCostPerSquareFoot = newProduct.LaborCostPerSquareFoot;
                }

                Console.WriteLine($"Order Area: {order.Area}");
                Console.Write(editField);
                input = Console.ReadLine();

                if (input != "")
                {
                    order.Area = -1;

                    while (order.Area < 100)
                    {
                        decimal orderArea;
                        if (decimal.TryParse(input, out orderArea))
                        {
                            order.Area = orderArea;
                        }


                        if (order.Area < 100)
                        {
                            Console.WriteLine($"Order Area: {order.Area}");
                            Console.Write(editField);
                            input = Console.ReadLine();
                        }
                    }
                }

                order.LaborCost    = order.LaborCostPerSquareFoot * order.Area;
                order.MaterialCost = order.CostPerSquareFoot * order.Area;
                order.Tax          = (order.LaborCost + order.MaterialCost) * order.TaxRate;
                order.Total        = order.LaborCost + order.MaterialCost + order.Tax;

                response.Success = true;
                response.Order   = order;

                //IOrder editOrder = OrderRulesFactory.Create(ChangeOrder.Edit);
                //Order foundOrder = new Order();
                //foundOrder = findOrderResponse.Order;


                //response = editOrder.Update(foundOrder, date);


                //if (response.Success)
                //{
                //    _displayOrder.Show(order);

                //    Console.Write("Save this order (Y/N)? ");
                //    string saveOrder = Console.ReadLine().ToUpper();
                //    if (saveOrder == "Y")
                //    {
                //        _orderRepository.SaveOrder(order, order.OrderFileDate);
                //        Console.WriteLine();
                //        Console.WriteLine("Order saved!");
                //        response.Success = true;
                //    }
                //}
            }
            return(response);
        }
コード例 #24
0
        public OrderResponse RemoveOrder(DateTime date, int orderNumber)
        {
            Order         order    = new Order();
            OrderResponse response = new OrderResponse();

            //if (date > DateTime.Today)
            //{
            //    response.Success = false;
            //    response.Message = $"{date} is not valid.  Please enter a past date.";
            //    return response;
            //}

            if (orderNumber < 1)
            {
                response.Success = false;
                response.Message = "You must enter a valid order number!";
                return(response);
            }

            else
            {
                response.Success = true;
            }


            OrderLookupResponse findOrderResponse = new OrderLookupResponse();

            findOrderResponse.Order = _orderRepository.LoadOrder(date, orderNumber);

            if (findOrderResponse.Order == null)
            {
                findOrderResponse.Success = false;
                findOrderResponse.Message = $"{orderNumber} is not a valid order number!";
            }
            else
            {
                findOrderResponse.Success = true;
            }

            if (findOrderResponse.Success)
            {
                response.Order = findOrderResponse.Order;

                //IOrder removeOrder = OrderRulesFactory.Create(ChangeOrder.Remove);
                //Order foundOrder = new Order();
                //foundOrder = findOrderResponse.Order;

                //response = removeOrder.Update(foundOrder, date);


                //if (response.Success)
                //{
                //    _displayOrder.Show(order);


                //    Console.Write("Are you sure you want to cancel this order (Y/N)? ");
                //    string deleteOrder = Console.ReadLine().ToUpper();
                //    if (deleteOrder == "Y")
                //    {
                //        _orderRepository.DeleteOrder(order, order.OrderFileDate);
                //        Console.WriteLine();
                //        Console.WriteLine("Order cancelled!");
                //        response.Success = true;
                //    }
                //}
            }
            return(response);
        }
コード例 #25
0
        private void ExecuteSimulationGrpc()
        {
            List <String> tickers = new List <String> {
                "ERX", "SPY", "DIA", "QQQ", "UPRO", "SPXU", "OILU", "OILD"
            };

            String msg = "";
            // int minOrders = 1000;
            int  numTrades   = 1000;
            bool limitOrders = true;
            int  numThreads  = 10;

            msg = "\n\n********** BEGIN TRADING **********\n";
            Console.WriteLine(msg);
            logger.Information(msg);
            long            tradeStart = Now;
            ParallelOptions opt        = new ParallelOptions()
            {
                MaxDegreeOfParallelism = numThreads
            };

            Parallel.For(0, numTrades, opt, i => {
                int orderType          = (rnd.Next(1, limitOrders ? 5 : 3));
                String ticker          = tickers[rnd.Next(1, tickers.Count + 1) - 1];
                ticker                 = "ERX";
                Task <Quote> quoteResp = apiClient.GetQuoteAsync(new StringMessage {
                    Value = ticker
                }).ResponseAsync;
                Quote quote      = quoteResp.Result;
                int sign         = rnd.Next(1, 3) == 1 ? 1 : -1;
                long orderStart  = Now;
                OrderRequest req = null;
                if (orderType == 1)
                {
                    req = new OrderRequest {
                        AccountId   = GetAccountId(),
                        Action      = OrderAction.OrderBuy,
                        Ticker      = ticker,
                        Type        = OrderType.OrderMarket,
                        Quantity    = RandomQuantity,
                        OrderPrice  = 0,
                        TimeInForce = OrderTimeInForce.OrderDay
                    };
                }
                else if (orderType == 2)
                {
                    req = new OrderRequest {
                        AccountId   = GetAccountId(),
                        Action      = OrderAction.OrderSell,
                        Ticker      = ticker,
                        Type        = OrderType.OrderMarket,
                        Quantity    = RandomQuantity,
                        OrderPrice  = 0,
                        TimeInForce = OrderTimeInForce.OrderDay
                    };
                }
                else if (orderType == 3)
                {
                    decimal price = Convert.ToDecimal(quote.Ask) + (sign * (rnd.Next(1, 10000) / 10000000M));
                    req           = new OrderRequest {
                        AccountId   = GetAccountId(),
                        Action      = OrderAction.OrderBuy,
                        Ticker      = ticker,
                        Type        = OrderType.OrderLimit,
                        Quantity    = RandomQuantity,
                        OrderPrice  = Convert.ToDouble(price),
                        TimeInForce = OrderTimeInForce.OrderDay
                    };
                }
                else
                {
                    decimal price = Convert.ToDecimal(quote.Bid) + (sign * (rnd.Next(1, 10000) / 10000000M));
                    req           = new OrderRequest {
                        AccountId   = GetAccountId(),
                        Action      = OrderAction.OrderSell,
                        Ticker      = ticker,
                        Type        = OrderType.OrderLimit,
                        Quantity    = RandomQuantity,
                        OrderPrice  = Convert.ToDouble(price),
                        TimeInForce = OrderTimeInForce.OrderDay
                    };
                }

                // Task<OrderResponse> resp = orderClient.SubmitOrderAsync(req).ResponseAsync;
                Task <OrderResponse> resp = apiClient.SubmitOrderAsync(req).ResponseAsync;
                resp.Wait();
                OrderResponse response = resp.Result;
                if (response.Errors.Count > 0)
                {
                    throw new Exception(response.Errors[0].Description);
                }
                msg = String.Format("Executed order in {0} milliseconds\n", Stop(orderStart));
                Console.WriteLine(msg);
                logger.Information(msg);
                Thread.Sleep(rnd.Next(1, 5) * 1000);
            });
            msg = String.Format("Executed {1} trades with {2} threads in {0} milliseconds",
                                Stop(tradeStart), numTrades, numThreads);
            Console.WriteLine(msg);
            logger.Information(msg);
            msg = "\n\n********** END TRADING **********\n";
            Console.WriteLine(msg);
            logger.Information(msg);
        }
コード例 #26
0
        /// <summary>
        /// Remove this order from outstanding queue: user is requesting a cancel.
        /// </summary>
        /// <param name="request">Request containing the specific order id to remove</param>
        public OrderTicket CancelOrder(CancelOrderRequest request)
        {
            OrderTicket ticket;

            if (!_orderTickets.TryGetValue(request.OrderId, out ticket))
            {
                Log.Error("BrokerageTransactionHandler.CancelOrder(): Unable to locate ticket for order.");
                return(OrderTicket.InvalidCancelOrderId(_algorithm.Transactions, request));
            }

            try
            {
                // if we couldn't set this request as the cancellation then another thread/someone
                // else is already doing it or it in fact has already been cancelled
                if (!ticket.TrySetCancelRequest(request))
                {
                    // the ticket has already been cancelled
                    request.SetResponse(OrderResponse.Error(request, OrderResponseErrorCode.InvalidRequest, "Cancellation is already in progress."));
                    return(ticket);
                }

                //Error check
                var order = GetOrderByIdInternal(request.OrderId);
                if (order != null && request.Tag != null)
                {
                    order.Tag = request.Tag;
                }
                if (order == null)
                {
                    Log.Error("BrokerageTransactionHandler.CancelOrder(): Cannot find this id.");
                    request.SetResponse(OrderResponse.UnableToFindOrder(request));
                }
                else if (order.Status.IsClosed())
                {
                    Log.Error("BrokerageTransactionHandler.CancelOrder(): Order already " + order.Status);
                    request.SetResponse(OrderResponse.InvalidStatus(request, order));
                }
                else if (_algorithm.IsWarmingUp)
                {
                    request.SetResponse(OrderResponse.WarmingUp(request));
                }
                else
                {
                    // update the order status
                    order.Status = OrderStatus.CancelPending;

                    // notify the algorithm with an order event
                    HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m));

                    // send the request to be processed
                    request.SetResponse(OrderResponse.Success(request), OrderRequestStatus.Processing);
                    _orderRequestQueue.Add(request);
                }
            }
            catch (Exception err)
            {
                Log.Error(err);
                request.SetResponse(OrderResponse.Error(request, OrderResponseErrorCode.ProcessingError, err.Message));
            }

            return(ticket);
        }
コード例 #27
0
        /// <summary>
        /// Perform preorder checks to ensure we have sufficient capital,
        /// the market is open, and we haven't exceeded maximum realistic orders per day.
        /// </summary>
        /// <returns>OrderResponse. If no error, order request is submitted.</returns>
        private OrderResponse PreOrderChecksImpl(SubmitOrderRequest request)
        {
            //Ordering 0 is useless.
            if (request.Quantity == 0 || request.Symbol == null || request.Symbol == Symbol.Empty)
            {
                return(OrderResponse.ZeroQuantity(request));
            }

            //If we're not tracking this symbol: throw error:
            if (!Securities.ContainsKey(request.Symbol) && !_sentNoDataError)
            {
                _sentNoDataError = true;
                return(OrderResponse.Error(request, OrderResponseErrorCode.MissingSecurity, "You haven't requested " + request.Symbol.SID + " data. Add this with AddSecurity() in the Initialize() Method."));
            }

            //Set a temporary price for validating order for market orders:
            var security = Securities[request.Symbol];
            var price    = security.Price;

            //Check the exchange is open before sending a market on close orders
            //Allow market orders, they'll just execute when the exchange reopens
            if (request.OrderType == OrderType.MarketOnClose && !security.Exchange.ExchangeOpen)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.ExchangeNotOpen, request.OrderType + " order and exchange not open."));
            }

            if (price == 0)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.SecurityPriceZero, request.Symbol.SID + ": asset price is $0. If using custom data make sure you've set the 'Value' property."));
            }

            if (security.Type == SecurityType.Forex)
            {
                // for forex pairs we need to verify that the conversions to USD have values as well
                string baseCurrency, quoteCurrency;
                Forex.DecomposeCurrencyPair(security.Symbol.Value, out baseCurrency, out quoteCurrency);

                // verify they're in the portfolio
                Cash baseCash, quoteCash;
                if (!Portfolio.CashBook.TryGetValue(baseCurrency, out baseCash) || !Portfolio.CashBook.TryGetValue(quoteCurrency, out quoteCash))
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.ForexBaseAndQuoteCurrenciesRequired, request.Symbol.Value + ": requires " + baseCurrency + " and " + quoteCurrency + " in the cashbook to trade."));
                }
                // verify we have conversion rates for each leg of the pair back into the account currency
                if (baseCash.ConversionRate == 0m || quoteCash.ConversionRate == 0m)
                {
                    return(OrderResponse.Error(request, OrderResponseErrorCode.ForexConversionRateZero, request.Symbol.Value + ": requires " + baseCurrency + " and " + quoteCurrency + " to have non-zero conversion rates. This can be caused by lack of data."));
                }
            }

            //Make sure the security has some data:
            if (!security.HasData)
            {
                return(OrderResponse.Error(request, OrderResponseErrorCode.SecurityHasNoData, "There is no data for this symbol yet, please check the security.HasData flag to ensure there is at least one data point."));
            }

            //We've already processed too many orders: max 100 per day or the memory usage explodes
            if (Transactions.OrdersCount > _maxOrders)
            {
                _quit = true;
                return(OrderResponse.Error(request, OrderResponseErrorCode.ExceededMaximumOrders, string.Format("You have exceeded maximum number of orders ({0}), for unlimited orders upgrade your account.", _maxOrders)));
            }

            if (request.OrderType == OrderType.MarketOnClose)
            {
                // must be submitted with at least 10 minutes in trading day, add buffer allow order submission
                var latestSubmissionTime = (Time.Date + security.Exchange.MarketClose).AddMinutes(-10.75);
                if (Time > latestSubmissionTime)
                {
                    // tell the user we require an 11 minute buffer, on minute data in live a user will receive the 3:49->3:50 bar at 3:50,
                    // this is already too late to submit one of these orders, so make the user do it at the 3:48->3:49 bar so it's submitted
                    // to the brokerage before 3:50.
                    return(OrderResponse.Error(request, OrderResponseErrorCode.MarketOnCloseOrderTooLate, "MarketOnClose orders must be placed with at least a 11 minute buffer before market close."));
                }
            }

            // passes all initial order checks
            return(OrderResponse.Success(request));
        }
コード例 #28
0
        private void ProcessNotifications(FtpManager manager, OrderResponseTypes responseType, IAuditLogAdapter log, Vendor vendor, string logPath, IUnitOfWork unit)
        {
            foreach (var file in manager)
            {
                try
                {
                    using (MemoryStream fileStream = new MemoryStream(ReadFully(file.Data)))
                    {
                        string fileName = "VSN_" + responseType.ToString() + "_" + Guid.NewGuid() + ".csv";
                        using (FileStream s = File.Create(Path.Combine(logPath, fileName)))
                        {
                            s.Write(fileStream.ToArray(), 0, (int)fileStream.Length);
                        }

                        int orderID = 0;
                        var parser  = GetCSVFile(fileStream, responseType);

                        var groupedOrders = (from p in parser
                                             group p by p["CustomerReference"] into od
                                             select new
                        {
                            OrderID = od.Key,
                            OrderInf = od.ToList()
                        }).ToDictionary(x => x.OrderID, x => x.OrderInf);

                        string vsnResponseType = responseType.ToString();
                        foreach (var orderResp in groupedOrders)
                        {
                            int.TryParse(orderResp.Key, out orderID);

                            var order = unit.Scope.Repository <Concentrator.Objects.Models.Orders.Order>().GetSingle(o => o.OrderID == orderID);

                            OrderResponse response = null;

                            if (order != null)
                            {
                                var responseHeader   = orderResp.Value.FirstOrDefault();
                                int orderLineCounter = 0;

                                switch (responseType)
                                {
                                case OrderResponseTypes.Acknowledgement:
                                    #region Acknowledgement
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNAcknowledgement.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNAcknowledgement.SalesOrderID.ToString()]
                                    };

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNAcknowledgement.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        //int.TryParse(line[VSNAcknowledgement.CustomerLineReference.ToString()], out lineReference);

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse    = response,
                                                Backordered      = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Backorder ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                Cancelled        = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Canceled ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                Ordered          = oLine.GetDispatchQuantity(),
                                                Description      = line[VSNAcknowledgement.ProductName.ToString()],
                                                Invoiced         = 0,
                                                Barcode          = line[VSNAcknowledgement.EANNumber.ToString()],
                                                OrderLine        = oLine,
                                                Price            = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed        = false,
                                                Shipped          = StatusCodes(line[VSNAcknowledgement.StatusCode.ToString()]) == VSNStatusCode.Picklist ? int.Parse(line[VSNAcknowledgement.Quantity.ToString()]) : 0,
                                                VendorItemNumber = line[VSNAcknowledgement.ProductCode.ToString()],
                                                Remark           = string.Format("ReleaseDate {0}", line[VSNAcknowledgement.ReleaseDate.ToString()])
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;

                                case OrderResponseTypes.CancelNotification:
                                    #region CancelNotification
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNCancel.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNCancel.SalesOrderID.ToString()],
                                        VendorDocumentDate   = DateTime.ParseExact(responseHeader[VSNCancel.Timestamp.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                                    };

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNCancel.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse    = response,
                                                Backordered      = 0,
                                                Cancelled        = int.Parse(line[VSNCancel.Quantity.ToString()]),
                                                Ordered          = oLine.GetDispatchQuantity(),
                                                Description      = line[VSNCancel.ProductName.ToString()],
                                                Invoiced         = 0,
                                                Barcode          = line[VSNCancel.EANNumber.ToString()],
                                                OrderLine        = oLine,
                                                Price            = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed        = false,
                                                Shipped          = 0,
                                                VendorItemNumber = line[VSNCancel.ProductCode.ToString()],
                                                Remark           = line[VSNCancel.SalesOrderLineCancelReason.ToString()]
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;

                                case OrderResponseTypes.ShipmentNotification:
                                    #region ShipmentNotification
                                    response = new OrderResponse()
                                    {
                                        Currency             = "EUR",
                                        ResponseType         = responseType.ToString(),
                                        OrderID              = orderID,
                                        OrderDate            = DateTime.ParseExact(responseHeader[VSNShipment.OrderDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                        VendorDocumentNumber = responseHeader[VSNShipment.SalesOrderID.ToString()],
                                        ShippingNumber       = responseHeader[VSNShipment.PackListID.ToString()],
                                        ReqDeliveryDate      = DateTime.ParseExact(responseHeader[VSNShipment.PacklistDate.ToString()], "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                                    };

                                    Customer cus = order.ShippedToCustomer;

                                    if (cus.CustomerName != responseHeader[VSNShipment.AddressName.ToString()] ||
                                        cus.CustomerAddressLine1 != responseHeader[VSNShipment.Street.ToString()] ||
                                        cus.HouseNumber != responseHeader[VSNShipment.HouseNumber.ToString()] ||
                                        cus.PostCode.Replace(" ", "").ToUpper() != responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper() ||
                                        cus.City.ToUpper() != responseHeader[VSNShipment.City.ToString()] ||
                                        (!string.IsNullOrEmpty(responseHeader[VSNShipment.CountryName.ToString()]) && cus.Country != responseHeader[VSNShipment.CountryName.ToString()]))
                                    {
                                        cus = new Customer()
                                        {
                                            CustomerName         = responseHeader[VSNShipment.AddressName.ToString()],
                                            CustomerAddressLine1 = responseHeader[VSNShipment.Street.ToString()],
                                            HouseNumber          = responseHeader[VSNShipment.HouseNumber.ToString()],
                                            PostCode             = responseHeader[VSNShipment.ZipCode.ToString()],
                                            Country = responseHeader[VSNShipment.CountryName.ToString()],
                                            City    = responseHeader[VSNShipment.City.ToString()]
                                        }
                                    }
                                    ;

                                    response.ShippedToCustomer = cus;

                                    foreach (var line in orderResp.Value)
                                    {
                                        int    lineReference  = 0;
                                        string referenceField = line[VSNShipment.CustomerLineReference.ToString()];
                                        if (referenceField.Contains('/'))
                                        {
                                            int.TryParse(referenceField.Split('/')[0], out lineReference);
                                        }
                                        else
                                        {
                                            int.TryParse(referenceField, out lineReference);
                                        }

                                        OrderLine oLine = order.OrderLines.Where(x => x.OrderLineID == lineReference).FirstOrDefault();

                                        if (oLine == null)
                                        {
                                            string vendorItemNumber = line[VSNAcknowledgement.EANNumber.ToString()];
                                            oLine = order.OrderLines.Where(x => x.Product != null && x.Product.VendorItemNumber == vendorItemNumber).FirstOrDefault();
                                        }

                                        if (oLine != null && (!oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == vsnResponseType) ||
                                                              (!string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) && !oLine.OrderResponseLines.Any(x => x.OrderResponse.ResponseType == responseType.ToString() && !string.IsNullOrEmpty(x.TrackAndTrace)))))
                                        {
                                            OrderResponseLine rLine = new OrderResponseLine()
                                            {
                                                OrderResponse     = response,
                                                Backordered       = 0,
                                                Cancelled         = 0,
                                                Ordered           = oLine.GetDispatchQuantity(),
                                                Description       = line[VSNShipment.ProductName.ToString()],
                                                Invoiced          = 0,
                                                Barcode           = line[VSNShipment.EANNumber.ToString()],
                                                OrderLine         = oLine,
                                                Price             = ((decimal)(oLine.Price.HasValue ? oLine.Price.Value : 0)),
                                                Processed         = false,
                                                Shipped           = int.Parse(line[VSNShipment.Quantity.ToString()]),
                                                VendorItemNumber  = line[VSNShipment.ProductCode.ToString()],
                                                NumberOfUnits     = line[VSNShipment.PackageType.ToString()] == "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0,
                                                NumberOfPallets   = line[VSNShipment.PackageType.ToString()] != "Doos" ? int.Parse(line[VSNShipment.PackageCount.ToString()]) : 0,
                                                Unit              = line[VSNShipment.PackageType.ToString()],
                                                Remark            = string.Format("ReleaseDate {0}", line[VSNShipment.ReleaseDate.ToString()]),
                                                TrackAndTrace     = line[VSNShipment.LabelReference.ToString()],
                                                TrackAndTraceLink = string.IsNullOrEmpty(line[VSNShipment.LabelReference.ToString()]) ? string.Empty : BuildTrackAndTraceNumber(line[VSNShipment.LabelReference.ToString()], responseHeader[VSNShipment.ZipCode.ToString()].Replace(" ", "").ToUpper())
                                            };

                                            unit.Scope.Repository <OrderResponseLine>().Add(rLine);
                                            orderLineCounter++;
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                    #endregion
                                    break;
                                }

                                if (orderLineCounter > 0)
                                {
                                    response.VendorID       = vendor.VendorID;
                                    response.ReceiveDate    = DateTime.Now;
                                    response.VendorDocument = parser.Document;
                                    response.DocumentName   = fileName;
                                    if (!response.VendorDocumentDate.HasValue)
                                    {
                                        response.VendorDocumentDate = DateTime.Now;
                                    }

                                    response.ReceiveDate = DateTime.Now;

                                    unit.Scope.Repository <OrderResponse>().Add(response);
                                }
                            }
                        }


                        unit.Save();
                        manager.Delete(file.FileName);
                    }
                }
                catch (Exception ex)
                {
                    log.AuditError("Error reading file", ex);
                }
            }
        }
コード例 #29
0
        public OrderResponse UploadPurchaseOrders(int companyID, string password, List<LocalPurchaseOrder> orders)
        {
            var newResponse = new OrderResponse();
               newResponse.is_error = false;
               newResponse.errorMessage = "";
               newResponse.statusMessage = "";
               try
               {
                    Company currentCompany = Company.GetCompany(companyID);

                    if (currentCompany == null)
                    {
                         newResponse.is_error = true;
                         newResponse.errorMessage = "NoCompany";
                    }
                    else
                    {
                         if (password != currentCompany.api_key)
                         {
                              newResponse.is_error = true;
                              newResponse.errorMessage = "IncorrectPassword";
                         }
                         else
                         {
                              foreach (var order in orders)
                              {
                                   //Check for duplicate barcodes.
                                   List<string> duplicateBarcodes = order.itemList.GroupBy(i => i.barcode)
                                                                                              .Where(g => g.Count() > 1)
                                                                                              .Select(g => g.Key)
                                                                                              .ToList();
                                   if (duplicateBarcodes.Count > 0)
                                   {
                                        string barcodes = String.Join("\r\n", duplicateBarcodes.ToArray());
                                        newResponse.is_error = true;
                                        newResponse.errorMessage += "Error with Purchase Order: " + order.local_code + ". Duplicate barcodes: \r\n " + barcodes;
                                   }
                                   else
                                   {
                                        var supplier = Company.GetCompany(order.supplier_id);
                                        if (supplier == null)
                                        {
                                             newResponse.is_error = true;
                                             newResponse.errorMessage += "Error with Purchase Order: " + order.local_code + ". Supplier not found\r\n";
                                        }
                                        else
                                        {
                                             var permission = AllowedStore.GetAllowedStoreByCustomerSupplier(currentCompany.company_id, supplier.company_id);
                                             if (permission == null)
                                             {
                                                  newResponse.is_error = true;
                                                  newResponse.errorMessage += "Error with Purchase Order: " + order.local_code + ". You don't have an account with this supplier.\r\n";
                                             }
                                             else
                                             {
                                                  if (PurchaseOrder.GetPurchaseOrdersByCustomerLocalCode(companyID, order.local_code).Count > 0)
                                                  {
                                                       newResponse.is_error = true;
                                                       newResponse.errorMessage += "Purchase order: " + order.local_code + " to " + supplier.name + " already submitted.\r\n";
                                                  }
                                                  else
                                                  {

                                                       PurchaseOrder newOrder = PurchaseOrder.CreatePurchaseOrder();
                                                       newOrder.local_code = order.local_code;
                                                       newOrder.customer_id = currentCompany.company_id;
                                                       newOrder.supplier_id = supplier.company_id;
                                                       newOrder.person = "HealthStop POS Client";
                                                       newOrder.creation_datetime = order.order_datetime;

                                                       newOrder.Save();
                                                       newOrder.Refresh();

                                                       foreach (var item in order.itemList)
                                                       {
                                                            var foundSupplierProduct = SupplierProduct.findProductByBarcode(supplier.company_id, item.barcode);

                                                            if (foundSupplierProduct == null)
                                                            {
                                                                 newResponse.is_error = true;
                                                                 newResponse.errorMessage += "Error with Purchase Order: " + order.local_code + "\r\nProduct not found in supplier list : " + item.barcode + "\r\nOrder submitted without this product." + "\r\n";
                                                            }
                                                            else
                                                            {
                                                                 var newItem = PurchaseOrderItem.CreatePurchaseOrderItem();
                                                                 newItem.purchaseorder_id = newOrder.purchaseorder_id;
                                                                 newItem.product_code = foundSupplierProduct.product_code;
                                                                 newItem.barcode = foundSupplierProduct.barcode;
                                                                 newItem.description = foundSupplierProduct.description;
                                                                 newItem.cost_price = foundSupplierProduct.CalculateApplicableCost(item.quantity, permission.is_member);
                                                                 newItem.quantity = item.quantity;

                                                                 newItem.Save();
                                                            }
                                                       }

                                                       newOrder.Refresh();
                                                       if (newOrder.PurchaseOrderItemsBypurchaseorder_.Count == 0)
                                                       {
                                                            newResponse.is_error = true;
                                                            newResponse.errorMessage += "Error with Purchase Order: " + order.local_code + " No items to order" + "\r\n";
                                                            newOrder.Delete();
                                                       }
                                                       else
                                                       {
                                                            EmailHelper.SendXMLOrder("HealthStop Auto", currentCompany, supplier, newOrder.createEDI());
                                                            newOrder.submitted_datetime = DateTime.UtcNow;
                                                            newOrder.is_submitted = true;
                                                            newOrder.Save();

                                                            newResponse.statusMessage += "Purchase Order: " + order.local_code + ". sent successfully to " + supplier.name + "\r\n";
                                                       }
                                                  }
                                             }
                                        }
                                   }
                              }
                         }
                    }
               }
               catch (Exception ex)
               {
                    newResponse.is_error = true;
                    newResponse.errorMessage = "GenericError";
                    LogHelper.WriteError(ex.ToString());
               }
               return newResponse;
        }
コード例 #30
0
        private void btnFinalizeOrder_Click(object sender, EventArgs e)
        {
            try
            {
                Customer customer = new Customer();
                if (rdoCreateCustomer.Checked)
                {
                    customer.CustomerId = -1;
                }
                else
                {
                    customer.CustomerId = Convert.ToInt32(lblCustomerId.Text);
                }

                customer.FirstName    = txtFirstName.Text;
                customer.LastName     = txtLastName.Text;
                customer.PhoneNumber1 = txtPhoneNumber.Text;
                customer.Email        = string.Empty;


                if (rdoCreateAddress.Checked)
                {
                    customer.AddressDetails.AddressId = -1;
                }
                else
                {
                    customer.AddressDetails.AddressId = Convert.ToInt32(lblAddressId.Text);
                }

                customer.AddressDetails.AddressLine1 = txtAddressLine1.Text;
                customer.AddressDetails.AddressLine2 = txtAddressLine2.Text;
                customer.AddressDetails.City         = txtCity.Text;
                customer.AddressDetails.PinCode      = txtPinCode.Text;

                Order order = new Order
                {
                    OrderId         = Convert.ToInt32(lblOrderId.Text),
                    Discount        = Convert.ToDecimal(txtDiscount.Text == string.Empty ? "0" : txtDiscount.Text),
                    TotalWithoutTax = Convert.ToDecimal(lblTotalPrice.Text),
                    Tax             = 0.0M
                };
                order.Total  = order.TotalWithoutTax + order.Tax;
                order.Status = Enums.OrderStatus.Pending;

                foreach (DataGridViewRow row in dgMenuView.Rows)
                {
                    if (row.Cells["dcItemQuantity"].Value != null &&
                        !string.IsNullOrEmpty(row.Cells["dcItemQuantity"].Value.ToString()) &&
                        Convert.ToInt32(row.Cells["dcItemQuantity"].Value) > 0)
                    {
                        var orderItem = new OrderItem
                        {
                            OrderId      = -1,
                            ItemId       = Convert.ToInt32(row.Cells["dcItemId"].Value),
                            Quantity     = Convert.ToInt32(row.Cells["dcItemQuantity"].Value),
                            PricePerItem = Convert.ToDecimal(row.Cells["dcItemPrice"].Value),
                            TotalPrice   = Convert.ToDecimal(row.Cells["dcItemTotal"].Value)
                        };
                        order.OrderItems.Add(orderItem);
                    }
                }
                OrderResponse orderResponse = BalObj.SaveOrder(customer, order);

                ViewOrderDetails(orderResponse.OrderId);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #31
0
        public int DispatchOrders(Dictionary <Models.Orders.Order, List <Models.Orders.OrderLine> > orderLines, Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, DataAccess.UnitOfWork.IUnitOfWork uni)
        {
            var Username = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var Secret   = vendor.VendorSettings.GetValueByKey("Secret", string.Empty);

            var _orderResponseRepo        = uni.Scope.Repository <OrderResponse>();
            var _orderResponseLineRepo    = uni.Scope.Repository <OrderResponseLine>();
            var _orderItemFulfillmentRepo = uni.Scope.Repository <OrderItemFullfilmentInformation>();


            RetailServices10SoapClient client = new RetailServices10SoapClient();

            RetailAccount account = new RetailAccount();

            var inputString = Username + Secret;

            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(inputString);
            byte[] byteHash  = MD5.ComputeHash(byteValue);
            MD5.Clear();

            account.Client     = Username;
            account.SecureHash = Convert.ToBase64String(byteHash);

            var response = client.Ping(account);

            if (response != null)
            {
                log.AuditInfo("AtomBlock services are online");

                ShopOrder[] orders = new ShopOrder[orderLines.Count()];

                int orderCount = 0;
                foreach (var order in orderLines.Keys)
                {
                    int       count       = 0;
                    double    totalAmount = 0;
                    ShopOrder shopOrder   = new ShopOrder();
                    shopOrder.Identifier  = order.OrderID.ToString();
                    shopOrder.IsTestOrder = true;
                    shopOrder.Items       = new ShopOrderItemRequest[order.OrderLines.Count()];
                    //shopOrder.PaymentMethod = "????"; //SET PAYMENT

                    foreach (var item in order.OrderLines)
                    {
                        shopOrder.Items[count]                   = new ShopOrderItemRequest();
                        shopOrder.Items[count].Discount          = 0; // ?????
                        shopOrder.Items[count].ItemPrice         = (int)item.Price * 100;
                        shopOrder.Items[count].ProductIdentifier = item.Product.VendorAssortments.FirstOrDefault(x => x.VendorID == vendor.VendorID).CustomItemNumber;
                        shopOrder.Items[count].Quantity          = item.GetDispatchQuantity();
                        count++;
                        totalAmount += item.Price.Value;
                    }

                    shopOrder.TotalAmount          = (int)totalAmount;
                    shopOrder.TotalDiscount        = 0; // ?????
                    shopOrder.TotalTransactionCost = 0; // ?????
                    orders[orderCount]             = shopOrder;
                    orderCount++;
                }

                ShopProfile profile = new ShopProfile();
                //add info?
                // profile.Email =

                var result    = client.AddOrderBatched(account, profile, orders);
                var successes = new List <ShopOrderReceipt>();
                var failures  = new List <ShopOrderReceipt>();

                if (orders.Count() > 0)
                {
                    LogOrder(orders, vendor.VendorID, string.Format("{0}.xml", orders.FirstOrDefault().Identifier), log);
                }

                foreach (var callback in result)
                {
                    switch (callback.CommunicationStatus.Type)
                    {
                    case MessageType.ERROR:
                        failures.Add(callback);
                        break;

                    case MessageType.NO_ACCESS:
                        failures.Add(callback);
                        break;

                    case MessageType.OK:
                        successes.Add(callback);
                        break;

                    case MessageType.WRONG_REQUEST:
                        failures.Add(callback);
                        break;

                    default:
                        failures.Add(callback);
                        break;
                    }
                }
                //all orders correctly processed
                log.AuditInfo("Processing order details");

                foreach (var success in successes)
                {
                    var id    = Int32.Parse(success.Reference);
                    var Order = uni.Scope.Repository <Order>().GetSingle(x => x.OrderID == id);

                    if (Order != null)
                    {
                        var orderResponse = new OrderResponse
                        {
                            Order                = Order,
                            OrderDate            = DateTime.Now,
                            ReceiveDate          = DateTime.Now,
                            Vendor               = vendor,
                            VendorDocument       = "",
                            VendorDocumentNumber = Order.OrderID.ToString()
                        };
                        orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString();
                        _orderResponseRepo.Add(orderResponse);

                        var TotalAmount = 0;

                        foreach (var orderline in success.OrderLines)
                        {
                            var name = orderline.Title;

                            var OrderLine = Order.OrderLines.FirstOrDefault(x => x.Product.ProductDescriptions.FirstOrDefault(p => p.ProductName == name).ProductName == name);

                            if (OrderLine != null)
                            {
                                var orderResponseLine = new OrderResponseLine
                                {
                                    OrderResponse = orderResponse,
                                    OrderLine     = OrderLine,
                                    Ordered       = orderline.Quantity,
                                    Backordered   = orderline.IsPreOrder ? orderline.Quantity : 0,
                                    Cancelled     = 0,
                                    Shipped       = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                    Invoiced      = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                    Price         = orderline.ItemPrice / 100,
                                    Processed     = false,
                                    Delivered     = 0,
                                    ProductName   = name,
                                    Remark        = orderline.IsPreOrder ? string.Format("PreOrder:{0}", orderline.PreOrderReleaseDate.ToString()) : null
                                };

                                _orderResponseLineRepo.Add(orderResponseLine);

                                TotalAmount += orderline.ItemPrice / 100;

                                if (!orderline.IsPreOrder)
                                {
                                    //DownloadFiles
                                    foreach (var file in orderline.DownloadFiles)
                                    {
                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                        {
                                            OrderResponseLine = orderResponseLine
                                        };
                                        orderItemFullfilmentInformation.Type  = "Name";
                                        orderItemFullfilmentInformation.Label = "FileName";
                                        orderItemFullfilmentInformation.Value = file.File;
                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                    }

                                    //Serials
                                    foreach (var serial in orderline.Serials)
                                    {
                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                        {
                                            OrderResponseLine = orderResponseLine
                                        };
                                        orderItemFullfilmentInformation.Type  = "Key";
                                        orderItemFullfilmentInformation.Label = "Serial";
                                        orderItemFullfilmentInformation.Value = serial.Code;
                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                    }

                                    //additional stuff
                                    foreach (var prop in orderline.GetType().GetProperties())
                                    {
                                        var propName = prop.Name;
                                        if (propName == "DownloadManagerUrl" || propName == "DownloadManagerReference" || propName == "SetupFileName")
                                        {
                                            var value = prop.GetValue(orderline, null);

                                            var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                            {
                                                OrderResponseLine = orderResponseLine
                                            };
                                            orderItemFullfilmentInformation.Type  = propName == "DownloadManagerUrl" ? "Binary" : "Name";
                                            orderItemFullfilmentInformation.Label = propName;
                                            orderItemFullfilmentInformation.Value = value.ToString();
                                            _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                        }
                                    }
                                }
                            }
                            else
                            {
                            }
                        }
                        orderResponse.TotalAmount = TotalAmount;
                    }
                }

                if (failures.Count != 0)
                {
                    log.AuditError("Some orders failed to process: ");
                    foreach (var failure in failures)
                    {
                        log.AuditError(string.Format("Failed ID: {0}", failure.OrderIdentifier));
                    }
                }
            }
            else
            {
                log.AuditError("AtomBlock services are offline, or incorrect credentials");
                return(-1);
            }
            uni.Save();
            return(0);
        }
コード例 #32
0
        /// <summary>
        /// Handles a request to submit a new order
        /// </summary>
        private OrderResponse HandleSubmitOrderRequest(SubmitOrderRequest request)
        {
            OrderTicket ticket;
            var         order = Order.CreateOrder(request);

            if (!_orders.TryAdd(order.Id, order))
            {
                Log.Error("BrokerageTransactionHandler.HandleSubmitOrderRequest(): Unable to add new order, order not processed.");
                return(OrderResponse.Error(request, OrderResponseErrorCode.OrderAlreadyExists, "Cannot process submit request because order with id {0} already exists"));
            }
            if (!_orderTickets.TryGetValue(order.Id, out ticket))
            {
                Log.Error("BrokerageTransactionHandler.HandleSubmitOrderRequest(): Unable to retrieve order ticket, order not processed.");
                return(OrderResponse.UnableToFindOrder(request));
            }

            // update the ticket's internal storage with this new order reference
            ticket.SetOrder(order);

            // check to see if we have enough money to place the order
            bool sufficientCapitalForOrder;

            try
            {
                sufficientCapitalForOrder = _algorithm.Transactions.GetSufficientCapitalForOrder(_algorithm.Portfolio, order);
            }
            catch (Exception err)
            {
                Log.Error(err);
                _algorithm.Error(string.Format("Order Error: id: {0}, Error executing margin models: {1}", order.Id, err.Message));
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Error executing margin models"));
                return(OrderResponse.Error(request, OrderResponseErrorCode.ProcessingError, "Error in GetSufficientCapitalForOrder"));
            }

            if (!sufficientCapitalForOrder)
            {
                order.Status = OrderStatus.Invalid;
                var security = _algorithm.Securities[order.Symbol];
                var response = OrderResponse.Error(request, OrderResponseErrorCode.InsufficientBuyingPower, string.Format("Order Error: id: {0}, Insufficient buying power to complete order (Value:{1}).", order.Id, order.GetValue(security).SmartRounding()));
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Insufficient buying power to complete order"));
                return(response);
            }

            // verify that our current brokerage can actually take the order
            BrokerageMessageEvent message;

            if (!_algorithm.LiveMode && !_algorithm.BrokerageModel.CanSubmitOrder(_algorithm.Securities[order.Symbol], order, out message))
            {
                // if we couldn't actually process the order, mark it as invalid and bail
                order.Status = OrderStatus.Invalid;
                if (message == null)
                {
                    message = new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidOrder", "BrokerageModel declared unable to submit order: " + order.Id);
                }
                var response = OrderResponse.Error(request, OrderResponseErrorCode.BrokerageModelRefusedToSubmitOrder, "OrderID: " + order.Id + " " + message);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "BrokerageModel declared unable to submit order"));
                return(response);
            }

            // set the order status based on whether or not we successfully submitted the order to the market
            bool orderPlaced;

            try
            {
                orderPlaced = _brokerage.PlaceOrder(order);
            }
            catch (Exception err)
            {
                Log.Error(err);
                orderPlaced = false;
            }

            if (!orderPlaced)
            {
                // we failed to submit the order, invalidate it
                order.Status = OrderStatus.Invalid;
                var errorMessage = "Brokerage failed to place order: " + order.Id;
                var response     = OrderResponse.Error(request, OrderResponseErrorCode.BrokerageFailedToSubmitOrder, errorMessage);
                _algorithm.Error(response.ErrorMessage);
                HandleOrderEvent(new OrderEvent(order, _algorithm.UtcTime, 0m, "Brokerage failed to place order"));
                return(response);
            }

            order.Status = OrderStatus.Submitted;
            return(OrderResponse.Success(request));
        }
コード例 #33
0
        public void GetAvailableDispatchAdvices(Models.Vendors.Vendor vendor, AuditLog4Net.Adapter.IAuditLogAdapter log, string logPath, DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            var Username = vendor.VendorSettings.GetValueByKey("Username", string.Empty);
            var Secret   = vendor.VendorSettings.GetValueByKey("Secret", string.Empty);

            var _orderResponseRepo        = unit.Scope.Repository <OrderResponse>();
            var _orderResponseLineRepo    = unit.Scope.Repository <OrderResponseLine>();
            var _orderItemFulfillmentRepo = unit.Scope.Repository <OrderItemFullfilmentInformation>();

            RetailServices10SoapClient client = new RetailServices10SoapClient();

            RetailAccount account = new RetailAccount();

            var inputString = Username + Secret;

            MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();

            byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(inputString);
            byte[] byteHash  = MD5.ComputeHash(byteValue);
            MD5.Clear();

            account.Client     = Username;
            account.SecureHash = Convert.ToBase64String(byteHash);

            var response = client.Ping(account);

            if (response != null)
            {
                log.AuditInfo("AtomBlock services are online");

                //get orderresponses for items pre ordered
                var items = unit.Scope.Repository <OrderResponse>().GetAll(x => x.ResponseType == OrderResponseTypes.ShipmentNotification.ToString() && x.Vendor == vendor);

                foreach (var item in items)
                {
                    var preOrders = item.OrderResponseLines.Where(x => x.Backordered > 0);

                    var OrdersToProcess = new List <string>();

                    foreach (var order in preOrders)
                    {
                        var TotalAmount = 0;
                        var releaseDate = DateTime.Parse(order.Remark.Substring(9).Trim());
                        if (releaseDate < DateTime.Now)
                        {
                            ////item is available so get order details
                            //var productIdentifier = unit.Scope.Repository<ProductDescription>().GetSingle(x => x.ProductName == order.ProductName).Product.VendorItemNumber;//nasty

                            if (order.OrderLineID.HasValue)
                            {
                                var success = client.GetOrderDetails(account, order.OrderLine.OrderID.ToString());
                                if (success.CommunicationStatus.Type == MessageType.OK)
                                {
                                    var Order = order.OrderLine.Order;
                                    //var Order = uni.Scope.Repository<Order>().GetSingle(x => x.OrderID == Int32.Parse(success.OrderIdentifier));
                                    var orderResponse = new OrderResponse
                                    {
                                        Order = Order,
                                        // OrderDate = Order.,
                                        ReceiveDate          = DateTime.Now,
                                        VendorDocument       = "",
                                        Vendor               = vendor,
                                        VendorDocumentNumber = Order.OrderID.ToString()
                                    };
                                    orderResponse.ResponseType = OrderResponseTypes.ShipmentNotification.ToString();
                                    _orderResponseRepo.Add(orderResponse);


                                    foreach (var orderline in success.OrderLines)
                                    {
                                        var name = orderline.Title;

                                        var OrderLine = Order.OrderLines.FirstOrDefault(x => x.Product.ProductDescriptions.FirstOrDefault().ProductName == name);

                                        if (OrderLine != null)
                                        {
                                            var orderResponseLine = new OrderResponseLine
                                            {
                                                OrderResponse = orderResponse,
                                                OrderLine     = OrderLine,
                                                Ordered       = orderline.Quantity,
                                                Backordered   = orderline.IsPreOrder ? orderline.Quantity : 0, //should always be false
                                                Cancelled     = 0,
                                                Shipped       = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                                Invoiced      = orderline.IsPreOrder ? 0 : orderline.Quantity,
                                                Price         = orderline.ItemPrice,
                                                Processed     = false,
                                                Delivered     = 0,
                                                ProductName   = name,
                                                Remark        = orderline.IsPreOrder ? string.Format("PreOrder:{0}", orderline.PreOrderReleaseDate.ToString()) : null
                                            };

                                            _orderResponseLineRepo.Add(orderResponseLine);

                                            TotalAmount += orderline.ItemPrice / 100;

                                            if (!orderline.IsPreOrder)
                                            {
                                                //DownloadFiles
                                                foreach (var file in orderline.DownloadFiles)
                                                {
                                                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                    {
                                                        OrderResponseLine = orderResponseLine
                                                    };
                                                    orderItemFullfilmentInformation.Type  = "Name";
                                                    orderItemFullfilmentInformation.Label = "FileName";
                                                    orderItemFullfilmentInformation.Value = file.File;
                                                    _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                }

                                                //Serials
                                                foreach (var serial in orderline.Serials)
                                                {
                                                    var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                    {
                                                        OrderResponseLine = orderResponseLine
                                                    };
                                                    orderItemFullfilmentInformation.Type  = "Key";
                                                    orderItemFullfilmentInformation.Label = "Serial";
                                                    orderItemFullfilmentInformation.Value = serial.Code;
                                                    _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                }

                                                //additional stuff
                                                foreach (var prop in orderline.GetType().GetProperties())
                                                {
                                                    var propName = prop.Name;
                                                    if (propName == "DownloadManagerUrl" || propName == "DownloadManagerReference" || propName == "SetupFileName")
                                                    {
                                                        var value = prop.GetValue(orderline, null);

                                                        var orderItemFullfilmentInformation = new OrderItemFullfilmentInformation
                                                        {
                                                            OrderResponseLine = orderResponseLine
                                                        };
                                                        orderItemFullfilmentInformation.Type  = propName == "DownloadManagerUrl" ? "Binary" : "Name";
                                                        orderItemFullfilmentInformation.Label = propName;
                                                        orderItemFullfilmentInformation.Value = value.ToString();
                                                        _orderItemFulfillmentRepo.Add(orderItemFullfilmentInformation);
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //hmmzz very strange indeed
                                        }
                                    }
                                    orderResponse.TotalAmount = TotalAmount;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                log.AuditError("AtomBlock services are offline, or incorrect credentials");
            }
        }
コード例 #34
0
ファイル: VistaOrdersDao.cs プロジェクト: OSEHRA/mdo
 internal OrderResponse[] toOrderResponses(string response)
 {
     if (response == "")
     {
         return null;
     }
     ArrayList lst = new ArrayList();
     OrderResponse rsp = null;
     string[] lines = StringUtils.split(response, StringUtils.CRLF);
     for (int i = 0; i < lines.Length; i++)
     {
         if (lines[i] == "")
         {
             continue;
         }
         switch (lines[i][0])
         {
             case '~':
                 if (rsp != null)
                 {
                     lst.Add(rsp);
                 }
                 rsp = new OrderResponse();
                 string[] flds = StringUtils.split(lines[i].Substring(1), StringUtils.CARET);
                 rsp.PromptId = flds[0];
                 rsp.Instance = Convert.ToInt32(flds[1]);
                 rsp.Name = flds[2];
                 rsp.Ivalue = "";
                 rsp.Evalue = "";
                 rsp.Tvalue = "";
                 break;
             case 'i':
                 rsp.Ivalue += lines[i].Substring(1);
                 break;
             case 'e':
                 rsp.Evalue += lines[i].Substring(1);
                 break;
             case 't':
                 rsp.Tvalue += lines[i].Substring(1);
                 break;
         }
     }
     if (rsp != null)
     {
         lst.Add(rsp);
     }
     return (OrderResponse[])lst.ToArray(typeof(OrderResponse));
 }
コード例 #35
0
        public OrderResponse MarkInvoiceAsDownloaded(int companyID, string password, int invoiceID)
        {
            var newResponse = new OrderResponse();
               newResponse.is_error = false;
               try
               {
                    Company currentCompany = Company.GetCompany(companyID);

                    if (currentCompany == null)
                    {
                         newResponse.is_error = true;
                         newResponse.errorMessage = "NoCompany";
                    }
                    else
                    {
                         if (password != currentCompany.api_key)
                         {
                              newResponse.is_error = true;
                              newResponse.errorMessage = "IncorrectPassword";
                         }
                         else
                         {
                              var foundInvoice = Invoice.GetInvoice(invoiceID);
                              if (foundInvoice == null)
                              {
                                   newResponse.is_error = true;
                                   newResponse.errorMessage += "Error with Invoice: " + invoiceID.ToString() + " Invoice not found\r\n";
                              }
                              else
                              {
                                   foundInvoice.is_downloaded = true;
                                   foundInvoice.downloaded_datetime = DateTime.UtcNow;
                                   foundInvoice.Save();
                                   newResponse.statusMessage = "Invoice # " + invoiceID.ToString() + " updated successfully";
                              }
                         }
                    }
               }
               catch (Exception ex)
               {
                    newResponse.is_error = true;
                    newResponse.errorMessage = "GenericError";
                    LogHelper.WriteError(ex.ToString());
               }
               return newResponse;
        }