Exemplo n.º 1
0
        protected override void OnPendingOrderCreated(PendingOrder newPendingOrder)
        {
            if (newPendingOrder.TradeType == TradeType.Sell)
                ordemv = newPendingOrder;
            else
                ordemc = newPendingOrder;

        }
Exemplo n.º 2
0
 /// <summary>
 /// Change parameters for pending order
 /// </summary>
 /// <param name="ord"></param>
 /// <returns></returns>
 protected RequestStatus ModifyPendingOrder(PendingOrder ord)
 {
     return(robotContext.SendEditPendingRequest(protectedContext.MakeProtectedContext(), ord));
 }
Exemplo n.º 3
0
 /// <summary>
 /// Вызывается на торговых событиях установка снятие ордера, изменение параметров, срабатывание ордера
 /// </summary>
 /// <param name="order"></param>
 public virtual void OnTradeEvent(PendingOrder order)
 {
     TerminalLog.Instance.SaveRobotLog(string.Format("робот {0}: срабатывание отложенного ордера {1}, {2}, статус {3}, side = {4}",
                                                     TypeName, order.ID, order.Symbol, order.Status, order.Side));
 }
        public static bool CreateStopOrder(this IStrategyBase Strategy, StringBuilder sb, TradeType?direction,
                                           double price, long size, double?sl, double?tp, string comment, out PendingOrder po)
        {
            TradeResult result = Strategy.Robot.PlaceStopOrder(direction.Value, Strategy.Symbol,
                                                               size, price, Strategy.GetLabel(), sl, tp, null, comment);

            if (result.IsSuccessful)
            {
                po = result.PendingOrder;
                sb.AppendLine("Created Stop: {0} {1} {2} {3}", direction.Value, Strategy.Symbol.Code, size, price);
            }
            else
            {
                po = null;
                sb.AppendLine("Stop Limit order failed {0}", result.Error);
            }
            return(result.IsSuccessful);
        }
Exemplo n.º 5
0
 /// <summary>
 /// Moneymanagement adjustments
 /// </summary>
 /// <param name="order"></param>
 public override void MoneyManagement(PendingOrder order)
 {
 }
Exemplo n.º 6
0
 /// <summary>
 /// Get commission and fees
 /// </summary>
 /// <param name="order"></param>
 /// <returns></returns>
 public decimal GetCommissionAndFees(PendingOrder order)
 => 0m;
 private string _getPendingOrderString(PendingOrder o, string action)
 {
     return _getPositionString(action, o.SymbolCode, o.Label, o.Volume, o.TradeType.ToString());
 }
Exemplo n.º 8
0
 /// <summary>
 /// send order that is compatible with OrderDelegate events
 /// </summary>
 /// <param name="o"></param>
 public void SendOrder(PendingOrder o)
 {
     SendOrderStatus(o);
 }
Exemplo n.º 9
0
 internal void Reset()
 {
     RobotPosition     = null;
     RobotPendingOrder = null;
     Status            = TradeStatus.Inactive;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Process submit order
        /// </summary>
        /// <param name="ticket"></param>
        protected virtual OrderTicketResponse SubmitOrder(SubmitOrderTicket ticket)
        {
            //Get order from factory
            PendingOrder pendingorder = OrderFactory.CreateOrder(ticket);
            OrderImpl    order        = pendingorder.Order as OrderImpl;

            //Round off order quantity for correct amounts
            RoundLotSize(order);

            //try and get the order from the order tracker
            if (!OrderTracker.TryAddOrder(pendingorder))
            {
                _log.Error($"Unable to add new order, order with id {pendingorder.OrderId} was already submitted");
                return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.OrderAlreadyExists, $"Current order with id {pendingorder.OrderId} was already submitted"));
            }
            if (!OrderTracker.TryGetOrder(pendingorder.OrderId, out pendingorder))
            {
                _log.Error($"Unable to retrieve newly added order, order with id {pendingorder.OrderId} was cannot be processed properly");
                return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.UnableToFindOrder, $"Current order with id {pendingorder.OrderId} cannot be found"));
            }

            //Round of prices
            RoundOrderPrices(order);

            //Set our new order
            pendingorder.UpdateOrder(order);

            //Check for correct size
            if (order.Quantity == 0)
            {
                order.State = OrderState.Invalid;
                var ticketresponse = OrderTicketResponse.Error(order.InternalId, OrderTicketResponseErrorCode.OrderQuantityZero);
                Portfolio.Log(LogLevel.Error, ticketresponse.ErrorMessage);
                return(ticketresponse);
            }

            //Check if we have enough capital for an order
            bool sufficientcapital = GetSufficientCapitalForOrder(pendingorder);

            if (!sufficientcapital)
            {
                //Not enough capital to execute this order
                order.State = OrderState.Invalid;
                var response = OrderTicketResponse.Error(order.InternalId,
                                                         OrderTicketResponseErrorCode.InsufficientBuyingPower, $"Cannot execute order with id {order.InternalId}, insufficient funds to execute order.");
                Portfolio.Log(LogLevel.Error, response.ErrorMessage);
                HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, $"Insufficent capital to execute order"));
                return(response);
            }

            //Check if broker accepts order at this moment
            try
            {
                if (!Portfolio.BrokerModel.CanSubmitOrder(order, out var message))
                {
                    //Broker model did not accept this order
                    order.State = OrderState.Invalid;
                    var response = OrderTicketResponse.Error(order.InternalId,
                                                             OrderTicketResponseErrorCode.BrokerageModelRefusedToSubmitOrder, $"Order with id {order.InternalId}: {message}");
                    Portfolio.Log(LogLevel.Error, "");
                    HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, $"Broker model of type {Portfolio.BrokerModel.BrokerType} declared order cannot be submitted, message: {message}"));
                    return(response);
                }
            }
            catch (Exception exc)
            {
                _log.Error(exc, $"Could not run CanSubmitOrder on order with id {order.InternalId}, please check the implemented logic");
                order.State = OrderState.Invalid;
                return(OrderTicketResponse.Error(pendingorder.OrderId, OrderTicketResponseErrorCode.ProcessingError, $"Current order with id {pendingorder.OrderId} cannot be processed due to error"));
            }

            //Try to execute this order to the broker connection attached
            bool ordersuccess = false;

            try
            {
                ordersuccess = BrokerConnection.SubmitOrder(pendingorder);
            }
            catch (Exception exc)
            {
                _log.Error(exc);
            }

            //Check if placing the order was a success
            if (!ordersuccess)
            {
                order.State = OrderState.Invalid;
                var submitmessage = "BrokerConnection failed to place order";
                var response      = OrderTicketResponse.Error(order.InternalId,
                                                              OrderTicketResponseErrorCode.BrokerageFailedToSubmitOrder, submitmessage);
                Portfolio.Log(LogLevel.Error, submitmessage);
                HandleOrderTicketEvent(OrderTicketEvent.Error(order.InternalId, submitmessage));
                return(response);
            }

            order.State = OrderState.Submitted;
            return(OrderTicketResponse.Processed(order.InternalId));
        }
Exemplo n.º 11
0
        public void CheckPendingOrder(PendingOrder order, Dictionary <string, QuoteData> curPrices)
        {
            // проверка на зафлаживание
            if (pendingFloodTimes.ContainsKey(order.ID))
            {
                var time = pendingFloodTimes[order.ID];
                if (DateTime.Now < time)
                {
                    return;
                }
                pendingFloodTimes.Remove(order.ID);
            }
            // отменить устаревший ордер)
            if (order.TimeTo.HasValue)
            {
                if (DateTime.Now > order.TimeTo)
                {
                    //var pairCancel = curPrices.ContainsKey(order.Symbol) ? curPrices[order.Symbol] : null;
                    //var priceCancel = pairCancel == null ? 0 : order.Side > 0 ? pairCancel.Bid : pairCancel.Ask;
                    proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                                                             order, PendingOrderStatus.Отменен, null, "Экспирация");
                    return;
                }
            }
            // получить текущую котировку
            if (!curPrices.ContainsKey(order.Symbol))
            {
                if ((DateTime.Now - timeStarted).TotalMilliseconds > MinMillsToReportError)
                {
                    floodSafeLogger.LogMessageFormatCheckFlood(LogEntryType.Debug, MsgNoQuoteMagic, 5 * 60 * 1000,
                                                               "CheckOrder: нет котировки по {0} для отлож. ордера #{1}",
                                                               order.Symbol, order.ID);
                }
                return;
            }
            var pricePair = curPrices[order.Symbol];
            var price     = order.Side > 0 ? pricePair.ask : pricePair.bid;

            // проверить нахождение в рамках цены и времени
            if (order.TimeFrom.HasValue)
            {
                if (DateTime.Now < order.TimeFrom)
                {
                    return;
                }
            }
            // цена...
            var orderFires = false;

            if (order.Side > 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Limit)
            {
                if (price <= order.PriceFrom && (order.PriceTo == null ? true : price >= order.PriceTo))
                {
                    orderFires = true;
                }
            }
            else
            if (order.Side < 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Limit)
            {
                if (price >= order.PriceFrom && (order.PriceTo == null ? true : price <= order.PriceTo))
                {
                    orderFires = true;
                }
            }
            else
            if (order.Side > 0 && ((PendingOrderPriceSide)order.PriceSide) == PendingOrderPriceSide.Stop)
            {
                if (price >= order.PriceFrom && (order.PriceTo == null ? true : price <= order.PriceTo))
                {
                    orderFires = true;
                }
            }
            else
            {
                if (price <= order.PriceFrom && (order.PriceTo == null ? true : price >= order.PriceTo))
                {
                    orderFires = true;
                }
            }
            if (!orderFires)
            {
                return;
            }
            Logger.InfoFormat("Активация отлож. ордера #{0} ({1} {2} at {3}), цена {4}",
                              order.ID, (DealType)order.Side, order.PriceSide,
                              order.PriceFrom.ToStringUniformPriceFormat(true),
                              price.ToStringUniformPriceFormat(true));

            // активировать ордер
            var orderMarket = new MarketOrder
            {
                AccountID  = order.AccountID,
                Magic      = order.Magic,
                Symbol     = order.Symbol,
                Volume     = order.Volume,
                Side       = order.Side,
                StopLoss   = order.StopLoss,
                TakeProfit = order.TakeProfit,
                Comment    = string.Format("по ордеру #{0}", order.ID)
            };

            var reqStatus = proxyTrade.SendNewOrderRequest(
                ProtectedOperationContext.MakeServerSideContext(),
                RequestUniqueId.Next(),
                orderMarket,
                OrderType.Market,
                0, 0);     // проскальзывание

            if (reqStatus == RequestStatus.OK)
            {
                // удалить парный ордер
                if (order.PairOCO.HasValue && order.PairOCO > 0)
                {
                    List <PendingOrder> orders;
                    try
                    {
                        proxyAccount.GetPendingOrders(order.AccountID, out orders);
                        var orderPair = orders == null ? null : orders.FirstOrDefault(o => o.ID == order.PairOCO.Value);
                        if (orderPair != null)
                        {
                            proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                                                                     orderPair, PendingOrderStatus.Отменен, null, "OCO");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorFormat("Ошибка удаления парного ордера {0} для ордера {1}: {2}",
                                           order.PairOCO, order, ex);
                    }
                }

                // удалить ордер
                proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                                                         order, PendingOrderStatus.Исполнен, null, "Активирован");
            }
            else
            {
                Logger.ErrorFormat("Ошибка активации отлож. ордера #{0}: {1}", order.ID, reqStatus);
                // удалить ордер
                proxyTrade.SendDeletePendingOrderRequest(ProtectedOperationContext.MakeServerSideContext(),
                                                         order, PendingOrderStatus.Отменен, null, "Отменен");

                // зафлаживание
                var nextTime = DateTime.Now.AddMilliseconds(PendingFloodTimeoutMils);
                if (pendingFloodTimes.ContainsKey(order.ID))
                {
                    pendingFloodTimes[order.ID] = nextTime;
                }
                else
                {
                    pendingFloodTimes.Add(order.ID, nextTime);
                }
            }
        }
Exemplo n.º 12
0
        private void MakePending(int side)
        {
            var priceVal = tbPrice.Text.Replace(",", ".").ToFloatUniformSafe();

            if (!priceVal.HasValue)
            {
                MessageBox.Show(Localizer.GetString("MessagePriceNotProvided"));
                tbPrice.Focus();
                return;
            }
            var price = priceVal.Value;

            if (price <= 0)
            {
                MessageBox.Show(Localizer.GetString("MessagePriceMustBePositive"));
                tbPrice.Text = "";
                tbPrice.Focus();
                return;
            }

            if (lastQuote == null)
            {
                MessageBox.Show(Localizer.GetString("MessageNoQuote"));
                return;
            }

            // создать новый отложенный ордер
            var volm      = cbVolume.Text.Replace(" ", "").ToInt();
            var orderType = PendingOrderType.Limit;

            if ((side == 1 && lastQuote.ask < price) || (side == -1 && lastQuote.bid > price))
            {
                orderType = PendingOrderType.Stop;
            }
            var orderOCO   = (PendingOrder)cbOrderOCO.SelectedItem;
            var orderOCOId = orderOCO == null ? (int?)null : orderOCO.ID;

            float?[] trailingLevels;
            float?[] trailTargets;
            GetTrailingLevels(side, out trailingLevels, out trailTargets);

            var order = new PendingOrder
            {
                AccountID     = AccountStatus.Instance.accountID,
                Symbol        = Ticker,
                Magic         = tbMagic.Text.ToIntSafe(),
                Volume        = volm,
                Side          = side,
                PriceSide     = orderType,
                PriceFrom     = price,
                PriceTo       = tbPriceTo.Text.Replace(",", ".").ToFloatUniformSafe(),
                TimeFrom      = cbStartFrom.Checked ? dpTimeFrom.Value : (DateTime?)null,
                TimeTo        = cbEndTime.Checked ? dpTimeTo.Value : (DateTime?)null,
                StopLoss      = tbSL.Text.Replace(",", ".").ToFloatUniformSafe(),
                TakeProfit    = tbTP.Text.Replace(",", ".").ToFloatUniformSafe(),
                PairOCO       = orderOCOId > 0 ? orderOCO.ID : (int?)null,
                Comment       = tbComment.Text,
                ExpertComment = tbExpertComment.Text,
                // трейлинг
                TrailLevel1  = trailingLevels[0],
                TrailLevel2  = trailingLevels[1],
                TrailLevel3  = trailingLevels[2],
                TrailLevel4  = trailingLevels[3],
                TrailTarget1 = trailTargets[0],
                TrailTarget2 = trailTargets[1],
                TrailTarget3 = trailTargets[2],
                TrailTarget4 = trailTargets[3],
            };

            MainForm.Instance.SendNewPendingOrderRequestSafe(RequestUniqueId.Next(), order);
        }
Exemplo n.º 13
0
 public override RequestStatus SendEditPendingRequest(ProtectedOperationContext secCtx, PendingOrder ord)
 {
     foreach (var order in orders.Where(order => order.ID == ord.ID && AccountInfo.ID == order.AccountID))
     {
         order.Magic         = ord.Magic;
         order.PriceFrom     = ord.PriceFrom;
         order.PriceTo       = ord.PriceTo;
         order.TimeFrom      = ord.TimeFrom;
         order.TimeTo        = ord.TimeTo;
         order.Comment       = ord.Comment;
         order.ExpertComment = ord.ExpertComment;
         order.StopLoss      = ord.StopLoss;
         order.TakeProfit    = ord.TakeProfit;
         order.Volume        = ord.Volume;
         order.PriceSide     = ord.PriceSide;
         order.Side          = ord.Side;
         order.Symbol        = ord.Symbol;
         return(RequestStatus.OK);
     }
     return(RequestStatus.NotFound);
 }
Exemplo n.º 14
0
 public override RequestStatus SendDeletePendingOrderRequest(ProtectedOperationContext ctx, PendingOrder order,
                                                             PendingOrderStatus status, int?positionId, string closeReason)
 {
     order.Status      = status;
     order.CloseReason = closeReason;
     ordHistory.Add(order);
     orders.Remove(order);
     return(RequestStatus.OK);
 }
Exemplo n.º 15
0
 public override RequestStatus SendNewPendingOrderRequest(
     ProtectedOperationContext ctx, int requestUniqueId, PendingOrder order)
 {
     orders.Add(order);
     return(RequestStatus.OK);
 }
Exemplo n.º 16
0
        private void LoadPendingOrderData()
        {
            RequestStatus       status;
            List <PendingOrder> actualPos;

            try
            {
                status = TradeSharpAccount.Instance.proxy.GetPendingOrders(AccountStatus.Instance.accountID, out actualPos);
            }
            catch (Exception ex)
            {
                Logger.Error("OrderDlg::GetPendingOrders proxy error", ex);
                return;
            }
            if (status != RequestStatus.OK)
            {
                return;
            }
            var pos = actualPos.FirstOrDefault(p => p.ID == orderId);

            if (pos == null)
            {
                Logger.ErrorFormat("OrderDlg::GetPendingOrders - not found ({0})", orderId);
                return;
            }
            pendingOrder = pos;

            Ticker               = pos.Symbol;
            orderSide            = pos.Side;
            cbVolume.Text        = pos.Volume.ToStringUniformMoneyFormat();
            tbSL.Text            = pos.StopLoss.ToStringUniformPriceFormat("", true);
            tbTP.Text            = pos.TakeProfit.ToStringUniformPriceFormat("", true);
            tbComment.Text       = pos.Comment;
            tbExpertComment.Text = pos.ExpertComment;
            Text = string.Format("Отл. ордер №{0} {1} {2} price={3}",
                                 pos.ID, pos.Side > 0 ? "BUY" : "SELL", pos.Symbol, pos.PriceFrom);
            cbCurx.SelectedIndex = cbCurx.Items.IndexOf(pos.Symbol);
            tbMagic.Text         = pos.Magic.HasValue ? pos.Magic.Value.ToString() : "";
            tbPrice.Text         = pos.PriceFrom.ToStringUniformPriceFormat(true);

            // трейлинг
            LoadTrailingLevels(pos.trailingLevels, pos.trailingTargets);

            // доп параметры
            if (pos.TimeFrom.HasValue)
            {
                cbStartFrom.Checked = true;
                dpTimeFrom.Value    = pos.TimeFrom.Value;
            }
            else
            {
                cbStartFrom.Checked = false;
            }
            if (pos.TimeTo.HasValue)
            {
                cbEndTime.Checked = true;
                dpTimeTo.Value    = pos.TimeTo.Value;
            }
            else
            {
                cbEndTime.Checked = false;
            }
            if (pos.PriceTo.HasValue)
            {
                cbPriceTo.Checked = true;
                tbPriceTo.Text    = pos.PriceTo.Value.ToStringUniformPriceFormat(true);
            }

            // стоп-лимит
            var orderCaption = string.Format("{0} {1}",
                                             pos.Side > 0 ? "BUY" : "SELL",
                                             pos.PriceSide == PendingOrderType.Stop ? "STOP" : "LIMIT");

            // кнопки
            var inactBtn = pos.Side > 0 ? btnSellMarket : btnBuyMarket;

            btnBuyMarket.Enabled  = false;
            btnSellMarket.Enabled = false;
            inactBtn.Enabled      = true;
            if (pos.Side > 0)
            {
                btnBuyMarket.buttonCaption = orderCaption;
            }
            else
            {
                btnSellMarket.buttonCaption = orderCaption;
            }
            inactBtn.textLeftColor  = SystemColors.InactiveCaptionText;
            inactBtn.textRightColor = SystemColors.InactiveCaptionText;
            inactBtn.captionColor   = SystemColors.ControlText;
            inactBtn.buttonCaption  = "Отменить";
        }
Exemplo n.º 17
0
        /// <summary>
        /// Submit an order that is going through the regular template cycle of orders
        /// </summary>
        /// <param name="pendingorder"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        protected bool ProcessOrder(PendingOrder pendingorder, AgentState state)
        {
            //Track Orders
            PendingOrder entryOrder = pendingorder;
            PendingOrder rmOrder    = null;

            //Check if we are allowed to trade
            var types = Templates.Select(x => x.GetType());
            RiskManagementTemplate rm = (RiskManagementTemplate)Templates.FirstOrDefault(x => x.GetType().BaseType == typeof(RiskManagementTemplate));

            if (rm != null &&
                !rm.IsTradingAllowed() &&
                (state != AgentState.EntryLong || state != AgentState.EntryShort))
            {
                return(false);
            }

            //Check risk management
            if (InvokeRm.Count > 0)
            {
                //Check all Risk Management template logics
                Exec.InvokeAll(InvokeRm, pendingorder, state);

                //On Order Event
                if (InvokeRm[0].Result != null)
                {
                    rmOrder = InvokeRm[0].Result;
                    RiskManagement(rmOrder);
                }
            }

            //Submit our new stop order
            if (rmOrder != null && rmOrder.Order.IsValid)
            {
                SubmitOrder(rmOrder);
            }
            else if (rmOrder != null && !rmOrder.Order.IsValid)
            {
                _logger.Warn("RM: INVALID ORDER {0} - {1}", rmOrder.OrderStatus, rmOrder.Order.Security.Name);
            }

            //Check money management
            if (InvokeMm.Count > 0)
            {
                Exec.InvokeAll(InvokeMm, pendingorder, state);

                MoneyManagement(pendingorder);
            }

            //Submit our new entry order
            if (entryOrder.Order.IsValid)
            {
                SubmitOrder(entryOrder);
            }
            else
            {
                _logger.Warn("MM: INVALID ORDER {0} - {1}", entryOrder.OrderStatus, entryOrder.Order.Security.Name);
            }

            return(true);
        }
Exemplo n.º 18
0
 internal void WhenOrderFilled(Position robotPosition)
 {
     RobotPosition     = robotPosition;
     RobotPendingOrder = null;
     Status            = TradeStatus.Active;
 }
Exemplo n.º 19
0
 public StatusType SubmitOrder(PendingOrder pendingorder)
 {
     return(Agent.SubmitOrder(pendingorder));
 }
Exemplo n.º 20
0
 /// <summary>
 /// Returns the applied commissions and fees for processing this pending order
 /// </summary>
 /// <param name="pendingorder"></param>
 /// <returns></returns>
 public decimal GetCommissionAndFees(PendingOrder pendingorder) => pendingorder.Value * 0.0025m;
Exemplo n.º 21
0
 public void QueueOrder(PendingOrder order)
 {
     _pendingOrders.Add(order);
     _queuedOrders.Add(order);
 }
Exemplo n.º 22
0
 /// <summary>
 /// Вызывается на торговых событиях установка снятие ордера, изменение параметров, срабатывание ордера
 /// </summary>
 /// <param name="order"></param>
 public override void OnTradeEvent(PendingOrder order)
 {
 }
Exemplo n.º 23
0
        public void AddOrder(PendingOrder order)
        {
            var queue = GetRuleBasedQueue(order.OrderRuleType);

            queue.Add(order);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Fill order, if possible
 /// </summary>
 /// <param name="broker">Associated broker model</param>
 /// <param name="datapoint">Currently received data point</param>
 /// <param name="pendingorder">Pending order to check for filling</param>
 /// <param name="highliquidfill">If true, size of ticks are not taken in to account</param>
 /// <returns></returns>
 /// <exception cref="NotImplementedException"></exception>
 public override Fill FillOrder(BrokerModel broker, DataPoint datapoint, PendingOrder pendingorder, bool highliquidfill)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 25
0
 /// <summary>
 /// Riskmanagement adjustments
 /// </summary>
 /// <param name="order"></param>
 public override void RiskManagement(PendingOrder order)
 {
 }
Exemplo n.º 26
0
 public static OrderImpactResponse GetMarketOrderImpact(PendingOrder curPendingOrder)
 {
     return(GetMarketOrderImpact(curPendingOrder.AccountNumber, curPendingOrder.Quote.symbolId, curPendingOrder.IsBuyOrder, curPendingOrder.Quantity));
 }
        public static bool PlaceOrder(this IStrategyBase Strategy, StringBuilder sb, TradeType?direction,
                                      double price, double?tp, double?sl, long size, string comment, out PendingOrder po)
        {
            double marketPrice = Strategy.Symbol.Bid;

            if (price > marketPrice && direction == TradeType.Sell)
            {
                return(CreateLimitOrder(Strategy, sb, direction, price, size, sl, tp, comment, out po));
            }
            else if (price > marketPrice && direction == TradeType.Buy)
            {
                return(CreateStopOrder(Strategy, sb, direction, price, size, sl, tp, comment, out po));
            }
            else if (price < marketPrice && direction == TradeType.Sell)
            {
                return(CreateStopOrder(Strategy, sb, direction, price, size, sl, tp, comment, out po));
            }
            else if (price < marketPrice && direction == TradeType.Buy)
            {
                return(CreateLimitOrder(Strategy, sb, direction, price, size, sl, tp, comment, out po));
            }
            po = null;
            return(false);
        }
Exemplo n.º 28
0
 public static bool CreateMarketOrder(PendingOrder curPendingOrder)
 {
     return(CreateMarketOrder(curPendingOrder.AccountNumber, curPendingOrder.Quote.symbol, curPendingOrder.Quote.symbolId, curPendingOrder.IsBuyOrder, curPendingOrder.Quantity));
 }
Exemplo n.º 29
0
 /// <summary>
 /// Delete pending order request
 /// </summary>
 /// <param name="order"></param>
 /// <returns></returns>
 protected RequestStatus DeletePendingOrder(PendingOrder order)
 {
     return(robotContext.SendDeletePendingOrderRequest(protectedContext.MakeProtectedContext(), order,
                                                       PendingOrderStatus.Отменен, null, "Отменен роботом"));
 }
Exemplo n.º 30
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (this.itemView.DataSource != null)
                {
                    this.itemView.DataSource = null;
                }
                else
                {
                    this.itemView.Rows.Clear();
                }

                if (this.dataGridPO.DataSource != null)
                {
                    this.dataGridPO.DataSource = null;
                }
                else
                {
                    this.dataGridPO.Rows.Clear();
                }

                if (this.dataGridO.DataSource != null)
                {
                    this.dataGridO.DataSource = null;
                }
                else
                {
                    this.dataGridO.Rows.Clear();
                }

                if (this.cart.DataSource != null)
                {
                    this.cart.DataSource = null;
                }
                else
                {
                    this.cart.Rows.Clear();
                }

                error         = "";
                orders        = new List <Item>();
                tempItems     = new List <Item>();
                TotalNewOrder = 0;
                newTotal.Text = TotalNewOrder.ToString();

                Items = new List <Item>();

                string line;
                using (System.IO.StreamReader reader = new System.IO.StreamReader(@"Items.csv"))
                {
                    reader.ReadLine();
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] part         = line.Split(',');
                        int      ID           = int.Parse(part[0]);
                        string   Title        = part[1];
                        string   Origin       = part[2];
                        double   Quantity     = double.Parse(part[3]);
                        double   Price        = System.Math.Round(double.Parse(part[4]), 2);
                        double   SellingPrice = System.Math.Round(double.Parse(part[5]), 2);
                        string   Status       = part[6];
                        DateTime Date         = DateTime.Parse(part[7]);
                        string   Details      = part[8];
                        Item     temp         = new Item(ID, Title, Origin, Quantity, Price, SellingPrice, Status, Date, Details);
                        Items.Add(temp);
                    }
                    AddItems(Items);
                }

                OrdersPending = new List <PendingOrder>();
                using (StreamReader reader = new StreamReader(@"PendingOrders.csv"))
                {
                    reader.ReadLine();
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[]     part     = line.Split(',');
                        int          ID       = int.Parse(part[0]);
                        DateTime     Date     = DateTime.Parse(part[1]);
                        string       Title    = part[2];
                        string       Address  = part[3];
                        string       ItemID   = part[4];
                        string       Quantity = part[5];
                        double       Payment  = double.Parse(part[6]);
                        string       Status   = part[7];
                        string       Details  = part[8];
                        PendingOrder temp     = new PendingOrder(ID, Date, Title, Address, ItemID, Quantity, Payment, Status, Details);
                        OrdersPending.Add(temp);
                    }

                    AddPendingOrders(OrdersPending);
                }

                Orders = new List <Order>();
                double total = 0;
                using (StreamReader reader = new StreamReader(@"Orders.csv"))
                {
                    reader.ReadLine();
                    while ((line = reader.ReadLine()) != null)
                    {
                        string[] part     = line.Split(',');
                        int      ID       = int.Parse(part[0]);
                        DateTime Date     = DateTime.Parse(part[1]);
                        string   ItemID   = part[2];
                        string   Quantity = part[3];
                        double   Payment  = double.Parse(part[4]);
                        total += Payment;
                        string Details = part[5];
                        Order  temp    = new Order(ID, Date, ItemID, Quantity, Payment, Details);
                        Orders.Add(temp);
                    }

                    AddOrders(Orders);
                    totalReceivedPayment.Text = total.ToString();
                }
            }
            catch (Exception exc)
            {
                error                = exc.Message;
                errorMessage.Text   += "Failed to load data. Fatal error. " + error;
                errorMessage.Visible = true;
                tabControl.Visible   = false;
            }
        }
 protected override void OnPendingOrderCreated(PendingOrder newOrder)
 {
     if (newOrder.TradeType == TradeType.Buy)
         _buyOrder = newOrder;
     else
         _sellOrder = newOrder;
 }
        /// <summary>
        /// Begin order for new certificate for one or more domains, fetching the required challenges
        /// to complete
        /// </summary>
        /// <param name="log">  </param>
        /// <param name="config">  </param>
        /// <param name="orderUri"> Uri of existing order to resume </param>
        /// <returns>  </returns>
        public async Task <PendingOrder> BeginCertificateOrder(ILog log, CertRequestConfig config, string orderUri = null)
        {
            if (DateTime.Now.Subtract(_lastInitDateTime).TotalMinutes > 30)
            {
                // our acme context nonce may have expired (which returns "JWS has an invalid
                // anti-replay nonce") so start a new one
                await InitProvider(null);
            }

            var pendingOrder = new PendingOrder {
                IsPendingAuthorizations = true
            };

            // prepare a list of all pending authorization we need to complete, or those we have
            // already satisfied
            var authzList = new List <PendingAuthorization>();

            //if no alternative domain specified, use the primary domain as the subject
            var domainOrders = new List <string>();

            // order all of the distinct domains in the config (primary + SAN).
            domainOrders.Add(_idnMapping.GetAscii(config.PrimaryDomain));

            if (config.SubjectAlternativeNames != null)
            {
                foreach (var s in config.SubjectAlternativeNames)
                {
                    if (!domainOrders.Contains(s))
                    {
                        domainOrders.Add(_idnMapping.GetAscii(s));
                    }
                }
            }

            try
            {
                IOrderContext order             = null;
                int           remainingAttempts = 3;
                bool          orderCreated      = false;
                try
                {
                    while (!orderCreated && remainingAttempts > 0)
                    {
                        try
                        {
                            remainingAttempts--;

                            log.Error($"BeginCertificateOrder: creating/retrieving order. Retries remaining:{remainingAttempts} ");

                            if (orderUri != null)
                            {
                                order = _acme.Order(new Uri(orderUri));
                            }
                            else
                            {
                                order = await _acme.NewOrder(domainOrders);
                            }

                            if (order != null)
                            {
                                orderCreated = true;
                            }
                        }
                        catch (Exception exp)
                        {
                            remainingAttempts--;

                            log.Error($"BeginCertificateOrder: error creating order. Retries remaining:{remainingAttempts} {exp.ToString()} ");

                            if (remainingAttempts == 0)
                            {
                                // all attempts to create order failed
                                throw;
                            }
                            else
                            {
                                await Task.Delay(1000);
                            }
                        }
                    }
                }
                catch (NullReferenceException exp)
                {
                    var msg = $"Failed to begin certificate order (account problem or API is not currently available): {exp}";

                    log.Error(msg);

                    pendingOrder.Authorizations =
                        new List <PendingAuthorization> {
                        new PendingAuthorization
                        {
                            AuthorizationError = msg,
                            IsFailure          = true
                        }
                    };

                    return(pendingOrder);
                }

                if (order == null)
                {
                    throw new Exception("Failed to begin certificate order.");
                }

                orderUri = order.Location.ToString();

                pendingOrder.OrderUri = orderUri;

                log.Information($"Created ACME Order: {orderUri}");

                // track order in memory, keyed on order Uri
                if (_currentOrders.Keys.Contains(orderUri))
                {
                    _currentOrders.Remove(orderUri);
                }

                _currentOrders.Add(orderUri, order);

                // handle order status 'Ready' if all authorizations are already valid
                var orderDetails = await order.Resource();

                if (orderDetails.Status == OrderStatus.Ready)
                {
                    pendingOrder.IsPendingAuthorizations = false;
                }

                // get all required pending (or already valid) authorizations for this order

                log.Information($"Fetching Authorizations.");

                var orderAuthorizations = await order.Authorizations();

                // get the challenges for each authorization
                foreach (IAuthorizationContext authz in orderAuthorizations)
                {
                    log.Debug($"Fetching Authz Challenges.");

                    var allChallenges = await authz.Challenges();

                    var res = await authz.Resource();

                    string authzDomain = res.Identifier.Value;
                    if (res.Wildcard == true)
                    {
                        authzDomain = "*." + authzDomain;
                    }

                    var challenges = new List <AuthorizationChallengeItem>();

                    // add http challenge (if any)
                    var httpChallenge = await authz.Http();

                    if (httpChallenge != null)
                    {
                        var httpChallengeStatus = await httpChallenge.Resource();

                        log.Information($"Got http-01 challenge {httpChallengeStatus.Url}");

                        if (httpChallengeStatus.Status == ChallengeStatus.Invalid)
                        {
                            log.Error($"HTTP challenge has an invalid status");
                        }

                        challenges.Add(new AuthorizationChallengeItem
                        {
                            ChallengeType = SupportedChallengeTypes.CHALLENGE_TYPE_HTTP,
                            Key           = httpChallenge.Token,
                            Value         = httpChallenge.KeyAuthz,
                            ChallengeData = httpChallenge,
                            ResourceUri   = $"http://{authzDomain.Replace("*.", "")}/.well-known/acme-challenge/{httpChallenge.Token}",
                            ResourcePath  = $".well-known\\acme-challenge\\{httpChallenge.Token}",
                            IsValidated   = (httpChallengeStatus.Status == ChallengeStatus.Valid)
                        });
                    }

                    // add dns challenge (if any)
                    var dnsChallenge = await authz.Dns();

                    if (dnsChallenge != null)
                    {
                        var dnsChallengeStatus = await dnsChallenge.Resource();

                        log.Information($"Got dns-01 challenge {dnsChallengeStatus.Url}");

                        if (dnsChallengeStatus.Status == ChallengeStatus.Invalid)
                        {
                            log.Error($"DNS challenge has an invalid status");
                        }

                        var dnsValue = _acme.AccountKey.DnsTxt(dnsChallenge.Token); //ComputeDnsValue(dnsChallenge, _acme.AccountKey);
                        var dnsKey   = $"_acme-challenge.{authzDomain}".Replace("*.", "");

                        challenges.Add(new AuthorizationChallengeItem
                        {
                            ChallengeType = SupportedChallengeTypes.CHALLENGE_TYPE_DNS,
                            Key           = dnsKey,
                            Value         = dnsValue,
                            ChallengeData = dnsChallenge,
                            IsValidated   = (dnsChallengeStatus.Status == ChallengeStatus.Valid)
                        });
                    }

                    // report back on the challenges we now may need to attempt
                    authzList.Add(
                        new PendingAuthorization
                    {
                        Challenges = challenges,
                        Identifier = new IdentifierItem
                        {
                            Dns = authzDomain,
                            IsAuthorizationPending = !challenges.Any(c => c.IsValidated)  //auth is pending if we have no challenges already validated
                        },
                        AuthorizationContext = authz,
                        IsValidated          = challenges.Any(c => c.IsValidated),
                        OrderUri             = orderUri
                    });
                }

                pendingOrder.Authorizations = authzList;

                return(pendingOrder);
            }
            catch (AcmeRequestException exp)
            {
                // failed to register one or more domain identifier with LE (invalid, rate limit or
                // CAA fail?)

                var msg = $"Failed to begin certificate order: {exp.Error?.Detail}";

                log.Error(msg);

                pendingOrder.Authorizations =
                    new List <PendingAuthorization> {
                    new PendingAuthorization
                    {
                        AuthorizationError = msg,
                        IsFailure          = true
                    }
                };

                return(pendingOrder);
            }
        }
Exemplo n.º 33
0
 private void SimBroker_GotFill(Trade t, PendingOrder o)
 {
     fillcount++;
 }
Exemplo n.º 34
0
 protected override void OnPendingOrderCreated(PendingOrder newOrder)
 {
 }