public async Task <Order> CompleteOrder(int orderId, OrderStateEnum orderState)
        {
            var order = await _context.Orders.Include(o => o.Product).SingleOrDefaultAsync(o => o.Id == orderId);

            var product = order.Product;

            if (order == null)
            {
                throw new ApplicationException($"Order with id: {orderId} doesn't exist");
            }

            if (order.OrderState == OrderStateEnum.Completed || order.OrderState == OrderStateEnum.Cancelled)
            {
                throw new ApplicationException("Completed order state cannot be changed");
            }

            if (orderState == OrderStateEnum.Cancelled)
            {
                // TODO: check if separate product update call required
                product.NumberInStock++;
            }

            order.OrderState          = orderState;
            order.CompletionTimeStamp = DateTime.UtcNow;

            var updatedOrder = _context.Update(order).Entity;

            _context.SaveChanges();

            return(updatedOrder);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public OrderInfo(string orderId, Symbol symbol, OrderTypeEnum orderType, OrderStateEnum state, int volume, Decimal?openPrice, Decimal?closePrice,
                         Decimal?orderStopLoss, Decimal?orderTakeProfit, Decimal?currentProfit, Decimal?orderSwap, DateTime?orderPlatformOpenTime, DateTime?orderPlatformCloseTime,
                         DateTime?orderPlatformPlaceTime, DateTime?orderExpiration, Decimal?orderCommission, string orderComment, string tag)
        {
            _id            = orderId;
            _symbol        = symbol;
            _type          = orderType;
            _volume        = volume;
            _openPrice     = openPrice;
            _closePrice    = closePrice;
            _stopLoss      = orderStopLoss;
            _takeProfit    = orderTakeProfit;
            _currentProfit = currentProfit;
            _swap          = orderSwap;
            _openTime      = orderPlatformOpenTime;
            _placeTime     = orderPlatformPlaceTime;

            _state = state;

            _closeTime  = orderPlatformCloseTime;
            _expiration = orderExpiration;
            _commission = orderCommission;
            _comment    = orderComment;
            _tag        = tag;
        }
 /// <summary>
 /// 获取订单列表
 /// </summary>
 /// <param name="OrderState"></param>
 /// <param name="CustomerId"></param>
 /// <param name="PageSize"></param>
 /// <param name="PageIndex"></param>
 /// <returns></returns>
 public Task <ResponseResult <List <OrderParent> > > GetOrderParentcsList(OrderStateEnum OrderState, int CustomerId, int PageSize, int PageIndex)
 {
     return(Task.Run(() =>
     {
         return GetOrderParentcsListAsync(OrderState, CustomerId, PageSize, PageIndex);
     }));
 }
Exemple #4
0
        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="helper">订单状态操作类</param>
        /// <param name="orderStateEnum">要更新的订单状态</param>
        protected virtual bool UpdateState(OrderStateHelper helper, OrderStateEnum orderStateEnum)
        {
            bool result = false;

            result = new OrderInfoBll().UpdateValue(helper.OrderId, orderStateEnum);
            return(result);
        }
Exemple #5
0
        /// <summary>
        /// Statis helper, allows the calculation of order results.
        /// </summary>
        public static Decimal?GetRawResult(decimal?open, decimal volume, OrderStateEnum state,
                                           OrderTypeEnum type, decimal?ask, decimal?bid, decimal?close, bool considerVolume)
        {
            if (state != OrderStateEnum.Closed && state != OrderStateEnum.Executed)
            {
                if (state == OrderStateEnum.Failed || state == OrderStateEnum.Initialized ||
                    state == OrderStateEnum.UnInitialized || state == OrderStateEnum.Unknown)
                {
                    return(null);
                }

                // Canceled, Submitted
                return(0);
            }

            if (open.HasValue == false ||
                (state == OrderStateEnum.Executed && (ask.HasValue == false || bid.HasValue == false)) ||
                (state == OrderStateEnum.Closed && close.HasValue == false))
            {
                return(null);
            }

            decimal currentValue = 0;

            if (state == OrderStateEnum.Executed)
            {
                currentValue = OrderInfo.TypeIsBuy(type) ? bid.Value : ask.Value;
            }
            else if (state == OrderStateEnum.Closed)
            {
                currentValue = close.Value;
            }
            else
            {
                return(null);
            }

            Decimal difference = 0;

            if (OrderInfo.TypeIsBuy(type))
            {
                difference = currentValue - open.Value;
            }
            else
            {
                difference = open.Value - currentValue;
            }

            if (considerVolume)
            {
                return(volume * difference);
            }
            else
            {
                return(difference);
            }
        }
 private OrderBag ChageState(OrderStateEnum from, OrderStateEnum to)
 {
     if (Order.OrderStateID != from.ToString())
     {
         throw new Exception("非法操作:要将订单状态变更为" + to.ToString() +
                             ",要求订单当前状态必须为:" + from.ToString());
     }
     return(ChageState(to));
 }
Exemple #7
0
 public Mail(User buyer, User seller, Order order, OrderStateEnum state, IConfiguration config, IEnumerable <OrderDetailSummary> cart = null, List <OrderDetail> orderDetails = null)
 {
     Buyer            = buyer;
     Seller           = seller;
     Order            = order;
     State            = state;
     Cart             = cart;
     OrderDetailsList = orderDetails;
     Configuration    = config;
 }
 /// <summary>
 /// Returns an unsafe collection of orders from this state.
 /// </summary>
 public ReadOnlyCollection <Order> GetOrdersByStateUnsafe(OrderStateEnum state)
 {
     lock (this)
     {
         if (_ordersByState.ContainsKey(state) == false)
         {
             return(null);
         }
         return(_ordersByState[state].AsReadOnly());
     }
 }
Exemple #9
0
        /// <summary>
        /// Convert a Date into DD/MMM/YYYY HH:mm format
        /// </summary>
        /// <param name="value">object: value</param>
        /// <param name="targetType">Type: targetType</param>
        /// <param name="parameter">object: parameter</param>
        /// <param name="culture">System.Globalization.CultureInfo: culture</param>
        /// <returns>System.Object</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try {
                OrderStateEnum state = (OrderStateEnum)value;
                Color          color = Colors.White;
                switch (state)
                {
                case OrderStateEnum.accepted:
                    color = Colors.Black;
                    break;

                case OrderStateEnum.askExtended:
                    color = Colors.Black;
                    break;

                case OrderStateEnum.banned:
                    color = Colors.Red;
                    break;

                case OrderStateEnum.completedWithoutEnter:
                    color = Colors.Red;
                    break;

                case OrderStateEnum.canceled:
                    color = Colors.Blue;
                    break;

                case OrderStateEnum.closed:
                    color = Colors.Black;
                    break;

                case OrderStateEnum.created:
                    color = Colors.Black;
                    break;

                case OrderStateEnum.completed:
                    color = Colors.Black;
                    break;

                case OrderStateEnum.extended:
                    color = Colors.Green;
                    break;

                case OrderStateEnum.opened:
                    color = Colors.Black;
                    break;
                }
                return(new SolidColorBrush(color));
            } catch {
                return(new SolidColorBrush(Colors.White));
            }
        }
Exemple #10
0
        internal TestTool(IHost host)
        {
            _highestBid = 0;
            _lowestBid  = decimal.MaxValue;
            _highestAsk = 0;
            _lowestAsk  = decimal.MaxValue;

            #region OUTPUT
            _stringBuilder = new StringBuilder(); //OUTPUT RELATED
            #endregion

            InitializeComponent();

            _host = host;

            _position = _host.GetPosition(Product);
            _level1   = _host.GetLevel1(Product);

            //initialize candlestickCharts here
            //notice the first 4 values are the excel file, sheet, upper right corner of values and lower left corner of values
            //we always need 4 columns: High, Last, Low, Open. If High is column K, then we need the last column to be N
            //the number of the first cell should be the High of the first value you want.
            //the number of the last cell will end up being (the amount of candlesticks you want + the number of the first cell - 1)
            //DON'T F**K THIS UP
            _candlestickChart5 = new CandlestickChart(File, "ES", "K3", "N29", TimerInterval, SlowLength, _level1, tbxAll);

            var marketConditionCoefficient = _candlestickChart5.MarketConditionCoefficient;

            _maxDrawdown        = (int)Math.Round(MaxDrawdown * marketConditionCoefficient);
            _dollarProfitTarget = (int)Math.Round(DollarProfitTarget * marketConditionCoefficient);
            _earned             = (int)Math.Round(Earned * marketConditionCoefficient);
            _percentDown        = (int)Math.Round(PercentDown * marketConditionCoefficient);

            #region OUTPUT
            tbxAll.AppendText("\r\nCoefficient: " + marketConditionCoefficient.ToString("F"));
            tbxAll.AppendText("\r\nPoint: " + Point);
            tbxAll.AppendText("\r\nMax drawdown: " + _maxDrawdown);
            tbxAll.AppendText("\r\nDollar profit target: " + _dollarProfitTarget);
            tbxAll.AppendText("\r\nEarned: " + _earned);
            tbxAll.AppendText("\r\nPercent down: " + _percentDown);
            #endregion

            _fast = _candlestickChart5.AverageLast(CandlestickChart.Point.Close, FastLength);
            _slow = _candlestickChart5.AverageLast(CandlestickChart.Point.Close, SlowLength);

            _signal     = Signals.None;
            _orderState = OrderStateEnum.FILLED;

            _candlestickChart5.Start();

            _level1.Level1Changed += Level1_Level1Changed;
        }
Exemple #11
0
        public string BuildMessage(OrderStateEnum state)
        {
            switch (state)
            {
            case OrderStateEnum.Active:
                var bodyActive = new StringBuilder();
                bodyActive.Append("\n");
                bodyActive.Append("New order is registered!\n");
                bodyActive.Append("\n");
                bodyActive.Append($"Buyer: {Buyer.UserName}\n");
                bodyActive.Append("\n");
                bodyActive.Append($"Seller: {Seller.UserName}\n");
                bodyActive.Append("\n");
                bodyActive.Append("Order details:\n");
                foreach (var item in Cart)
                {
                    bodyActive.Append($"Name: {item.ProductName}, Quantity: {item.Quantity}, Price: {item.Price}\n");
                }
                bodyActive.Append($"Total price: {Cart.Sum(i => i.Quantity * i.Price)}\n");
                bodyActive.Append("\n");
                bodyActive.Append("Delivery to:\n");
                bodyActive.Append($"{Order.Name} {Order.Surname}, {Order.Address}, {Order.City}, {Order.PostCode}\n");
                bodyActive.Append("\n");
                bodyActive.Append("After succesfull transaction pelase confrm it in the user profile panel.\n");
                bodyActive.Append("In other case please cancel the order.\n");
                bodyActive.Append("\n");
                bodyActive.Append("Thank you for using flea market!\n");
                bodyActive.Append("\n");
                return(bodyActive.ToString());

            case OrderStateEnum.Canceled:
                var bodyCancel = new StringBuilder();
                bodyCancel.Append($"\n");
                bodyCancel.Append($"Order No. {Order.OrderId} placed by {Order.Name} {Order.Surname} just got canceled.\n");
                bodyCancel.Append($"Please check your user panel if everything is ok.\n");
                bodyCancel.Append($"\n");
                return(bodyCancel.ToString());

            case OrderStateEnum.Completed:
                var bodyCompleted = new StringBuilder();
                bodyCompleted.Append($"\n");
                bodyCompleted.Append($"Order No. {Order.OrderId} placed by {Order.Name} {Order.Surname} just got marked as copleted!\n");
                bodyCompleted.Append($"\n");
                bodyCompleted.Append($"Thank you for trusting Flea Market!\n");
                bodyCompleted.Append($"\n");
                return(bodyCompleted.ToString());

            default:
                return(String.Empty);
            }
        }
Exemple #12
0
        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="OrderState"></param>
        /// <param name="CustomerId"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public async Task <IActionResult> OrderList(OrderStateEnum OrderState, int CustomerId, int PageSize = 20, int PageIndex = 1)
        {
            ViewBag.Title      = "订单列表";
            ViewBag.CustomerId = CustomerId;
            ResponseResult <List <OrderParent> > responseResult = await _YoungoServer.GetOrderParentcsList(OrderState, CustomerId, PageSize, PageIndex);

            List <OrderParent> list = new List <OrderParent>();

            if (responseResult.IsSuccess)
            {
                list = responseResult.Content;
            }
            return(View(list));
        }
Exemple #13
0
        //[Route("GetOrderParentcsList/{CustomerId:int}")]
        public string GetOrderParentcsList(OrderStateEnum OrderState, int CustomerId, int PageSize, int PageIndex)
        {
            Func <ResponseResult> funcAction = () =>
            {
                var responseModel = new ResponseResult
                {
                    Content   = _YoungoServer.GetOrderParentcsList(OrderState, CustomerId, PageSize, PageIndex),
                    IsSuccess = true,
                    ErrorMsg  = ""
                };
                return(responseModel);
            };

            return(ActionResponseGetString(funcAction));
        }
        /// <summary>
        ///
        /// </summary>
        public List <Order> GetOrdersByState(OrderStateEnum state)
        {
            List <Order> result = new List <Order>();

            lock (this)
            {
                foreach (OrderStateEnum orderState in Enum.GetValues(typeof(OrderStateEnum)))
                {
                    OrderStateEnum filteredState = orderState & state;
                    if (filteredState == orderState && _ordersByState.ContainsKey(orderState))
                    {
                        result.AddRange(_ordersByState[orderState]);
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public OrderInfo(string orderId, Symbol symbol, OrderTypeEnum orderType, OrderStateEnum state, int volume)
        {
            _id            = orderId;
            _symbol        = symbol;
            _type          = orderType;
            _volume        = volume;
            _openPrice     = null;
            _closePrice    = null;
            _stopLoss      = null;
            _takeProfit    = null;
            _currentProfit = null;
            _swap          = null;
            _openTime      = null;
            _placeTime     = null;

            _state = state;

            _closeTime  = null;
            _expiration = null;
            _commission = null;
            _comment    = null;
            _tag        = null;
        }
Exemple #16
0
        private void CreateOrder(SideEnum sideEnum)
        {
            _orderState = OrderStateEnum.NO_ORDER;
            _canCheckForTrailingStop = false;
            _signal = Signals.None;

            _order = _host.CreateOrder(
                Product,
                sideEnum,
                Lots,
                sideEnum == SideEnum.BUY ? _level1.Ask : _level1.Bid,
                TimeInForceEnum.GTC,
                OrderTypeMarket);

            if (_order == null)
            {
                return;
            }

            _order.ExecutionReport += Order_ExecutionReport;
            _order.Anonymous        = "Y"; // values = "Y" or "N"
            _order.Send();
        }
Exemple #17
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            OrderStateEnum orderState = (OrderStateEnum)value;

            switch (orderState)
            {
            case OrderStateEnum.Complite:
                return(new LinearGradientBrush(
                           Color.FromRgb(134, 255, 151), Color.FromRgb(118, 254, 137), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.Work:
                return(new LinearGradientBrush(
                           Color.FromRgb(255, 254, 158), Color.FromRgb(255, 254, 137), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.New:
                return(new LinearGradientBrush(
                           Color.FromRgb(161, 208, 252), Color.FromRgb(161, 208, 230), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.Canceled:
                return(new LinearGradientBrush(
                           Color.FromRgb(231, 231, 231), Color.FromRgb(220, 220, 220), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            default:
                return(new LinearGradientBrush(
                           Color.FromRgb(255, 255, 255), Color.FromRgb(255, 255, 255), new Point(0.5, 0), new Point(0.5, 1)));

                break;
            }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            OrderStateEnum orderState = (OrderStateEnum)value;

            switch (orderState)
            {
            case OrderStateEnum.Complite:
                return(new LinearGradientBrush(
                           Color.FromRgb(115, 223, 130), Color.FromRgb(115, 223, 110), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.Work:
                return(new LinearGradientBrush(
                           Color.FromRgb(225, 224, 132), Color.FromRgb(225, 224, 110), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.New:
                return(new LinearGradientBrush(
                           Color.FromRgb(129, 181, 229), Color.FromRgb(129, 181, 210), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            case OrderStateEnum.Canceled:
                return(new LinearGradientBrush(
                           Color.FromRgb(210, 210, 210), Color.FromRgb(200, 200, 200), new Point(0.5, 0), new Point(0.5, 1)));

                break;

            default:
                return(new LinearGradientBrush(
                           Color.FromRgb(255, 255, 255), Color.FromRgb(240, 240, 240), new Point(0.5, 0), new Point(0.5, 1)));

                break;
            }
        }
Exemple #19
0
        private void Order_ExecutionReport(long toolId, ExecutionReport execReport)
        {
            // Information available in the execReport object.
            var  lastPrice     = (decimal)execReport.LastPx; // Price of this (last) fill.
            var  orderQuantity = (int)execReport.OrderQty;   // Number of shares ordered.
            char side          = execReport.Side;            // '1'=Buy, '2'=Sell, '3'=Buy Minus, '4'=Sell Plus, '5'=Sell Short, '6'=Sell Short Exempt, '7'=Undisclosed, '8'=Cross, '9'=Cross Short.

            if (execReport.OrdStatus != 2)
            {
                return;
            }

            // Order completely filled, no remaining quantity.
            if (_trade != null)
            {
                _trade.ClosePrice = lastPrice;
                _trade.ClosedAt   = DateTime.Now;

                #region output
                textBox1.AppendText("TRADE: Position: " + _trade.Position + " | Open Price: " + _trade.OpenPrice +
                                    " @ " + _trade.OpenedAt + " | Close Price: " + _trade.ClosePrice + " @ " + _trade.ClosedAt + " | Drawdown: " + _trade.Drawdown + "\r\n");
                #endregion

                _trade = orderQuantity > Lots ? new Trade(lastPrice, side == '2' ? Lots * -1 : Lots) : null;
            }
            else
            {
                _trade = new Trade(lastPrice, side == '2' ? Lots * -1 : Lots);
            }

            _lastPrice  = lastPrice;
            _highestBid = _level1.Bid;
            _lowestAsk  = _level1.Ask;

            _orderState = OrderStateEnum.FILLED;
        }
        /// <summary>
        /// Constructor.
        /// </summary>
        public OrderInfo(string orderId)
        {
            _id    = orderId;
            _type  = OrderTypeEnum.UNKNOWN;
            _state = OrderStateEnum.Unknown;

            _symbol = Symbol.Empty;

            _volume        = 0;
            _openPrice     = null;
            _closePrice    = null;
            _stopLoss      = null;
            _takeProfit    = null;
            _currentProfit = null;
            _swap          = null;
            _openTime      = null;
            _placeTime     = null;

            _closeTime  = null;
            _expiration = null;
            _commission = null;
            _comment    = null;
            _tag        = null;
        }
Exemple #21
0
        /// <summary>
        /// NON UI Thread.
        /// </summary>
        //protected void DoObtainAllOrders(bool showError)
        //{
        //foreach (ExpertSession session in _sessions.ToArray())
        //{
        //    if (session.OrderExecutionProvider == null ||
        //        session.OrderExecutionProvider.OperationalState != OperationalStateEnum.Operational)
        //    {
        //        continue;
        //    }

        //    string operationResultMessage;
        //    if (session.OrderExecutionProvider.DefaultAccount != null &&
        //        session.OrderExecutionProvider.DefaultAccount.SynchronizeOrders(null, out operationResultMessage) == false)
        //    {
        //        if (showError)
        //        {
        //            MessageBox.Show("Failed to obtain orders session [" + session.Info.Name + "] [" + operationResultMessage + "].", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //        else
        //        {
        //            SystemMonitor.OperationError("Failed to obtain orders session [" + session.Info.Name + "] [" + operationResultMessage + "].");
        //        }
        //    }
        //}

        //WinFormsHelper.BeginFilteredManagedInvoke(this, new GeneralHelper.DefaultDelegate( delegate() { toolStripButtonObtainOrders.Enabled = true; }));
        //}

        protected ListViewItem SetItemAsOrder(ListViewItem item, Order order, AccountInfo account)
        {
            if (item.Tag != order)
            {
                item.Tag = order;
            }

            if (item.UseItemStyleForSubItems != false)
            {
                item.UseItemStyleForSubItems = false;
            }

            OrderStateEnum orderState = order.State;
            string         groupName  = string.Format("{0} Orders, Server [{1}] Company [{2}] Account [{3} / {4}]", orderState.ToString().ToUpper(), account.Server, account.Company, account.Name, account.Id);

            ListViewGroup group = listViewOrders.Groups[groupName];

            if (group == null)
            {
                group = new ListViewGroup(groupName, groupName);

                if (orderState == OrderStateEnum.Executed)
                {// Insert group at top of list.
                    listViewOrders.Groups.Insert(0, group);
                }
                else if (orderState == OrderStateEnum.Submitted)
                {// ...
                    listViewOrders.Groups.Insert(0, group);
                }
                else
                {
                    listViewOrders.Groups.Add(group);
                }
            }

            if (item.Group != group)
            {
                item.Group = group;
            }

            if (order.IsBuy)
            {
                int index = order.State == OrderStateEnum.Executed ? 0 : 2;
                if (item.ImageIndex != index)
                {
                    item.ImageIndex = index;
                }
            }
            else
            {
                int index = order.State == OrderStateEnum.Executed ? 1 : 3;
                if (item.ImageIndex != index)
                {
                    item.ImageIndex = index;
                }
            }

            while (item.SubItems.Count < 12)
            {
                item.SubItems.Add("");
            }

            //if (order.Type == OrderTypeEnum.UNKNOWN)
            //{// Order type not established yet.
            //    item.SubItems[0].Text = "NA";
            //    return item;
            //}

            string id = order.Id;

            if (id == null)
            {
                id = string.Empty;
            }

            if (item.SubItems[0].Text != id)
            {
                item.SubItems[0].Text = id;
            }

            if (item.SubItems[1].Text != order.Symbol.Name)
            {
                item.SubItems[1].Text = order.Symbol.Name;
            }

            if (order.IsOpenOrPending)
            {
                if (item.SubItems[2].Text != (GeneralHelper.GetShortDateTime(order.OpenTime)))
                {
                    item.SubItems[2].Text = (GeneralHelper.GetShortDateTime(order.OpenTime));
                }
            }
            else
            {
                if (item.SubItems[2].Text != (GeneralHelper.GetShortDateTime(order.OpenTime) + " to " + GeneralHelper.GetShortDateTime(order.CloseTime)))
                {
                    item.SubItems[2].Text = (GeneralHelper.GetShortDateTime(order.OpenTime) + " to " + GeneralHelper.GetShortDateTime(order.CloseTime));
                }
            }

            if (item.SubItems[3].Text != (order.Type.ToString()))
            {
                item.SubItems[3].Text = (order.Type.ToString());
            }

            if (item.SubItems[4].Text != (GeneralHelper.ToString(order.CurrentVolume)))
            {
                item.SubItems[4].Text = GeneralHelper.ToString(order.CurrentVolume);
            }

            if (item.SubItems[5].Text != GeneralHelper.ToString(order.OpenPrice))
            {
                item.SubItems[5].Text = GeneralHelper.ToString(order.OpenPrice);
            }

            string closePriceValue = GeneralHelper.ToString(order.ClosePrice);

            if (item.SubItems[6].Text != closePriceValue)
            {
                item.SubItems[6].Text = closePriceValue;
            }

            if (item.SubItems[7].Text != GeneralHelper.ToString(order.StopLoss))
            {
                item.SubItems[7].Text = GeneralHelper.ToString(order.StopLoss);
            }

            if (item.SubItems[8].Text != GeneralHelper.ToString(order.TakeProfit))
            {
                item.SubItems[8].Text = GeneralHelper.ToString(order.TakeProfit);
            }

            if (item.SubItems[9].Text != ("-"))
            {
                item.SubItems[9].Text = ("-");
            }

            decimal?currentResultPips         = order.GetResult(Order.ResultModeEnum.Pips);
            decimal?currentResultBaseCurrency = order.GetResult(Order.ResultModeEnum.Currency);

            string resultString;

            if (currentResultBaseCurrency.HasValue == false ||
                currentResultBaseCurrency.HasValue == false)
            {
                resultString = "NaN";
            }
            else
            {
                resultString = currentResultPips.Value.ToString("0.#") + "p / " + currentResultBaseCurrency.Value.ToString("0.#");
            }

            if (item.SubItems[10].Text != resultString)
            {
                item.SubItems[10].Text = resultString;
            }

            if (currentResultPips < 0)
            {
                if (item.SubItems[10].BackColor != Color.MistyRose)
                {
                    item.SubItems[10].BackColor = Color.MistyRose;
                }
            }
            else
            {
                if (item.SubItems[10].BackColor != Color.Transparent)
                {
                    item.SubItems[10].BackColor = Color.Transparent;
                }
            }

            if (item.SubItems[11].Text != "-")
            {
                item.SubItems[11].Text = ("-");
            }

            return(item);
        }
 private OrderBag ChageState(OrderStateEnum state)
 {
     Order.OrderStateID = state.ToString();
     return(this);
 }
Exemple #23
0
        /// <summary>
        /// Static helper.
        /// </summary>
        public static decimal?GetResult(ResultModeEnum mode, decimal?open, decimal?close, decimal volume, Symbol orderSymbol,
                                        OrderStateEnum state, OrderTypeEnum type, CurrencyConversionManager convertor, Symbol accountCurrency,
                                        decimal lotSize, int decimalPlaces, decimal?ask, decimal?bid)
        {
            if (/*ask.HasValue == false || bid.HasValue == false */
                string.IsNullOrEmpty(orderSymbol.Name))
            {
                return(null);
            }

            Decimal?currentRawResult = null;

            if (state == OrderStateEnum.Executed)
            {
                // Update result.
                currentRawResult = GetRawResult(open, volume, state, type, ask, bid, null, mode != ResultModeEnum.Pips);
            }
            else if (state == OrderStateEnum.Closed)
            {
                currentRawResult = GetRawResult(open, volume, state, type, null, null, close.Value, mode != ResultModeEnum.Pips);
            }

            if (currentRawResult.HasValue == false)
            {
                return(null);
            }

            if (mode == ResultModeEnum.Pips)
            {
                //if (state == OrderStateEnum.Closed)
                //{// When closed we need to compensate the
                //    if (OrderInfo.TypeIsBuy(type))
                //    {
                //        return (close - open) * (decimal)Math.Pow(10, decimalPlaces);
                //    }
                //    else
                //    {
                //        return (open - close) * (decimal)Math.Pow(10, decimalPlaces);
                //    }
                //}
                //else
                //{
                return(currentRawResult * (decimal)Math.Pow(10, decimalPlaces));
                //}
            }
            else if (mode == ResultModeEnum.Raw)
            {
                return(currentRawResult);
            }
            else if (mode == ResultModeEnum.Currency)
            {
                return(currentRawResult);
            }
            else if (mode == ResultModeEnum.AccountBaseCurrency)
            {
                if (string.IsNullOrEmpty(accountCurrency.Name) || convertor == null)
                {
                    SystemMonitor.Warning("Mode requires the Account Currency and Convertion Manager to be specified.");
                    return(null);
                }

                if (orderSymbol.IsForexPair)
                {// We have a forex pair and need to rebase to account base currency.
                    double?conversionRate = convertor.GetRate(orderSymbol.ForexCurrency2, accountCurrency.Name, TimeSpan.FromSeconds(1.5), true);
                    if (conversionRate.HasValue == false)
                    {
                        SystemMonitor.OperationError("Failed to establish conversion rate between [" + orderSymbol.ForexCurrency2 + "] and [" + accountCurrency.Name + "].");
                        return(null);
                    }
                }
                else
                {// All other symbols are by default in account base currency prices.
                    return(currentRawResult.Value);
                }
            }

            SystemMonitor.NotImplementedCritical("Mode not supported.");
            return(0);
        }
Exemple #24
0
 public static string Parse(this OrderStateEnum orderState)
 {
     return(orderState.ToString());
 }
 /// <summary>
 /// Changes the main state of a single order
 /// </summary>
 /// <param name="id">The internal id of the order</param>
 /// <param name="state">The data used to change the state</param>
 public void ChangeOrderState(long id, OrderStateEnum state)
 {
     put <object>($"/orders/{id}/orderstate", new { NewStateId = (int)state }, null);
 }
        /// <summary>
        /// Static helper.
        /// </summary>
        public static decimal? GetResult(ResultModeEnum mode, decimal? open, decimal? close, decimal volume, Symbol orderSymbol,
            OrderStateEnum state, OrderTypeEnum type, CurrencyConversionManager convertor, Symbol accountCurrency, 
            decimal lotSize, int decimalPlaces, decimal? ask, decimal? bid)
        {
            if (/*ask.HasValue == false || bid.HasValue == false */
                string.IsNullOrEmpty(orderSymbol.Name))
            {
                return null;
            }

            Decimal? currentRawResult = null;
            if (state == OrderStateEnum.Executed)
            {
                // Update result.
                currentRawResult = GetRawResult(open, volume, state, type, ask, bid, null, mode != ResultModeEnum.Pips);
            }
            else if (state == OrderStateEnum.Closed)
            {
                currentRawResult = GetRawResult(open, volume, state, type, null, null, close.Value, mode != ResultModeEnum.Pips);
            }

            if (currentRawResult.HasValue == false)
            {
                return null;
            }

            if (mode == ResultModeEnum.Pips)
            {
                //if (state == OrderStateEnum.Closed)
                //{// When closed we need to compensate the
                //    if (OrderInfo.TypeIsBuy(type))
                //    {
                //        return (close - open) * (decimal)Math.Pow(10, decimalPlaces);
                //    }
                //    else
                //    {
                //        return (open - close) * (decimal)Math.Pow(10, decimalPlaces);
                //    }
                //}
                //else
                //{
                    return currentRawResult * (decimal)Math.Pow(10, decimalPlaces);
                //}
            }
            else if (mode == ResultModeEnum.Raw)
            {
                return currentRawResult;
            }
            else if (mode == ResultModeEnum.Currency)
            {
                return currentRawResult;
            }
            else if (mode == ResultModeEnum.AccountBaseCurrency)
            {
                if (string.IsNullOrEmpty(accountCurrency.Name) || convertor == null)
                {
                    SystemMonitor.Warning("Mode requires the Account Currency and Convertion Manager to be specified.");
                    return null;
                }

                if (orderSymbol.IsForexPair)
                {// We have a forex pair and need to rebase to account base currency.
                    double? conversionRate = convertor.GetRate(orderSymbol.ForexCurrency2, accountCurrency.Name, TimeSpan.FromSeconds(1.5), true);
                    if (conversionRate.HasValue == false)
                    {
                        SystemMonitor.OperationError("Failed to establish conversion rate between [" + orderSymbol.ForexCurrency2 + "] and [" + accountCurrency.Name + "].");
                        return null;
                    }
                }
                else
                {// All other symbols are by default in account base currency prices.
                    return currentRawResult.Value;
                }
            }

            SystemMonitor.NotImplementedCritical("Mode not supported.");
            return 0;
        }
        /// <summary>
        ///
        /// </summary>
        public bool Update(OrderInfo updateInfo)
        {
            if (updateInfo.Id != _id ||
                (updateInfo.Symbol.Name != _symbol.Name)
                // Can not filter type here, since type may change (for ex. the server may accept market orders as Market_Limit)
                /*|| (updateInfo.Type != OrderTypeEnum.UNKNOWN && updateInfo.Type != Type)*/)
            {
                SystemMonitor.Warning("Mismatching order basic parameters.");
                return(false);
            }

            _volume = updateInfo._volume;
            _state  = updateInfo._state;

            if (updateInfo._openPrice.HasValue)
            {
                _openPrice = updateInfo._openPrice;
            }

            if (updateInfo._closePrice.HasValue)
            {
                _closePrice = updateInfo._closePrice;
            }

            //if (updateInfo._stopLoss.HasValue)
            {
                _stopLoss = updateInfo._stopLoss;
            }

            //if (updateInfo._takeProfit.HasValue)
            {
                _takeProfit = updateInfo._takeProfit;
            }

            if (updateInfo._currentProfit.HasValue)
            {
                _currentProfit = updateInfo._currentProfit;
            }

            if (updateInfo._swap.HasValue)
            {
                _swap = updateInfo._swap;
            }

            if (updateInfo._closeTime.HasValue)
            {
                _closeTime = updateInfo._closeTime;
            }

            if (updateInfo._openTime.HasValue)
            {
                _openTime = updateInfo._openTime;
            }

            if (updateInfo._expiration.HasValue)
            {
                _expiration = updateInfo._expiration;
            }

            if (updateInfo._commission.HasValue)
            {
                _commission = updateInfo._commission;
            }

            if (updateInfo._comment != null)
            {
                _comment = updateInfo._comment;
            }

            if (updateInfo._tag != null)
            {
                _tag = updateInfo._tag;
            }

            return(true);
        }
        /// <summary>
        /// Statis helper, allows the calculation of order results.
        /// </summary>
        public static Decimal? GetRawResult(decimal? open, decimal volume, OrderStateEnum state,
            OrderTypeEnum type, decimal? ask, decimal? bid, decimal? close, bool considerVolume)
        {
            if (state != OrderStateEnum.Closed && state != OrderStateEnum.Executed)
            {
                if (state == OrderStateEnum.Failed || state == OrderStateEnum.Initialized
                    || state == OrderStateEnum.UnInitialized || state == OrderStateEnum.Unknown)
                {
                    return null;
                }

                // Canceled, Submitted
                return 0;
            }

            if (open.HasValue == false
                || (state == OrderStateEnum.Executed && (ask.HasValue == false || bid.HasValue == false))
                || (state == OrderStateEnum.Closed && close.HasValue == false))
            {
                return null;
            }

            decimal currentValue = 0;

            if (state == OrderStateEnum.Executed)
            {
                currentValue = OrderInfo.TypeIsBuy(type) ? bid.Value : ask.Value;
            }
            else if (state == OrderStateEnum.Closed)
            {
                currentValue = close.Value;
            }
            else
            {
                return null;
            }

            Decimal difference = 0;
            if (OrderInfo.TypeIsBuy(type))
            {
                difference = currentValue - open.Value;
            }
            else
            {
                difference = open.Value - currentValue;
            }

            if (considerVolume)
            {
                return volume * difference;
            }
            else
            {
                return difference;
            }
        }
 partial void OnOrderStateChanging(OrderStateEnum value);
        /// <summary>
        /// Convert a Date into DD/MMM/YYYY HH:mm format
        /// </summary>
        /// <param name="value">object: value</param>
        /// <param name="targetType">Type: targetType</param>
        /// <param name="parameter">object: parameter</param>
        /// <param name="culture">System.Globalization.CultureInfo: culture</param>
        /// <returns>System.Object</returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try {
                Color  color = Colors.Transparent;
                string param = parameter.ToString();
                if (param == "State")
                {
                    OrderStateEnum state = (OrderStateEnum)value;
                    switch (state)
                    {
                    case OrderStateEnum.accepted:
                        color = Color.FromArgb(255, 204, 255, 255);
                        break;

                    case OrderStateEnum.askExtended:
                        color = Color.FromArgb(255, 255, 255, 153);
                        break;

                    case OrderStateEnum.banned:
                        color = Colors.LightGray;
                        break;

                    case OrderStateEnum.canceled:
                        color = Colors.LightGray;
                        break;

                    case OrderStateEnum.closed:
                        color = Color.FromArgb(255, 204, 204, 255);
                        break;

                    case OrderStateEnum.created:
                        color = Colors.White;
                        break;

                    case OrderStateEnum.completed:
                        color = Colors.LightGray;
                        break;

                    case OrderStateEnum.completedWithoutEnter:
                        color = Colors.LightGray;
                        break;

                    case OrderStateEnum.extended:
                        color = Colors.LightGray;
                        break;

                    case OrderStateEnum.opened:
                        color = Color.FromArgb(255, 204, 255, 204);
                        break;
                    }
                }
                else if (param == "type")
                {
                    OrderTypeEnum type = (OrderTypeEnum)value;
                    switch (type)
                    {
                    case OrderTypeEnum.crash:
                        color = Colors.Red;
                        break;

                    case OrderTypeEnum.npl:
                        color = Color.FromArgb(255, 255, 204, 204);
                        break;

                    case OrderTypeEnum.pl:
                        color = Color.FromArgb(255, 153, 255, 204);
                        break;

                    case OrderTypeEnum.no:
                        color = Colors.Orange;
                        break;
                    }
                }
                else if (param == "Time")
                {
                    double?time = (double?)value;
                    if (time.HasValue)
                    {
                        if (time.Value < 0)
                        {
                            color = Colors.Red;
                        }
                        else if (time.Value < 2)
                        {
                            color = Colors.Orange;
                        }
                        else if (time.Value < 8)
                        {
                            color = Colors.Yellow;
                        }
                    }
                }
                else if (param == "Expired")
                {
                    double?time = (double?)value;
                    color = Colors.Transparent;
                    if (time.HasValue)
                    {
                        /*if (time.Value > -2)
                         *      color = Color.FromArgb(255, 153, 255, 204);
                         * else */if (time.Value < -2)
                        {
                            color = Color.FromArgb(255, 255, 204, 204);
                        }
                    }
                }
                return(new SolidColorBrush(color));
            } catch {
                return(new SolidColorBrush(Colors.Transparent));
            }
        }
        /// <summary>
        /// Returns an unsafe collection of orders from this state.
        /// </summary>
        public ReadOnlyCollection<Order> GetOrdersByStateUnsafe(OrderStateEnum state)
        {
            lock (this)
            {
                if (_ordersByState.ContainsKey(state) == false)
                {
                    return null;

                }
                return _ordersByState[state].AsReadOnly();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public List<Order> GetOrdersByState(OrderStateEnum state)
        {
            List<Order> result = new List<Order>();
            lock (this)
            {
                foreach (OrderStateEnum orderState in Enum.GetValues(typeof(OrderStateEnum)))
                {
                    OrderStateEnum filteredState = orderState & state;
                    if (filteredState == orderState && _ordersByState.ContainsKey(orderState))
                    {
                        result.AddRange(_ordersByState[orderState]);
                    }
                }
            }

            return result;
        }
        // >>
        public void OrderInformation(int orderTicket, int operationID, string orderSymbol, int orderType, decimal volume,
                                     decimal inputOpenPrice, decimal inputClosePrice, decimal inputOrderStopLoss, decimal inputOrderTakeProfit,
                                     decimal currentProfit, decimal orderSwap, int inputOrderPlatformOpenTime,
                                     int inputOrderPlatformCloseTime, int inputOrderExpiration, decimal orderCommission,
                                     string orderComment, int orderCustomID, bool operationResult, string operationResultMessage)
        {
            TracerHelper.TraceEntry(string.Format("ticketId[{0}], customId[{1}], operationId[{2}], symbol[{3}], SL[{4}, TP[{5}]", orderTicket.ToString(),
                                                  orderCustomID.ToString(), operationID.ToString(), orderSymbol, inputOrderStopLoss.ToString(), inputOrderTakeProfit.ToString()));

            try
            {
                #region Preprocess Data

                decimal?openPrice              = Convert(inputOpenPrice);
                decimal?closePrice             = Convert(inputClosePrice);
                decimal?orderStopLoss          = Convert(inputOrderStopLoss);
                decimal?orderTakeProfit        = Convert(inputOrderTakeProfit);
                int?    orderPlatformOpenTime  = Convert(inputOrderPlatformOpenTime);
                int?    orderPlatformCloseTime = Convert(inputOrderPlatformCloseTime);
                int?    orderExpiration        = Convert(inputOrderExpiration);

                // Perform dataDelivery fixes to convert to proper cases.
                bool isOpen = orderPlatformCloseTime.HasValue == false || orderPlatformCloseTime == 0;

                OrderStateEnum orderState = OrderStateEnum.Unknown;
                // According to documentataion this is the way to establish if order is closed, see here : http://docs.mql4.com/trading/OrderSelect
                if (isOpen)
                {
                    if (CommonFinancial.OrderInfo.TypeIsDelayed((OrderTypeEnum)orderType) == false &&
                        orderPlatformOpenTime > 0)
                    {
                        orderState = OrderStateEnum.Executed;
                    }
                    else
                    {
                        orderState = OrderStateEnum.Submitted;
                    }
                }
                else
                {
                    orderState = OrderStateEnum.Closed;
                }

                if (orderState == OrderStateEnum.Executed)
                {// Since the integration might report close price for opened orders, at the current closing price.
                    closePrice = null;
                }

                DateTime?openTime       = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformOpenTime);
                DateTime?closeTime      = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformCloseTime);
                DateTime?expirationTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderExpiration);

                CombinedDataSubscriptionInformation sessionSubscriptionInfo = GetDataSession(orderSymbol);

                if (sessionSubscriptionInfo == null)
                {
                    SystemMonitor.Error("Corresponding symbol [" + orderSymbol + "] session info not found.");
                    return;
                }

                #endregion

                bool      isNewlyAcquired  = false;
                OrderInfo?orderInformation = null;

                if (orderTicket > -1)
                {// Store call information for later use.
                    orderInformation = new OrderInfo(
                        orderTicket.ToString(), sessionSubscriptionInfo.SessionInformation.Info.Symbol, ConvertOrderType(orderType), orderState,
                        ConvertVolume(sessionSubscriptionInfo.SessionInformation.Info.LotSize, volume), openPrice, closePrice,
                        orderStopLoss, orderTakeProfit, currentProfit,
                        orderSwap, openTime, closeTime, openTime,
                        expirationTime, orderCommission, orderComment, orderCustomID.ToString());

                    lock (this)
                    {
                        isNewlyAcquired = _orders.ContainsKey(orderTicket.ToString()) == false || _orders[orderTicket.ToString()].HasValue == false;
                        _orders[orderTicket.ToString()] = orderInformation;
                    }

                    TracerHelper.TraceEntry(string.Format("Storing information, id[{0}], symb[{1}], customId[{2}], operationId[{3}].", orderTicket.ToString(), orderSymbol, orderCustomID.ToString(), operationID));
                }
                else
                {// This used to be flush call (send all stored to user), but currently not used.
                    SystemMonitor.NotImplementedError("Case not implemented.");
                }

                //if (isNewlyAcquired)
                {// Send a notification to subscribers, an order orderInfo was acquired.
                    OrdersInformationUpdateResponseMessage message = new OrdersInformationUpdateResponseMessage(_accountInfo,
                                                                                                                new OrderInfo[] { orderInformation.Value }, true);

                    SendToSubscribers(message);
                }
            }
            catch (Exception ex)
            {// Make sure we handle any possible unexpected exceptions, as otherwise they bring the
                // entire package (MT4 included) down with a bad error.
                SystemMonitor.Error(ex.Message);
            }
        }
        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="OrderState"></param>
        /// <param name="CustomerId"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public async Task <ResponseResult <List <OrderParent> > > GetOrderParentcsListAsync(OrderStateEnum OrderState, int CustomerId, int PageSize, int PageIndex)
        {
            string Action     = "Youngo";
            string Function   = "/GetOrderParentcsList";
            string Parameters = string.Format("OrderState={0}&CustomerId={1}&PageSize={2}&PageIndex={3}", OrderState, CustomerId, PageSize, PageIndex);;
            string result     = await httpHelper.QueryData(Api_Host + Action + Function
                                                           , Parameters, HttpHelper.MethodType.GET, HttpHelper.SelectType.Select);

            return(await Task.Run(() =>
            {
                return JsonConvert.DeserializeObject <ResponseResult <List <OrderParent> > >(result);
            }));
        }
Exemple #35
0
        /// <summary>
        /// 获取订单列表
        /// </summary>
        /// <param name="OrderState"></param>
        /// <param name="CustomerId"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        public List <OrderParent> GetOrderParentcsList(OrderStateEnum OrderState, int CustomerId, int PageSize, int PageIndex)
        {
            //sql语句
            string sql = @"SELECT
	                        od.Id,
	                        op.CustomerID,
	                        od.ProductID,
	                        od.OrderID,
	                        op.TraceID,
	                        op.PackPrice,
	                        op.ExpressPrice,
	                        op.OrderState,
	                        op.PaymentType,
	                        da.ReceiveName,
	                        da.Address,
	                        da.Province,
	                        da.City,
	                        da.Area,
	                        da.Phone,
	                        od.Number,
	                        p.PurchasePrice,
	                        p.CnName AS ProductName,
	                        op.TotalPrice,
	                        op.CustomerRemarks,
	                        op.DeliveryTime,
	                        op.PayTime,
	                        op.FinishTime,
	                        op.UpdateTime,
	                        op.CreatTime,
	                        r.Address AS Picture
                        FROM
	                        OnLineOrderDetail AS od
                        INNER JOIN  OnLineOrderParent AS op ON op.OrderID = od.OrderID
                        INNER JOIN Product AS p ON p.ProductID = od.ProductID
                        INNER JOIN DeliveryAddress AS da ON op.DeliveryAddressID = da.Id
                        LEFT JOIN Resources AS r ON p.ProductID = r.ProductID
                        AND r.Type = 1 and Sort =0
                        WHERE op.IsDelete = 0 AND op.CustomerID = @customerId ";

            if (OrderState != OrderStateEnum.All)
            {
                sql += "AND op.OrderState = @orderState ";
            }
            sql += "LIMIT @pageIndex,@page";

            SugarParameter[] parameters = new SugarParameter[]
            {
                new SugarParameter("@orderState", OrderState),
                new SugarParameter("@customerId", CustomerId),
                new SugarParameter("@pageIndex", (PageIndex - 1) * PageSize),
                new SugarParameter("@page", PageSize)
            };
            parameters[0].DbType = System.Data.DbType.Int32;
            parameters[1].DbType = System.Data.DbType.Int32;
            parameters[2].DbType = System.Data.DbType.Int32;
            parameters[3].DbType = System.Data.DbType.Int32;

            List <OrderParent> orderParentList = _db.Ado.SqlQuery <OrderParent>(sql, parameters).ToList();

            return(orderParentList);
        }