public Message CreateFillReport(OrderMatch match, string execID)
        {
            var symbol = new Symbol(match.Contract.Symbol);
            var exReport = new ExecutionReport(
                new OrderID(match.OrderID.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execID),
                new ExecType(match.MatchType == MatchType.Full
                                 ? ExecType.FILL
                                 : ExecType.PARTIAL_FILL),
                new OrdStatus(match.MatchType == MatchType.Full
                                  ? OrdStatus.FILLED
                                  : OrdStatus.PARTIALLY_FILLED),
                symbol,
                TranslateFixFields.Translate(match.MarketSide),
                new LeavesQty(match.RemainingQuantity),
                new CumQty(match.OriginalOrderQuantity - match.RemainingQuantity),
                new AvgPx(match.Price))
            {
                ClOrdID = new ClOrdID(match.ClOrdID),
                Symbol = symbol,
                OrderQty = new OrderQty(match.OriginalOrderQuantity),
                LastQty = new LastQty(match.MatchedQuantity),
                LastPx = new LastPx(match.Price)
            };

            if (TradingAccount.IsSet(match.Account))
                exReport.SetField(new Account(match.Account.Name));

            return exReport;
        }
        public Message CreateNewOrderExecutionReport(IOrder o, string execID)
        {
            var symbol = new Symbol(o.Contract.Symbol);
            var exReport = new ExecutionReport(
                new OrderID(o.ID.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execID),
                new ExecType(ExecType.NEW),
                new OrdStatus(OrdStatus.NEW),
                symbol,
                TranslateFixFields.Translate(o.MarketSide),
                new LeavesQty(o.Quantity),
                new CumQty(0m),
                new AvgPx(o.Price))
                {
                    ClOrdID = new ClOrdID(o.ClOrdID),
                    Symbol = symbol,
                    OrderQty = new OrderQty(o.Quantity),
                    LastQty = new LastQty(0m)
                };

            //exReport.Set(new LastPx(o.Price));

            if (TradingAccount.IsSet(o.Account))
                exReport.SetField(new Account(o.Account.Name));

            return exReport;
        }
Example #3
0
        public static ExecutionReport CreateRejectNewOrderExecutionReport(
            NewOrderSingle n,
            string execID,
            string rejectionReason,
            int? rejectionCode = null)
        {
            var exReport = new ExecutionReport(
                new OrderID("unknown orderID"),
                new ExecID(execID),
                new ExecTransType(ExecTransType.NEW),
                new ExecType(ExecType.REJECTED),
                new OrdStatus(OrdStatus.REJECTED),
                n.Symbol,
                n.Side,
                new LeavesQty(0m),
                new CumQty(0m),
                new AvgPx(0m));

            if (rejectionCode.HasValue)
            {
                exReport.OrdRejReason = new OrdRejReason(rejectionCode.Value);
            }

            exReport.Set(n.ClOrdID);
            exReport.Set(n.OrderQty);

            if (n.IsSetAccount())
                exReport.SetField(n.Account);

            return exReport;
        }
Example #4
0
 public Order OnExecutionReport(ExecutionReport report)
 {
     var order = this.orders[report.OrderId];
     if (order == null)
         return null;
     report.Order = order;
     order.OnExecutionReport(report);
     return order;
 }
 internal ExecutionReportViewItem(ExecutionReport report)
 {
     Report = report;
     ImageIndex = 1;
     var priceFormat = report.Instrument.PriceFormat;
     SubItems[0].Text = report.DateTime.ToString();
     SubItems.AddRange(new[]
     {
         string.Empty, report.ExecType.ToString(), report.OrdStatus.ToString(),
         report.Side.ToString(), report.OrdType.ToString(), report.Price.ToString(priceFormat),
         report.StopPx.ToString(priceFormat),
         report.OrdQty.ToString(), report.CumQty.ToString(), report.LeavesQty.ToString(),
         report.LastQty.ToString(), report.LastPx.ToString(priceFormat), report.Text
     });
 }
Example #6
0
        /// <summary>
        /// Converts an FXCM order to a QuantConnect order.
        /// </summary>
        /// <param name="fxcmOrder">The FXCM order</param>
        private Order ConvertOrder(ExecutionReport fxcmOrder)
        {
            Order order;

            if (fxcmOrder.getOrdType() == OrdTypeFactory.LIMIT)
            {
                order = new LimitOrder
                {
                    LimitPrice = Convert.ToDecimal(fxcmOrder.getPrice())
                };
            }

            else if (fxcmOrder.getOrdType() == OrdTypeFactory.MARKET)
            {
                order = new MarketOrder();
            }

            else if (fxcmOrder.getOrdType() == OrdTypeFactory.STOP)
            {
                order = new StopMarketOrder
                {
                    StopPrice = Convert.ToDecimal(fxcmOrder.getPrice())
                };
            }

            else
            {
                throw new NotSupportedException("FxcmBrokerage.ConvertOrder(): The FXCM order type " + fxcmOrder.getOrdType() + " is not supported.");
            }

            var securityType = _symbolMapper.GetBrokerageSecurityType(fxcmOrder.getInstrument().getSymbol());
            order.Symbol = _symbolMapper.GetLeanSymbol(fxcmOrder.getInstrument().getSymbol(), securityType, Market.FXCM);
            order.Quantity = Convert.ToInt32(fxcmOrder.getOrderQty() * (fxcmOrder.getSide() == SideFactory.BUY ? +1 : -1));
            order.Status = ConvertOrderStatus(fxcmOrder.getFXCMOrdStatus());
            order.BrokerId.Add(fxcmOrder.getOrderID());
            order.Duration = ConvertDuration(fxcmOrder.getTimeInForce());
            order.Time = FromJavaDate(fxcmOrder.getTransactTime().toDate());

            return order;
        }
Example #7
0
        public ExecutionReport(ExecutionReport report)
        {
            this.DateTime = report.DateTime;
            this.Instrument = report.Instrument;
            this.Order = report.Order;

            this.CurrencyId = report.CurrencyId;
            this.ExecType = report.ExecType;
            this.OrdType = report.OrdType;
            this.Side = report.Side;
            this.TimeInForce = report.TimeInForce;
            this.OrdStatus = report.OrdStatus;
            this.LastPx = report.LastPx;
            this.AvgPx = report.AvgPx;
            this.OrdQty = report.OrdQty;
            this.CumQty = report.CumQty;
            this.LastQty = report.LastQty;
            this.LeavesQty = report.LeavesQty;
            this.Price = report.Price;
            this.StopPx = report.StopPx;
            this.Commission = report.Commission;
            this.Text = report.Text;
        }
 public virtual void onMessage(ExecutionReport message, QuickFix.SessionID session)
 {
     throw new QuickFix.UnsupportedMessageType();
 }
Example #9
0
 public Task ExternalOrder(ExecutionReport trade)
 {
     return(TryProduceMessageAsync(_settings.RabbitMqQueues.ExternalOrder.ExchangeName, trade));
 }
Example #10
0
 public virtual void onExecutionReport(ExecutionReport report)
 {
     if (SwigDerivedClassHasMethod("onExecutionReport", swigMethodTypes3))
     {
         ContextModulePINVOKE.Application_onExecutionReportSwigExplicitApplication(swigCPtr, ExecutionReport.getCPtr(report));
     }
     else
     {
         ContextModulePINVOKE.Application_onExecutionReport(swigCPtr, ExecutionReport.getCPtr(report));
     }
     if (ContextModulePINVOKE.SWIGPendingException.Pending)
     {
         throw ContextModulePINVOKE.SWIGPendingException.Retrieve();
     }
 }
Example #11
0
        private bool _er_Update(ExecutionReport er, FixOrderStatus ordS, string desc, string bolsa)
        {
            try
            {
                int account;
                if (bolsa.Equals(ExchangePrefixes.BOVESPA, StringComparison.InvariantCultureIgnoreCase))
                {
                    string acc = er.Account.getValue();
                    acc     = (acc.Remove(acc.Length - 1));
                    account = Convert.ToInt32(acc);
                }
                else
                {
                    account = Convert.ToInt32(er.Account.getValue());
                }

                // Buscar Ordem Original, de algum jeito!!!
                // 1a. tentativa: Tentar via ExchangeNumber
                // 2a. tentativa: Tentar via ClOrdID e OrigClOrdID
                // 3a. tentativa: Tentar via ClOrdID no tb_fix_order_update e buscar a ordem pelo OrderID
                // 4a. tentativa: ahhh foda-se, nao achou mesmo

                OrderDbInfo orderOrig = null;

                // 1a. tentativa
                if (er.IsSetOrderID() && !er.OrderID.getValue().Equals("NONE"))
                {
                    orderOrig = _db.BuscarOrdemPorExchangeNumber(er.OrderID.getValue());
                }
                // 2a. Tentativa
                if (null == orderOrig || orderOrig.OrderID == 0)
                {
                    orderOrig = _db.BuscarOrdem(er.ClOrdID.getValue(), account, er.Symbol.getValue());
                    if (orderOrig.OrderID == 0)
                    {
                        // Se ordem nao encontrada, entao procurar pelo OrigClOrdID
                        if (er.IsSetOrigClOrdID())
                        {
                            orderOrig = _db.BuscarOrdem(er.OrigClOrdID.getValue(), account, er.Symbol.getValue());
                            if (orderOrig.OrderID == 0)
                            {
                                orderOrig = _db.BuscarOrdem(er.OrigClOrdID.getValue(), account, er.Symbol.getValue(), true);
                                //if (orderOrig.OrderID == 0)
                                //{
                                //    logger.Info("01 ER - Nao achou a ordem em questao!!!: " + er.OrigClOrdID.getValue() + " Status: " + ordS.ToString() + " Desc: " + desc);
                                //    return false;
                                //}
                            }
                            else
                            {
                                orderOrig = _db.BuscarOrdem(er.OrigClOrdID.getValue(), account, er.Symbol.getValue());
                            }
                        }
                        else
                        {
                            orderOrig = _db.BuscarOrdem(er.ClOrdID.getValue(), account, er.Symbol.getValue(), true);
                            //if (orderOrig.OrderID == 0)
                            //{
                            //    logger.Info("02 ER - Nao achou a ordem em questao!!!: " + er.ClOrdID.getValue() + " Status: " + ordS.ToString() + " Desc: " + desc);
                            //    return false;
                            //}
                        }
                    }
                }

                // 3a. Tentativa
                if (null == orderOrig || orderOrig.OrderID == 0)
                {
                    // Buscar a partir de tb_fix_order_update
                    OrderDbUpdateInfo orderUpdate = _db.BuscarOrdemUpdate(er.ClOrdID.getValue());
                    // Buscar ordem original a partir do order ID
                    if (orderUpdate.OrderID != 0)
                    {
                        orderOrig = _db.BuscarOrdemPorOrderID(orderUpdate.OrderID);
                    }
                    else
                    {
                        logger.Info("01 ER - Nao achou a ordem em questao!!!: " + er.ClOrdID.getValue() + " Status: " + ordS.ToString() + " Desc: " + desc);
                        return(false);
                    }
                }
                if (null == orderOrig || orderOrig.OrderID == 0)
                {
                    logger.Info("02 ER - Nao achou a ordem em questao!!!: " + er.ClOrdID.getValue() + " Status: " + ordS.ToString() + " Desc: " + desc);
                    return(false);
                }
                //}
                //else
                //{
                //    orderOrig = _db.BuscarOrdemPorExchangeNumber(er.OrderID.getValue());
                //    if (orderOrig.OrderID == 0)
                //    {
                //        logger.Info("ER - Nao achou a ordem em questao via exchange number (OrderID ER)!!!: " + er.OrderID.getValue() + " Status: " + ordS.ToString() + " Desc: " + desc);
                //        return false;
                //    }
                // }
                // Adicionar OrdemDetalhe
                OrderDbDetalheInfo detail = new OrderDbDetalheInfo();
                detail.OrderID       = orderOrig.OrderID;
                detail.TransactID    = er.ExecID.getValue();
                detail.OrderQty      = Convert.ToInt32(er.OrderQty.getValue());
                detail.Price         = er.IsSetField(Tags.Price) ? er.Price.getValue() : Decimal.Zero;
                detail.OrderStatusID = (int)ordS;
                detail.TransactTime  = er.TransactTime.getValue();
                if (er.IsSetField(Tags.Text))
                {
                    detail.Description = desc + " - " + er.Text.getValue();
                }
                else
                {
                    detail.Description = desc;
                }

                detail.TradeQty     = er.IsSetField(Tags.LastQty) ? Convert.ToInt32(er.LastQty.getValue()) : 0;
                detail.CumQty       = er.IsSetField(Tags.CumQty) ? Convert.ToInt32(er.CumQty.getValue()) : 0;
                detail.FixMsgSeqNum = Convert.ToInt32(er.Header.GetField(Tags.MsgSeqNum));
                if (!_db.InserirOrdemDetalhe(detail, orderOrig.ClOrdID))
                {
                    logger.Info("Erro ao inserir o registro na tabela tb_fix_order_update");
                    return(false);
                }

                // Atualizar Ordem
                orderOrig.ExchangeNumberID = er.OrderID.getValue();
                orderOrig.OrdStatus        = (int)ordS;
                orderOrig.TransactTime     = er.TransactTime.getValue();
                // orderOrig.ClOrdID = er.ClOrdID.getValue();
                // if (er.IsSetOrigClOrdID())
                //    orderOrig.OrigClOrdID = er.OrigClOrdID.getValue();
                if (er.IsSetField(Tags.LeavesQty))
                {
                    orderOrig.OrderQtyRemaining = Convert.ToInt32(er.LeavesQty.getValue());
                }
                if (er.IsSetField(Tags.CumQty))
                {
                    orderOrig.CumQty = Convert.ToInt32(er.CumQty.getValue());
                }
                orderOrig.Memo = er.IsSetField(Tags.Memo) ? er.GetField(Tags.Memo): string.Empty;
                if (!_db.AtualizarOrdem(orderOrig))
                {
                    logger.Info("Problemas na atualizacao da ordem. ClOrdID: " + orderOrig.ClOrdID);
                    return(false);
                }

                DropCopyCallbackManager.Instance.EnqueueCallback(orderOrig);

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error("_er_Update: Erro na atualizacao dos status da ordem: " + ex.Message, ex);
                return(false);
            }
        }
Example #12
0
        public override void onExecutionReport(ExecutionReport report)
        {
            logInfo("onExecutionReport:-------------------->");
            //		report.dump();
            try{
                logInfo("Status:" + report.getOrderStatus().ToString());
                logInfo("Instrument Name: " + report.getInstrumentName());


                printOrder(
                    Portfolio.getInstance().getOrderBook().getOrder(
                        report.getClOrderId()
                        )
                    );
            }
            catch (Exception e)
            {
                logInfo(e.Message);
            }
            logInfo("Status:" + report.getOrderStatus().ToString());
            logInfo("Instrument Name: " + report.getInstrumentName());


            if (report.getInstrumentName() == (sd.firstLegSymbol))
            {
                logInfo("Here1");
                if (report.getOrderStatus() == (OrderStatus.OrderStatus_CONFIRMED))
                {
                    logInfo("Here2");
                    sd.firstLegOrder.setClOrdId(report.getClOrderId());
                    sd.firstLegOrder.setOrigClOrdId(report.getOriginalClOrderId());
                    sd.firstLegOrder.setOrderStatus(OrderStatus.OrderStatus_CONFIRMED);
                    sd.isOrderPending = false;
                }
                else if (report.getOrderStatus() == (OrderStatus.OrderStatus_REPLACED))
                {
                    sd.firstLegOrder.setClOrdId(report.getClOrderId());
                    sd.firstLegOrder.setOrigClOrdId(report.getOriginalClOrderId());
                    sd.firstLegOrder.setOrderStatus(OrderStatus.OrderStatus_CONFIRMED);
                    sd.isOrderPending = false;
                }
                else if (report.getOrderStatus() == (OrderStatus.OrderStatus_FILLED))
                {
                    try
                    {
                        TradeQue trades
                            = Portfolio.getInstance().getTradeBook().getTradeQue(report.getClOrderId());
                        logInfo("**************** Dumping Trades ***************** .\n");
                        long size = trades.size();
                        logInfo("size = ", size);
                        for (int i = 0; i < size; ++i)
                        {
                            printTrade(trades.getitem(i));
                        }
                    }
                    catch (Exception e)
                    {
                        logInfo(e.Message.ToString());
                    }
                    //				Side side;
                    //				if(report.getOrderMode().)
                    //
                    //
                    placeSecondLegMarket();
                    sd.isOrderPending = true;
                    //				Position pos =Portfolio.getInstance().getNetPositions().getPosition(
                    //						Context.getInstance().getInstrument(report.getInstrumentName()),
                    //						report.getOrderMode());
                    //				printPosition(pos);
                    printPortfolio(report.getInstrumentName(), report.getOrderMode());

                    //				List trades = new ArrayList<Trade>();
                    //				trades =ArrayList<Trade>Portfolio.getInstance().getTradeBook().getTrades(
                    //						report.getClOrderId()
                    //						);
                    //				printTrade((Trade)trades.get(trades.size()-1));
                }
            }
            else if (report.getInstrumentName() == (sd.secondLegSymbol))
            {
                if (report.getOrderStatus() == (OrderStatus.OrderStatus_CONFIRMED))
                {
                    sd.secondLegOrder.setClOrdId(report.getClOrderId());
                    sd.secondLegOrder.setOrigClOrdId(report.getOriginalClOrderId());
                    sd.isOrderPending = false;
                }
                else if (report.getOrderStatus() == (OrderStatus.OrderStatus_FILLED))
                {
                    logInfo("Strategy completed successfully.\n");
                    printPortfolio();
                    logInfo("Calling Logout.\n");
                    Context.getInstance().logout();
                }
            }
        }
Example #13
0
 public virtual void onExecutionReport(ExecutionReport report)
 {
     if (SwigDerivedClassHasMethod("onExecutionReport", swigMethodTypes3)) ContextModulePINVOKE.Application_onExecutionReportSwigExplicitApplication(swigCPtr, ExecutionReport.getCPtr(report)); else ContextModulePINVOKE.Application_onExecutionReport(swigCPtr, ExecutionReport.getCPtr(report));
     if (ContextModulePINVOKE.SWIGPendingException.Pending) throw ContextModulePINVOKE.SWIGPendingException.Retrieve();
 }
Example #14
0
 internal void OnExecutionReport(ExecutionReport report) => OnEvent(report);
Example #15
0
 protected virtual void OnExecutionReport(SingleOrder order, ExecutionReport report)
 {
 }
Example #16
0
 internal void SetExecutionReport(SingleOrder order, ExecutionReport report)
 {
     this.OnExecutionReport(order, report);
 }
        public void EmitExecutionReport(OrderRecord record, SQ.ExecType execType, SQ.OrderStatus orderStatus)
        {
            ExecutionReport report = CreateReport(record, execType, orderStatus);

            provider.EmitExecutionReport(report);
        }
Example #18
0
        public List <ExecutionReport> NewOrder(ExecutionReport order)
        {
            var client = GetProxy(order.Symbol);

            return(client.NewOrder(order));
        }
Example #19
0
        static void Main(string[] args)
        {
            const string          senderCompID = "Acceptor";
            const string          targetCompID = "Initiator";
            const ProtocolVersion version      = ProtocolVersion.FIX44;
            const string          host         = "localhost";
            const int             port         = 4500;

            Engine engine = Engine.Init(port);

            using (Session acceptor = new Session(senderCompID, targetCompID, version))
            {
                FIX42.TypedMessageListener acceptorTypedMessageListener = new FIX42.TypedMessageListener(acceptor);

                acceptorTypedMessageListener.OrderSingleReceived += new Action <OrderSingle>((order) =>
                {
                    Console.WriteLine("Acceptor has received the Order Single message:  ClOrdID=" + order.ClOrdID + "; Msg(" + ((Message)order) + ")\n");
                    Console.WriteLine("NoAllocs group size: " + order.NoAllocs.Count);

                    foreach (FIX42.OrderSingleNoAllocsInstance instance in order.NoAllocs)
                    {
                        Console.WriteLine("AllocAccount=" + instance.AllocAccount + "; AllocShares=" + instance.AllocShares);
                    }

                    ExecutionReport report = new ExecutionReport(order.ClOrdID, "Report1", FIX42.ExecTransType.New, FIX42.ExecType.Fill, FIX42.OrdStatus.Filled, order.Symbol, order.Side, 0, 10000, 100);
                    acceptor.Send(report);
                    Console.WriteLine("\n");
                });

                acceptor.LogonAsAcceptor();

                using (Session initiator = new Session(targetCompID, senderCompID, version))
                {
                    FIX42.TypedMessageListener initiatorTypedMessageListener = new FIX42.TypedMessageListener(initiator);

                    initiatorTypedMessageListener.ExecutionReportReceived += new Action <ExecutionReport>((report) =>
                    {
                        Console.WriteLine("Initiator has received the Execution Report message: OrderID=" + report.OrderID + "; Msg(" + ((Message)report) + ")\n");
                        Console.WriteLine("Press any key to disconnect the session and terminate the application.\n");
                    });

                    initiator.LogonAsInitiator(host, Engine.Instance.Settings.ListenPort);

                    OrderSingle order = new OrderSingle();

                    order.ClOrdID      = "Order1";
                    order.HandlInst    = FIX42.HandlInst.AutomatedExecutionNoIntervention;
                    order.Symbol       = "Ticker symbol";
                    order.Side         = FIX42.Side.Buy;
                    order.TransactTime = DateTime.UtcNow;
                    order.OrdType      = FIX42.OrdType.Market;
                    order.OrderQty     = 10000;

                    FIX42.OrderSingleNoAllocsInstance orderSingleNoAllocsInstance1 = order.NoAllocs.CreateNew();
                    orderSingleNoAllocsInstance1.AllocAccount = "AllocAccount1";
                    orderSingleNoAllocsInstance1.AllocShares  = 10;
                    FIX42.OrderSingleNoAllocsInstance orderSingleNoAllocsInstance2 = order.NoAllocs.CreateNew();
                    orderSingleNoAllocsInstance2.AllocAccount = "AllocAccount2";
                    orderSingleNoAllocsInstance2.AllocShares  = 20;

                    ((Message)order).Validate();

                    Console.WriteLine("Press any key to send an order.\n");
                    Console.ReadKey();

                    initiator.Send(order);

                    Console.WriteLine("The order (" + ((Message)order) + ") was sent by the Initiator\n");

                    Console.ReadKey();

                    initiator.Logout();
                }

                acceptor.Logout();
            }

            engine.Shutdown();
        }
Example #20
0
 public void ProcessExecutionReport(ExecutionReport report)
 {
     GetPosition(report.Instrument).ProcessExecutionReport(report, GetOrderFlags(report.Order));
 }
Example #21
0
 protected override void OnExecutionReport(ExecutionReport report)
 {
     // 用于更新其中的持仓数量等信息
     // 反手等事件的处理
     StrategyHelper.OnExecutionReport(report);
 }
 private void ProcessExecutionReport(ExecutionReport executionReport)
 {
     this.lastUpdatedOrderList.Add((OrderViewItem)this.allOrders[(object)this.orderFactory.OnExecutionReport(executionReport)]);
     if (executionReport.Order != this.reportedOrder)
         return;
     this.ltvReports.Items.Add((ListViewItem)new ExecutionReportViewItem(executionReport));
 }
Example #23
0
 internal void SendExecutionReport(ExecutionReport report)
 {
     this.MetaStrategyBase.SendExecutionReport(this, report);
 }
Example #24
0
 public virtual double GetPrice(ExecutionReport report) => report.LastPx*(1 + Slippage*(report.Side == OrderSide.Buy ? 1 : -1));
Example #25
0
        public List <ExecutionReport> Put(string id, [FromBody] ExecutionReport order)
        {
            var results = _orderbookService.NewOrder(order);

            return(results);
        }
Example #26
0
 protected override void OnExecutionReport(ExecutionReport report)
 {
     Console.WriteLine(report);
 }
Example #27
0
 private void DispatcherExecutionReport(object sender, ExecutionReport report)
 {
     OrderManagerQueue.Enqueue(report);
 }
Example #28
0
        public void ProcessExecutionReport(QuickFix.Message msg, string bolsa)
        {
            try
            {
                ExecutionReport er = (ExecutionReport)msg;

                char execType  = er.ExecType.getValue();
                char ordStatus = er.OrdStatus.getValue();

                switch (execType)
                {
                // Trade Bust Working order / Non-working order (TODO [FF]: Dificil de testar esta situacao)
                case ExecType.TRADE_CANCEL:
                    this._er_Update(er, FixOrderStatus.NEGOCIO_CANCELADO, DescMsg.ER_TRADE_BUST, bolsa);
                    break;

                // Iceberg restatement (TODO [FF]: Dificil de testar esta situacao)
                case ExecType.RESTATED:
                    this._er_Update(er, FixOrderStatus.REAPRESENTADA, DescMsg.ER_ORDER_RESTATED, bolsa);
                    break;
                }

                switch (ordStatus)
                {
                // Order Entry Accepted
                case OrdStatus.NEW:
                    this._er_Update(er, FixOrderStatus.NOVA, DescMsg.ER_NOS_TO_EXCHANGE, bolsa);
                    break;

                // Order Entry rejected
                // Nao necessario estabelecer informacoes da tb_fix_update, pois nao se trata de alteracao / cancelamento
                case OrdStatus.REJECTED:
                    this._er_Update(er, FixOrderStatus.REJEITADA, DescMsg.ER_NOS_REJECTED, bolsa);
                    break;

                // Modification Accepted
                case OrdStatus.REPLACED:
                    this._er_Update(er, FixOrderStatus.SUBSTITUIDA, DescMsg.ER_OCRR_MODIFIED, bolsa);
                    break;

                // Cancelation Accepted
                case OrdStatus.CANCELED:
                    this._er_Update(er, FixOrderStatus.CANCELADA, DescMsg.ER_OCR_CANCELLED, bolsa);
                    break;

                // Full Fill
                case OrdStatus.FILLED:
                    this._er_Update(er, FixOrderStatus.EXECUTADA, DescMsg.ER_ORDER_FILLED, bolsa);
                    break;

                // Partial Fill
                case OrdStatus.PARTIALLY_FILLED:
                    this._er_Update(er, FixOrderStatus.PARCIALMENTEEXECUTADA, DescMsg.ER_ORDER_PARTIALLY_FILLED, bolsa);
                    break;

                // Order Expiration (all time in forces, except FOK and IOC)
                case OrdStatus.EXPIRED:
                    this._er_Update(er, FixOrderStatus.EXPIRADA, DescMsg.ER_ORDER_EXPIRED, bolsa);
                    break;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Problemas no processamento da mensagem ExecutionReport: " + ex.Message, ex);
            }
        }
Example #29
0
        private void EmitExecutionReport(OrderRecord record, OrdStatus ordStatus, double lastPx, int lastQty, string text, CommType commType, double commission)
        {
            ExecutionReport report = new ExecutionReport
            {
                TransactTime     = Clock.Now,
                ClOrdID          = record.Order.ClOrdID,
                OrigClOrdID      = record.Order.ClOrdID,
                OrderID          = record.Order.OrderID,
                Symbol           = record.Order.Symbol,
                SecurityType     = record.Order.SecurityType,
                SecurityExchange = record.Order.SecurityExchange,
                Currency         = record.Order.Currency,
                CommType         = commType,
                Commission       = commission,
                Side             = record.Order.Side,

                OrdType     = record.Order.OrdType,
                TimeInForce = record.Order.TimeInForce,
                OrderQty    = record.Order.OrderQty,
                Price       = record.Order.Price,
                StopPx      = record.Order.StopPx,
                LastPx      = lastPx,
                LastQty     = lastQty
            };

            if (ordStatus == OrdStatus.Replaced)
            {
                report.OrdType     = record.Order.ReplaceOrder.ContainsField(EFIXField.OrdType) ? record.Order.ReplaceOrder.OrdType : record.Order.OrdType;
                report.TimeInForce = record.Order.ReplaceOrder.ContainsField(EFIXField.TimeInForce) ? record.Order.ReplaceOrder.TimeInForce : record.Order.TimeInForce;
                report.OrderQty    = record.Order.ReplaceOrder.ContainsField(EFIXField.OrderQty) ? record.Order.ReplaceOrder.OrderQty : record.Order.OrderQty;
                report.Price       = record.Order.ReplaceOrder.ContainsField(EFIXField.Price) ? record.Order.ReplaceOrder.Price : record.Order.Price;
                report.StopPx      = record.Order.ReplaceOrder.ContainsField(EFIXField.StopPx) ? record.Order.ReplaceOrder.StopPx : record.Order.StopPx;
                record.LeavesQty   = ((int)report.OrderQty) - record.CumQty;
            }
            else
            {
                report.OrdType     = record.Order.OrdType;
                report.TimeInForce = record.Order.TimeInForce;
                report.OrderQty    = record.Order.OrderQty;
                report.Price       = record.Order.Price;
                report.StopPx      = record.Order.StopPx;
            }


            if (ordStatus == OrdStatus.Undefined)
            {
                record.AddFill(lastPx, lastQty);
                if (record.LeavesQty > 0)
                {
                    ordStatus = OrdStatus.PartiallyFilled;
                }
                else
                {
                    ordStatus = OrdStatus.Filled;
                }
            }
            report.AvgPx     = record.AvgPx;
            report.CumQty    = record.CumQty;
            report.LeavesQty = record.LeavesQty;
            report.ExecType  = CTPZQProvider.GetExecType(ordStatus);
            report.OrdStatus = ordStatus;
            report.Text      = text;

            EmitExecutionReport(report);
        }
Example #30
0
 internal void OnMessage(ExecutionReport report)
 {
     _emitter.EmitExecutionReport(report);
 }
        private static void ProcessExecutionReport(FixMessage msg)
        {
            ExecutionReport execReport;

            try
            {
                // отчет об исполнении может относиться не к клиентскому ордеру,
                // а к инициированной брокером процедуре (в т.ч. - стопауту)
                if (!msg.fieldValues.ContainsKey(FixMessage.TAG_CLIENT_ORDER_ID))
                {
                    ProcessBrokerInitiatedExecutionReport(msg);
                }

                // промежуточный отчет по исполнению ордера, не учитывается
                var ordStatusStr = msg[FixMessage.TAG_ORDER_STATUS];
                if (ordStatusStr == FixMessage.VALUE_ORDER_NEW ||
                    ordStatusStr == FixMessage.VALUE_ORDER_PARTIALLY_FILLED ||
                    ordStatusStr == FixMessage.VALUE_ORDER_CALCULATED)
                {
                    return;
                }

                // получить Id запроса
                var clientIdStr = msg[FixMessage.TAG_CLIENT_ORDER_ID];
                int clientId;
                if (!int.TryParse(clientIdStr, out clientId))
                {
                    loggerNoFlood.LogMessageFormatCheckFlood(LogEntryType.Debug,
                                                             LogMagicIncorrectId, 1000 * 60 * 15, "Отчет брокера: поле ClientOrderId не представлено целым [{0}]",
                                                             clientIdStr);
                    return;
                }

                execReport = new ExecutionReport {
                    brokerResponse = { RequestId = clientId, ValueDate = DateTime.Now }
                };
                if (ordStatusStr == FixMessage.VALUE_ORDER_FILLED)
                {
                    execReport.brokerResponse.Status = OrderStatus.Исполнен;
                }
                else
                if (ordStatusStr == FixMessage.VALUE_ORDER_REJECTED)
                {
                    execReport.brokerResponse.Status = OrderStatus.Отклонен;
                }
                else
                {
                    // ордер может быть либо исполнен, либо не исполнен, третьего не дано
                    loggerNoFlood.LogMessageFormatCheckFlood(LogEntryType.Debug,
                                                             LogMagicIncorrectStatus, 1000 * 60 * 15, "Отчет брокера по запросу [{0}]: статус ({1}) не поддерживается",
                                                             clientId,
                                                             ordStatusStr);
                    return;
                }

                var price = (decimal?)null;
                if (msg.fieldValues.ContainsKey(FixMessage.TAG_ARG_PX))
                {
                    price = msg.GetValueDecimal(FixMessage.TAG_ARG_PX);
                }
                else
                if (msg.fieldValues.ContainsKey(FixMessage.TAG_PRICE))
                {
                    price = msg.GetValueDecimal(FixMessage.TAG_PRICE);
                }
                // нет цены в положительной квитанции
                if (!price.HasValue && execReport.brokerResponse.Status == OrderStatus.Исполнен)
                {
                    loggerNoFlood.LogMessageFormatCheckFlood(LogEntryType.Debug,
                                                             LogMagicNoQuoteInPositiveReport, 1000 * 60 * 15,
                                                             "Отчет брокера по запросу [{0}]: статус \"Исполнен\", нет цены",
                                                             clientId);
                    return;
                }
                execReport.brokerResponse.Price = price ?? 0;
                // сообщение об ошибке
                execReport.brokerResponse.RejectReason = OrderRejectReason.None;
                if (execReport.brokerResponse.Status != OrderStatus.Исполнен)
                {
                    if (msg.fieldValues.ContainsKey(FixMessage.TAG_ORD_REJECT_REASON))
                    {
                        var rejectReasonStr = msg[FixMessage.TAG_ORD_REJECT_REASON];
                        execReport.brokerResponse.RejectReason =
                            rejectReasonStr == FixMessage.VALUE_ORDER_REJECT_BROKER_EXCHANGE_OPT
                                ? OrderRejectReason.BrokerExchangeOption
                                : rejectReasonStr == FixMessage.VALUE_ORDER_REJECT_DUPLICATE_ORDER
                                      ? OrderRejectReason.DuplicateClOrdID
                                      : rejectReasonStr == FixMessage.VALUE_ORDER_REJECT_UNKNOWN_ORDER
                                      ? OrderRejectReason.UnknownOrder : OrderRejectReason.None;
                        execReport.brokerResponse.RejectReasonString = rejectReasonStr;
                    }
                }
            }
            catch (Exception ex)
            {
                loggerNoFlood.LogMessageFormatCheckFlood(LogEntryType.Debug,
                                                         LogMagicCommonReportParseError, 1000 * 60 * 15,
                                                         "Общая ошибка обработки ответа провайдера: {0}",
                                                         ex);
                return;
            }
            // отправить отчет FIX-дилеру
            try
            {
                execReport.SendToQueue(false);
            }
            catch (Exception ex)
            {
                loggerNoFlood.LogMessageFormatCheckFlood(LogEntryType.Debug,
                                                         LogMagicSendReportError, 1000 * 60 * 15,
                                                         "Ошибка отправки сообщения в очередь: {0}",
                                                         ex);
            }
        }
        public override void onMessage(QuickFix42.ExecutionReport report, QuickFix.SessionID sessionID)
        {
            if (report.getExecType().getValue() == QuickFix.ExecType.PENDING_CANCEL ||
                report.getExecType().getValue() == QuickFix.ExecType.CANCELED ||
                report.getExecType().getValue() == QuickFix.ExecType.PENDING_REPLACE ||
                report.getExecType().getValue() == QuickFix.ExecType.REPLACE)
            {
                object request = cancelRequests[report.getClOrdID().getValue()];

                if (request == null)
                {
                    report.set(new OrigClOrdID(report.getClOrdID().getValue()));
                }
                else
                {
                    if (request is FIXOrderCancelRequest)
                    {
                        report.set(new OrigClOrdID((request as FIXOrderCancelRequest).OrigClOrdID));
                    }

                    if (request is FIXOrderCancelReplaceRequest)
                    {
                        report.set(new OrigClOrdID((request as FIXOrderCancelReplaceRequest).OrigClOrdID));
                    }
                }
            }

            ExecutionReport Report = new ExecutionReport();

            if (report.isSetOrderID())
            {
                Report.OrderID = report.getOrderID().getValue();
            }
            ////if (report.isSetSecondaryOrderID()) Report.SecondaryOrderID = report.getSecondaryOrderID().getValue();
            if (report.isSetClOrdID())
            {
                Report.ClOrdID = report.getClOrdID().getValue();
            }
            if (report.isSetOrigClOrdID())
            {
                Report.OrigClOrdID = report.getOrigClOrdID().getValue();
            }
            ////if (report.isSetListID()) Report.ListID = report.getListID().getValue();
            if (report.isSetExecID())
            {
                Report.ExecID = report.getExecID().getValue();
            }
            ////if (report.isSetExecRefID()) Report.ExecRefID = report.getExecRefID().getValue();
            if (report.isSetExecType())
            {
                (Report as FIXExecutionReport).ExecType = report.getExecType().getValue();
            }
            if (report.isSetOrdStatus())
            {
                (Report as FIXExecutionReport).OrdStatus = report.getOrdStatus().getValue();
            }
            if (report.isSetOrdRejReason())
            {
                Report.OrdRejReason = report.getOrdRejReason().getValue();
            }
            ////if (report.isSetExecRestatementReason()) Report.ExecRestatementReason = report.getExecRestatementReason().getValue();
            ////if (report.isSetAccount()) Report.Account = report.getAccount().getValue();
            ////if (report.isSetSettlmntTyp()) Report.SettlType = report.getSettlmntTyp().getValue();
            //if (report.isSetFutSettDate           ()) Report.FutSettDate            = report.getFutSettDate           ().getValue();
            if (report.isSetSymbol())
            {
                Report.Symbol = report.getSymbol().getValue();
            }
            ////if (report.isSetSymbolSfx()) Report.SymbolSfx = report.getSymbolSfx().getValue();
            ////if (report.isSetSecurityID()) Report.SecurityID = report.getSecurityID().getValue();
            //if (report.isSetIDSource              ()) Report.IDSource               = report.getIDSource              ().getValue();
            ////if (report.isSetSecurityType()) Report.SecurityType = report.getSecurityType().getValue();
            ////if (report.isSetMaturityMonthYear()) Report.MaturityMonthYear = report.getMaturityMonthYear().getValue();
            //if (report.isSetMaturityDay           ()) Report.MaturityDate           = DateTime.Parse(report.getMaturityDay           ().getValue());
            //if (report.isSetPutOrCall             ()) Report.PutOrCall              = report.getPutOrCall             ().getValue();
            ////if (report.isSetStrikePrice()) Report.StrikePrice = report.getStrikePrice().getValue();
            ////if (report.isSetOptAttribute()) Report.OptAttribute = report.getOptAttribute().getValue();
            ////if (report.isSetContractMultiplier()) Report.ContractMultiplier = report.getContractMultiplier().getValue();
            ////if (report.isSetCouponRate()) Report.CouponRate = report.getCouponRate().getValue();
            ////if (report.isSetSecurityExchange()) Report.SecurityExchange = report.getSecurityExchange().getValue();
            ////if (report.isSetIssuer()) Report.Issuer = report.getIssuer().getValue();
            ////if (report.isSetEncodedIssuerLen()) Report.EncodedIssuerLen = report.getEncodedIssuerLen().getValue();
            ////if (report.isSetEncodedIssuer()) Report.EncodedIssuer = report.getEncodedIssuer().getValue();
            ////if (report.isSetSecurityDesc()) Report.SecurityDesc = report.getSecurityDesc().getValue();
            ////if (report.isSetEncodedSecurityDescLen()) Report.EncodedSecurityDescLen = report.getEncodedSecurityDescLen().getValue();
            ////if (report.isSetEncodedSecurityDesc()) Report.EncodedSecurityDesc = report.getEncodedSecurityDesc().getValue();
            if (report.isSetSide())
            {
                (Report as FIXExecutionReport).Side = report.getSide().getValue();
            }
            if (report.isSetOrderQty())
            {
                Report.OrderQty = report.getOrderQty().getValue();
            }
            ////if (report.isSetCashOrderQty()) Report.CashOrderQty = report.getCashOrderQty().getValue();
            if (report.isSetOrdType())
            {
                (Report as FIXExecutionReport).OrdType = report.getOrdType().getValue();
            }
            if (report.isSetPrice())
            {
                Report.Price = report.getPrice().getValue();
            }
            ////if (report.isSetStopPx()) Report.StopPx = report.getStopPx().getValue();
            //if (report.isSetPegDifference         ()) Report.PegDifference          = report.getPegDifference         ().getValue();
            ////if (report.isSetDiscretionInst()) Report.DiscretionInst = report.getDiscretionInst().getValue();
            ////if (report.isSetDiscretionOffset()) Report.DiscretionOffsetValue = report.getDiscretionOffset().getValue();
            ////if (report.isSetCurrency()) Report.Currency = report.getCurrency().getValue();
            ////if (report.isSetComplianceID()) Report.ComplianceID = report.getComplianceID().getValue();
            //if (report.isSetSolicitedFlag         ()) Report.SolicitedFlag          = report.getSolicitedFlag         ().getValue();
            ////if (report.isSetTimeInForce()) (Report as FIXExecutionReport).TimeInForce = report.getTimeInForce().getValue();
            ////if (report.isSetEffectiveTime()) Report.EffectiveTime = report.getEffectiveTime().getValue();
            ////if (report.isSetExpireDate()) Report.ExpireDate = DateTime.Parse(report.getExpireDate().getValue());
            ////if (report.isSetExpireTime()) Report.ExpireTime = report.getExpireTime().getValue();
            ////if (report.isSetExecInst()) Report.ExecInst = report.getExecInst().getValue();
            //if (report.isSetRule80A               ()) Report.Rule80A                = report.getRule80A               ().getValue();
            if (report.isSetLastShares())
            {
                Report.LastQty = report.getLastShares().getValue();
            }
            if (report.isSetLastPx())
            {
                Report.LastPx = report.getLastPx().getValue();
            }
            ////if (report.isSetLastSpotRate()) Report.LastSpotRate = report.getLastSpotRate().getValue();
            ////if (report.isSetLastForwardPoints()) Report.LastForwardPoints = report.getLastForwardPoints().getValue();
            ////if (report.isSetLastMkt()) Report.LastMkt = report.getLastMkt().getValue();
            ////if (report.isSetTradingSessionID()) Report.TradingSessionID = report.getTradingSessionID().getValue();
            ////if (report.isSetLastCapacity()) Report.LastCapacity = report.getLastCapacity().getValue();
            if (report.isSetLeavesQty())
            {
                Report.LeavesQty = report.getLeavesQty().getValue();
            }
            if (report.isSetCumQty())
            {
                Report.CumQty = report.getCumQty().getValue();
            }
            if (report.isSetAvgPx())
            {
                Report.AvgPx = report.getAvgPx().getValue();
            }
            ////if (report.isSetDayOrderQty()) Report.DayOrderQty = report.getDayOrderQty().getValue();
            ////if (report.isSetDayCumQty()) Report.DayCumQty = report.getDayCumQty().getValue();
            ////if (report.isSetDayAvgPx()) Report.DayAvgPx = report.getDayAvgPx().getValue();
            ////if (report.isSetGTBookingInst()) Report.GTBookingInst = report.getGTBookingInst().getValue();
            ////if (report.isSetTradeDate()) Report.TradeDate = DateTime.Parse(report.getTradeDate().getValue());
            if (report.isSetTransactTime())
            {
                Report.TransactTime = report.getTransactTime().getValue();
            }
            //if (report.isSetReportToExch          ()) Report.ReportToExch           = report.getReportToExch          ().getValue();
            ////if (report.isSetCommission()) Report.Commission = report.getCommission().getValue();
            ////if (report.isSetCommType()) (Report as FIXExecutionReport).CommType = report.getCommType().getValue();
            ////if (report.isSetGrossTradeAmt()) Report.GrossTradeAmt = report.getGrossTradeAmt().getValue();
            ////if (report.isSetSettlCurrAmt()) Report.SettlCurrAmt = report.getSettlCurrAmt().getValue();
            ////if (report.isSetSettlCurrency()) Report.SettlCurrency = report.getSettlCurrency().getValue();
            ////if (report.isSetHandlInst()) Report.HandlInst = report.getHandlInst().getValue();
            ////if (report.isSetMinQty()) Report.MinQty = report.getMinQty().getValue();
            ////if (report.isSetMaxFloor()) Report.MaxFloor = report.getMaxFloor().getValue();
            //if (report.isSetOpenClose             ()) Report.OpenClose              = report.getOpenClose             ().getValue();
            ////if (report.isSetMaxShow()) Report.MaxShow = report.getMaxShow().getValue();
            if (report.isSetText())
            {
                Report.Text = report.getText().getValue();
            }
            ////if (report.isSetEncodedTextLen()) Report.EncodedTextLen = report.getEncodedTextLen().getValue();
            ////if (report.isSetEncodedText()) Report.EncodedText = report.getEncodedText().getValue();
            //if (report.isSetFutSettDate2          ()) Report.FutSettDate2           = report.getFutSettDate2          ().getValue();
            ////if (report.isSetOrderQty2()) Report.OrderQty2 = report.getOrderQty2().getValue();
            //if (report.isSetClearingFirm          ()) Report.ClearingFirm           = report.getClearingFirm          ().getValue();
            //if (report.isSetClearingAccount       ()) Report.ClearingAccount        = report.getClearingAccount       ().getValue();
            ////if (report.isSetMultiLegReportingType()) Report.MultiLegReportingType = report.getMultiLegReportingType().getValue();

            //

            SingleOrder order;

            if (Report.ExecType == SmartQuant.FIX.ExecType.PendingCancel ||
                Report.ExecType == SmartQuant.FIX.ExecType.Cancelled ||
                Report.ExecType == SmartQuant.FIX.ExecType.PendingReplace ||
                Report.ExecType == SmartQuant.FIX.ExecType.Replace)
            {
                order = OrderManager.Orders.All[Report.OrigClOrdID] as SingleOrder;
            }
            else
            {
                order = OrderManager.Orders.All[Report.ClOrdID] as SingleOrder;
            }

            Instrument instrument = order.Instrument;

            Report.Symbol = instrument.Symbol;

            Report.TransactTime = Clock.Now;

            // emit execution report

            EmitExecutionReport(Report);
        }
Example #33
0
 /// <summary>
 /// Returns the order expiry time if the given FIX message contains the tag (else null).
 /// </summary>
 /// <param name="message">The execution report FIX message.</param>
 /// <returns>A <see cref="decimal"/>.</returns>
 public static ZonedDateTime?GetExpireTime(ExecutionReport message)
 {
     return(message.IsSetField(Tags.ExpireTime)
         ? ParseTimestamp(message.GetField(Tags.ExpireTime))
         : null);
 }
        /// <summary>
        /// ExecutionReport message handler
        /// </summary>
        private void OnExecutionReport(ExecutionReport message)
        {
            var orderId     = message.getOrderID();
            var orderStatus = message.getFXCMOrdStatus();

            if (orderId != "NONE" && message.getAccount() == _accountId)
            {
                if (_openOrders.ContainsKey(orderId) && OrderIsClosed(orderStatus.getCode()))
                {
                    _openOrders.Remove(orderId);
                }
                else
                {
                    _openOrders[orderId] = message;
                }

                Order order;
                if (_mapFxcmOrderIdsToOrders.TryGetValue(orderId, out order))
                {
                    // existing order
                    if (!OrderIsBeingProcessed(orderStatus.getCode()))
                    {
                        var status = ConvertOrderStatus(orderStatus);

                        int id;
                        // if we get a Submitted status and we had placed an order update, this new event is flagged as an update
                        var isUpdate = status == OrderStatus.Submitted && _orderUpdates.TryRemove(order.Id, out id);
                        var security = _securityProvider.GetSecurity(order.Symbol);
                        order.PriceCurrency = security.SymbolProperties.QuoteCurrency;

                        var orderEvent = new OrderEvent(order,
                                                        DateTime.UtcNow,
                                                        OrderFee.Zero)
                        {
                            Status       = isUpdate ? OrderStatus.UpdateSubmitted : status,
                            FillPrice    = Convert.ToDecimal(message.getPrice()),
                            FillQuantity = Convert.ToInt32(message.getSide() == SideFactory.BUY ? message.getLastQty() : -message.getLastQty()),
                        };

                        // we're catching the first fill so we apply the fees only once
                        if ((int)message.getCumQty() == (int)message.getLastQty() && message.getLastQty() > 0)
                        {
                            orderEvent.OrderFee = security.FeeModel.GetOrderFee(
                                new OrderFeeParameters(security, order));
                        }

                        _orderEventQueue.Enqueue(orderEvent);
                    }
                }
                else if (_mapRequestsToOrders.TryGetValue(message.getRequestID(), out order))
                {
                    _mapFxcmOrderIdsToOrders[orderId] = order;
                    order.BrokerId.Add(orderId);
                    order.PriceCurrency = _securityProvider.GetSecurity(order.Symbol).SymbolProperties.QuoteCurrency;

                    // new order
                    var orderEvent = new OrderEvent(order,
                                                    DateTime.UtcNow,
                                                    OrderFee.Zero)
                    {
                        Status = ConvertOrderStatus(orderStatus)
                    };

                    _orderEventQueue.Enqueue(orderEvent);
                }
            }

            if (message.getRequestID() == _currentRequest)
            {
                if (message.isLastRptRequested())
                {
                    if (orderId == "NONE" && orderStatus.getCode() == IFixValueDefs.__Fields.FXCMORDSTATUS_REJECTED)
                    {
                        if (message.getSide() != SideFactory.UNDISCLOSED)
                        {
                            var messageText = message.getFXCMErrorDetails().Replace("\n", "");
                            Log.Trace("FxcmBrokerage.OnExecutionReport(): " + messageText);
                            OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSubmitReject", messageText));
                        }

                        _isOrderSubmitRejected = true;
                    }

                    AutoResetEvent autoResetEvent;
                    if (_mapRequestsToAutoResetEvents.TryGetValue(_currentRequest, out autoResetEvent))
                    {
                        autoResetEvent.Set();
                        _mapRequestsToAutoResetEvents.Remove(_currentRequest);
                    }
                }
            }
        }
 public virtual void OnExecutionReport(ExecutionReport report)
 {
     // noop
 }
 public static void SetErrorId(this ExecutionReport report, int errorId, int rawErrorId)
 {
     report.Fields[QuantBoxConst.ReportErrorOffset] = new MakeLong(errorId, rawErrorId);
 }
Example #37
0
        /// <summary>
        /// ExecutionReport message handler
        /// </summary>
        private void OnExecutionReport(ExecutionReport message)
        {
            var orderId     = message.getOrderID();
            var orderStatus = message.getFXCMOrdStatus();

            if (orderId != "NONE" && message.getAccount() == _accountId)
            {
                if (_openOrders.ContainsKey(orderId) && OrderIsClosed(orderStatus.getCode()))
                {
                    _openOrders.Remove(orderId);
                }
                else
                {
                    _openOrders[orderId] = message;
                }

                Order order;
                if (_mapFxcmOrderIdsToOrders.TryGetValue(orderId, out order))
                {
                    // existing order
                    if (!OrderIsBeingProcessed(orderStatus.getCode()))
                    {
                        var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                        {
                            Status       = ConvertOrderStatus(orderStatus),
                            FillPrice    = Convert.ToDecimal(message.getPrice()),
                            FillQuantity = Convert.ToInt32(message.getSide() == SideFactory.BUY ? message.getLastQty() : -message.getLastQty())
                        };

                        _orderEventQueue.Enqueue(orderEvent);
                    }
                }
                else if (_mapRequestsToOrders.TryGetValue(message.getRequestID(), out order))
                {
                    _mapFxcmOrderIdsToOrders[orderId] = order;
                    order.BrokerId.Add(Convert.ToInt64(orderId));

                    // new order
                    var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                    {
                        Status = ConvertOrderStatus(orderStatus)
                    };

                    _orderEventQueue.Enqueue(orderEvent);
                }
            }

            if (message.getRequestID() == _currentRequest)
            {
                if (message.isLastRptRequested())
                {
                    if (orderId == "NONE" && orderStatus.getCode() == IFixValueDefs.__Fields.FXCMORDSTATUS_REJECTED)
                    {
                        if (message.getSide() != SideFactory.UNDISCLOSED)
                        {
                            var messageText = message.getFXCMErrorDetails().Replace("\n", "");
                            Log.Trace("FxcmBrokerage.OnExecutionReport(): " + messageText);
                            OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSubmitReject", messageText));
                        }

                        _isOrderSubmitRejected = true;
                    }

                    _mapRequestsToAutoResetEvents[_currentRequest].Set();
                    _mapRequestsToAutoResetEvents.Remove(_currentRequest);
                }
            }
        }
Example #38
0
        // ExecutionReport message handler
        private void OnExecutionReport(ExecutionReport executionReport)
        {
            Console.WriteLine("OnExecutionReport()");
            Console.WriteLine("\tRequestId = {0}", executionReport.getRequestID());

            Console.WriteLine("\tgetOrderID() = " + executionReport.getOrderID());
            Console.WriteLine("\tgetFXCMPosID() = " + executionReport.getFXCMPosID());
            Console.WriteLine("\tgetAccount() = " + executionReport.getAccount());
            Console.WriteLine("\tgetTransactTime() = " + executionReport.getTransactTime());
            Console.WriteLine("\tgetExecType() = " + executionReport.getExecType());
            Console.WriteLine("\tgetFXCMOrdStatus() = " + executionReport.getFXCMOrdStatus());
            Console.WriteLine("\tgetOrdStatus() = " + executionReport.getOrdStatus());
            Console.WriteLine("\tgetPrice() = " + executionReport.getPrice());
            Console.WriteLine("\tgetStopPx() = " + executionReport.getStopPx());
            Console.WriteLine("\tgetOrderQty() = " + executionReport.getOrderQty());
            Console.WriteLine("\tgetCumQty() = " + executionReport.getCumQty());
            Console.WriteLine("\tgetLastQty() = " + executionReport.getLastQty());
            Console.WriteLine("\tgetLeavesQty() = " + executionReport.getLeavesQty());
            Console.WriteLine("\tgetFXCMErrorDetails() = " + executionReport.getFXCMErrorDetails());
            Console.WriteLine();

            var orderId = executionReport.getOrderID();
            if (orderId != "NONE")
            {
                _orders[orderId] = executionReport;
                _orderRequests[executionReport.getRequestID()] = executionReport;
            }

            if (executionReport.getRequestID() == _currentRequest)
            {
                var status = executionReport.getFXCMOrdStatus().getCode();
                if (executionReport.isLastRptRequested() &&
                    status != IFixValueDefs.__Fields.FXCMORDSTATUS_PENDING_CANCEL &&
                    status != IFixValueDefs.__Fields.FXCMORDSTATUS_EXECUTING &&
                    status != IFixValueDefs.__Fields.FXCMORDSTATUS_INPROCESS)
                {
                    _requestOrderEvent.Set();
                }
            }
        }
Example #39
0
 public override void onExecutionReport(ExecutionReport report)
 {
     Console.WriteLine("Got on onExecutionReport Event.");
     report.dump();
     Console.WriteLine("Status = %d",OrderStatus.OrderStatus_CONFIRMED);
     if(report.getInstrumentName() == (_data.firstLegSymbol))
     {
         if( report.getOrderStatus() == OrderStatus.OrderStatus_CONFIRMED ||
             report.getOrderStatus() == OrderStatus.OrderStatus_REPLACED )
         {
             _data.firstLegOrder.setClOrdId(report.getClOrderId());
             _data.firstLegOrder.setOrigClOrdId(report.getOriginalClOrderId());
             _data.firstLegOrder.setOrderStatus(OrderStatus.OrderStatus_CONFIRMED);
             _data.isOrderPending = false;
         }
         else if(report.getOrderStatus() == OrderStatus.OrderStatus_FILLED)
         {
             placeSecondLegMarket();
             _data.isOrderPending = false;
         }
     }
     else if(report.getInstrumentName() == (_data.secondLegSymbol))
     {
         if(report.getOrderStatus() == OrderStatus.OrderStatus_CONFIRMED)
         {
             _data.secondLegOrder.setClOrdId(report.getClOrderId());
             _data.secondLegOrder.setOrigClOrdId(report.getOriginalClOrderId());
             _data.isOrderPending = false;
         }
         else if(report.getOrderStatus() == OrderStatus.OrderStatus_FILLED)
         {
             Console.WriteLine("Strategy completed successfully.");
         }
     }
 }
Example #40
0
 /// <summary>
 /// Returns the domain price for the given order type parsed from the given message.
 /// </summary>
 /// <param name="orderType">The order type.</param>
 /// <param name="message">The execution report FIX message.</param>
 /// <returns>A <see cref="decimal"/>.</returns>
 public static Price GetOrderPrice(OrderType orderType, ExecutionReport message)
 {
     return(Price.Create(orderType == OrderType.Stop
         ? message.GetDecimal(Tags.StopPx)
         : message.GetDecimal(Tags.Price)));
 }
Example #41
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="signal">交易信号(正向/反向)</param>
        /// <param name="data">KLine格式的交易数据</param>
        /// <param name="positions">头寸信息</param>
        /// <param name="myAccount">账户信息</param>
        /// <param name="now">交易日的时间信息</param>
        /// <param name="nowIndex">当前索引值(不知道什么意思)</param>
        /// <param name="slipPoint">滑点</param>
        /// <returns></returns>
        public static Dictionary <string, ExecutionReport> ComputePosition(Dictionary <string, MinuteSignal> signal, Dictionary <string, List <KLine> > data, ref SortedDictionary <DateTime, Dictionary <string, PositionsWithDetail> > positions, ref BasicAccount myAccount, DateTime now, int nowIndex, double slipPoint = 0.00)
        {
            //初始化记录成交回报的变量
            Dictionary <string, ExecutionReport> tradingFeedback = new Dictionary <string, ExecutionReport>();
            //初始化上一次头寸记录时间
            DateTime lastTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);

            //如果signal无信号,无法成交,直接返回空的成交回报。
            if (signal == null || signal.Count == 0)
            {
                return(tradingFeedback);
            }
            if (positions.Count != 0)
            {
                lastTime = positions.Keys.Last();
            }
            //新建头寸变量,作为接受新仓位的容器
            Dictionary <string, PositionsWithDetail> positionShot = new Dictionary <string, PositionsWithDetail>();

            //如果持仓最后状态时间大于signal信号的时间,无成交,直接返回空的成交回报。
            if (lastTime > now)
            {
                return(tradingFeedback);
            }
            //如果两者时间相等,则把总仓位变化数组positions中的最后一项,添加进新仓位的容器positionShot中
            if (now == lastTime)
            {
                positionShot = positions[positions.Keys.Last()];
            }
            //如果交易信号时间在最后一次持仓变化时间点之后,则需要重新把最后持仓的仓位变化信息手工copy一份;
            //然后添加进新仓位的容器positionShot中。
            else if (positions.Count > 0)                              //如果持仓大于0
            {
                foreach (var item in positions[positions.Keys.Last()]) //循环 持仓最后状态时间的持仓数据
                {
                    //这里必须手动copy一份,不可以直接传引用。因为最后持仓变化节点的仓位信息是不应该被改变的;
                    //如果直接传引用,交易信号时间点仓位变化会同时改变最后持仓变化节点的仓位信息。
                    PositionsWithDetail position0 = new PositionsWithDetail().myClone(item.Value);//复制一份新的
                    positionShot.Add(position0.code, position0);
                }
            }
            //获取前一步的头寸信息,如果没有寸头就设为null
            Dictionary <string, PositionsWithDetail> positionLast = (positions.Count == 0 ? null : positions[positions.Keys.Last()]);

            //对信号进行遍历
            foreach (var signal0 in signal.Values)
            {
                //整理成交信号,剔除不合理信号。
                //①信号触发时间必须在positionLast的记录时间之后,在当前时间now之前。
                //②信号必须有合理的交易数量。
                //③信号必须有对应的数据。
                if (signal0.time != now) //【???】不是说必须要在当前时间now之前么
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.status = "交易时间错误,无效信号";
                    tradingFeedback.Add(signal0.code, report0);
                    continue;
                }
                if (signal0.volume == 0 || signal0.price == 0)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.status = "交易数据错误,无效信号";
                    tradingFeedback.Add(signal0.code, report0);
                    continue;
                }
                if (data.ContainsKey(signal0.code) == false)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.status = "无法找到行情数据,无效信号";
                    tradingFeedback.Add(signal0.code, report0);
                    continue;
                }

                //根据K线来判断成交数量,有可能完全成交,也有可能部分成交
                //开多头时,如果价格大于最低价,完全成交,否者不成交
                //开空头时,如果价格小于最高价,完全成交,否者不成交

                //找出对应的K线
                KLine KLineData = data[signal0.code][nowIndex];
                //确定滑点
                double slip = Math.Max(slipPoint, signal0.bidAskSpread);

                //开多头时,如果价格大于最低价,完全成交,否者不成交
                if (signal0.volume > 0 && signal0.price >= KLineData.low)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.volume = signal0.volume;
                    report0.price  = signal0.price + slip;
                    report0.status = "完全成交";
                    tradingFeedback.Add(signal0.code, report0);
                }
                if (signal0.volume > 0 && signal0.price < KLineData.low)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.price  = signal0.price + slip;
                    report0.status = "无法成交";
                    tradingFeedback.Add(signal0.code, report0);
                    continue;
                }

                //开空头时,如果价格小于最高价,完全成交,否者不成交
                if (signal0.volume < 0 && signal0.price <= KLineData.high)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.price  = signal0.price - slip;
                    report0.volume = signal0.volume;
                    report0.status = "完全成交";
                    tradingFeedback.Add(signal0.code, report0);
                }
                if (signal0.volume < 0 && signal0.price > KLineData.high)
                {
                    ExecutionReport report0 = new ExecutionReport();
                    report0.code   = signal0.code;
                    report0.time   = signal0.time;
                    report0.price  = signal0.price - slip;
                    report0.status = "无法成交";
                    tradingFeedback.Add(signal0.code, report0);
                    continue;
                }

                ///【解释:以下部分 position,positionShot和position0的关系】
                /// position:是传入的参数,
                ///

                //接下来处理能够成交的signal0,信号下单的时间只能是lastTime或者now。
                PositionsWithDetail position0 = new PositionsWithDetail();
                //查询当前持仓数量
                double nowHoldingVolume;
                //当前证券已有持仓
                if (positionShot.Count > 0 && positionShot.ContainsKey(signal0.code))
                {
                    //将当前证券持仓情况赋值给临时持仓变量
                    position0        = positionShot[signal0.code];
                    nowHoldingVolume = position0.volume;
                }
                else //若历史无持仓
                {
                    //当前信号证券代码
                    position0.code = signal0.code;
                    //多空头寸初始化
                    position0.LongPosition  = new PositionDetail();
                    position0.ShortPosition = new PositionDetail();
                    position0.record        = new List <TransactionRecord>();
                    nowHoldingVolume        = 0;
                    positionShot.Add(position0.code, position0);
                }
                //持仓和开仓方向一致
                if (nowHoldingVolume * signal0.volume >= 0)
                {
                    //开多仓
                    if (signal0.volume > 0)
                    {
                        //重新计算仓位和价格
                        double volume       = signal0.volume + position0.LongPosition.volume;
                        double cost         = (signal0.price + slip) * signal0.volume + position0.LongPosition.volume * position0.LongPosition.averagePrice;
                        double averagePrice = cost / volume;
                        position0.LongPosition = new PositionDetail {
                            volume = volume, totalCost = cost, averagePrice = averagePrice
                        };
                    }
                    else //开空仓
                    {
                        //重新计算仓位和价格
                        double volume       = signal0.volume + position0.ShortPosition.volume;
                        double cost         = (signal0.price - slip) * signal0.volume + position0.ShortPosition.volume * position0.ShortPosition.averagePrice;
                        double averagePrice = cost / volume;
                        position0.ShortPosition = new PositionDetail {
                            volume = volume, totalCost = cost, averagePrice = averagePrice
                        };
                    }
                }
                else //持仓和开仓方向不一致
                {
                    if (nowHoldingVolume > 0) //原先持有多头头寸,现开空仓
                    {
                        //计算总头寸,分类讨论
                        double volume = signal0.volume + position0.LongPosition.volume;
                        if (volume > 0)
                        {
                            position0.LongPosition.volume    = volume;
                            position0.LongPosition.totalCost = position0.LongPosition.volume * position0.LongPosition.averagePrice;
                        }
                        else if (volume < 0)
                        {
                            position0.ShortPosition.volume       = volume;
                            position0.ShortPosition.totalCost    = volume * (signal0.price - slip);
                            position0.ShortPosition.averagePrice = (signal0.price - slip);
                            position0.LongPosition = new PositionDetail();
                        }
                        else
                        {
                            position0.LongPosition = new PositionDetail();
                        }
                    }
                    else //原先持有空头头寸,现开多仓
                    {
                        //计算总头寸,分类讨论
                        double volume = signal0.volume + position0.ShortPosition.volume;
                        if (volume < 0)
                        {
                            position0.ShortPosition.volume    = volume;
                            position0.ShortPosition.totalCost = position0.ShortPosition.volume * position0.ShortPosition.averagePrice;
                        }
                        else if (volume > 0)
                        {
                            position0.LongPosition.volume       = volume;
                            position0.LongPosition.averagePrice = (signal0.price + slip);
                            position0.LongPosition.totalCost    = (signal0.price - slip) * volume;
                            position0.ShortPosition             = new PositionDetail();
                        }
                        else
                        {
                            position0.ShortPosition = new PositionDetail();
                        }
                    }
                }
                //更新其他信息
                position0.record.Add(new TransactionRecord
                {
                    time   = now,
                    volume = signal0.volume,
                    price  = signal0.price + slip * (signal0.volume > 0?1:-1),
                    code   = position0.code
                });
                position0.totalCashFlow    = position0.totalCashFlow - (signal0.price + (signal0.volume > 0 ? 1 : -1) * slip) * signal0.volume;
                position0.transactionCost  = position0.transactionCost + Math.Abs(slip * signal0.volume);
                position0.volume           = position0.volume + signal0.volume;
                position0.time             = now;
                position0.code             = signal0.code;
                position0.currentPrice     = KLineData.close;
                position0.tradingVarieties = signal0.tradingVarieties;
                //总资产=权益现值+现金盈亏
                position0.totalAmt = position0.totalCashFlow + position0.volume * position0.currentPrice;
            }
            if (now > lastTime)
            {
                positions.Add(now, positionShot);
            }
            //更新持仓的头寸信息
            if (positions.Count != 0)
            {
                AccountUpdatingWithMinuteBar.computeAccount(ref myAccount, positions, now, nowIndex, data);
            }
            return(tradingFeedback);
        }
Example #42
0
 protected override void OnExecutionReport(ExecutionReport report)
 {
 }
Example #43
0
 public double GetExecutionPrice(ExecutionReport report)
 {
     //report.Price
     report.Side = Side.Buy;
     throw new Exception("The method or operation is not implemented.");
 }
 private void HandleOrderReport(ExecutionReport er)
 {
     _logger.LogInformation($"Execution report: {er}");
 }
Example #45
0
        public Message CreateOrderCancelAccept(IOrder cancelledOrder, string execID)
        {
            var exReport = new ExecutionReport(
                new OrderID(cancelledOrder.ID.ToString(CultureInfo.InvariantCulture)),
                new ExecID(execID),
                new ExecType(ExecType.CANCELED),
                new OrdStatus(OrdStatus.CANCELED),
                new Symbol(cancelledOrder.Contract.Symbol),
                TranslateFixFields.Translate(cancelledOrder.MarketSide),
                new LeavesQty(0m), // 0 because the order is being cancelled
                new CumQty(cancelledOrder.FilledQuantity),
                new AvgPx(cancelledOrder.Price))
                {
                    OrderQty = new OrderQty(cancelledOrder.OriginalQuantity),
                    ClOrdID = new ClOrdID(cancelledOrder.ClOrdID)
                };

            return exReport;
        }
Example #46
0
 public int update(ExecutionReport report)
 {
     int ret = ContextModulePINVOKE.OrderBook_update__SWIG_1(swigCPtr, ExecutionReport.getCPtr(report));
     if (ContextModulePINVOKE.SWIGPendingException.Pending) throw ContextModulePINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Example #47
0
 internal void method_28(ExecutionReport executionReport_0)
 {
     if (executionReport_0.order_0.strategyId == -1)
     {
         return;
     }
     if (this.strategy__0 != null && this.strategy__0.Status == StrategyStatus.Running)
     {
         this.idArray_0[executionReport_0.order_0.strategyId].vmethod_31(executionReport_0);
     }
 }
Example #48
0
 private void DispatcherExecutionReport(object sender, ExecutionReport report)
 {
     OrderManagerQueue.Enqueue(report);
 }
Example #49
0
        private void HandleExecutionReport(ExecutionReport msg)
        {
            if (msg == null) throw new ArgumentNullException("msg");

            var order = new OrderRecord(msg);
            var status = TranslateFixFields.Translate(msg.OrdStatus);

            var e = OrderExecutionEvent;
            if (e != null)
                e(status, order);
        }
Example #50
0
 internal static HandleRef getCPtr(ExecutionReport obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Example #51
0
        public Message CreateRejectNewOrderExecutionReport(string symbol,
                                                           MarketSide marketSide,
                                                           string clOrdID,
                                                           decimal orderQuantity,
                                                           TradingAccount account,
                                                           string execID,
                                                           string rejectionReason,
                                                           int? rejectionCode = null)
        {
            var exReport = new ExecutionReport(
               new OrderID("unknown orderID"),
               new ExecID(execID),
               new ExecType(ExecType.REJECTED),
               new OrdStatus(OrdStatus.REJECTED),
               new Symbol(symbol),
               TranslateFixFields.Translate(marketSide),
               new LeavesQty(0m),
               new CumQty(0m),
               new AvgPx(0m))
            {
                ClOrdID = new ClOrdID(clOrdID),
                OrderQty = new OrderQty(orderQuantity)
            };

            if (rejectionCode.HasValue)
            {
                exReport.OrdRejReason = new OrdRejReason(rejectionCode.Value);
            }

            if (TradingAccount.IsSet(account))
            {
                exReport.Account = new Account(account.Name);
            }

            return exReport;
        }
        /// <summary>
        /// ExecutionReport message handler
        /// </summary>
        private void OnExecutionReport(ExecutionReport message)
        {
            var orderId = message.getOrderID();
            var orderStatus = message.getFXCMOrdStatus();

            if (orderId != "NONE" && message.getAccount() == _accountId)
            {
                if (_openOrders.ContainsKey(orderId) && OrderIsClosed(orderStatus.getCode()))
                {
                    _openOrders.Remove(orderId);
                }
                else
                {
                    _openOrders[orderId] = message;
                }

                Order order;
                if (_mapFxcmOrderIdsToOrders.TryGetValue(orderId, out order))
                {
                    // existing order
                    if (!OrderIsBeingProcessed(orderStatus.getCode()))
                    {
                        var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                        {
                            Status = ConvertOrderStatus(orderStatus),
                            FillPrice = Convert.ToDecimal(message.getPrice()),
                            FillQuantity = Convert.ToInt32(message.getSide() == SideFactory.BUY ? message.getLastQty() : -message.getLastQty())
                        };

                        _orderEventQueue.Enqueue(orderEvent);
                    }
                }
                else if (_mapRequestsToOrders.TryGetValue(message.getRequestID(), out order))
                {
                    _mapFxcmOrderIdsToOrders[orderId] = order;
                    order.BrokerId.Add(Convert.ToInt64(orderId));

                    // new order
                    var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                    {
                        Status = ConvertOrderStatus(orderStatus)
                    };

                    _orderEventQueue.Enqueue(orderEvent);
                }
            }

            if (message.getRequestID() == _currentRequest)
            {
                if (message.isLastRptRequested())
                {
                    if (orderId == "NONE" && orderStatus.getCode() == IFixValueDefs.__Fields.FXCMORDSTATUS_REJECTED)
                    {
                        Log.Trace("Order submit rejected: {0}", message.getFXCMErrorDetails().Replace("\n", ""));
                        _isOrderSubmitRejected = true;
                    }

                    _mapRequestsToAutoResetEvents[_currentRequest].Set();
                    _mapRequestsToAutoResetEvents.Remove(_currentRequest);
                }
            }
        }
 public virtual void OnExecutionReport(SingleOrder order, ExecutionReport report)
 {
 }
        /// <summary>
        /// ExecutionReport message handler
        /// </summary>
        private void OnExecutionReport(ExecutionReport message)
        {
            var orderId = message.getOrderID();
            var orderStatus = message.getFXCMOrdStatus();

            if (orderId != "NONE" && message.getAccount() == _accountId)
            {
                if (_openOrders.ContainsKey(orderId) && OrderIsClosed(orderStatus.getCode()))
                {
                    _openOrders.Remove(orderId);
                }
                else
                {
                    _openOrders[orderId] = message;
                }

                Order order;
                if (_mapFxcmOrderIdsToOrders.TryGetValue(orderId, out order))
                {
                    // existing order
                    if (!OrderIsBeingProcessed(orderStatus.getCode()))
                    {
                        order.PriceCurrency = message.getCurrency();

                        var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                        {
                            Status = ConvertOrderStatus(orderStatus),
                            FillPrice = Convert.ToDecimal(message.getPrice()),
                            FillQuantity = Convert.ToInt32(message.getSide() == SideFactory.BUY ? message.getLastQty() : -message.getLastQty())
                        };

                        // we're catching the first fill so we apply the fees only once
                        if ((int)message.getCumQty() == (int)message.getLastQty() && message.getLastQty() > 0)
                        {
                            var security = _securityProvider.GetSecurity(order.Symbol);
                            orderEvent.OrderFee = security.FeeModel.GetOrderFee(security, order);
                        }

                        _orderEventQueue.Enqueue(orderEvent);
                    }
                }
                else if (_mapRequestsToOrders.TryGetValue(message.getRequestID(), out order))
                {
                    _mapFxcmOrderIdsToOrders[orderId] = order;
                    order.BrokerId.Add(orderId);
                    order.PriceCurrency = message.getCurrency();

                    // new order
                    var orderEvent = new OrderEvent(order, DateTime.UtcNow, 0)
                    {
                        Status = ConvertOrderStatus(orderStatus)
                    };

                    _orderEventQueue.Enqueue(orderEvent);
                }
            }

            if (message.getRequestID() == _currentRequest)
            {
                if (message.isLastRptRequested())
                {
                    if (orderId == "NONE" && orderStatus.getCode() == IFixValueDefs.__Fields.FXCMORDSTATUS_REJECTED)
                    {
                        if (message.getSide() != SideFactory.UNDISCLOSED)
                        {
                            var messageText = message.getFXCMErrorDetails().Replace("\n", "");
                            Log.Trace("FxcmBrokerage.OnExecutionReport(): " + messageText);
                            OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "OrderSubmitReject", messageText));
                        }

                        _isOrderSubmitRejected = true;
                    }

                    _mapRequestsToAutoResetEvents[_currentRequest].Set();
                    _mapRequestsToAutoResetEvents.Remove(_currentRequest);
                }
            }
        }
 public OnExecutionReport(ExecutionReport report)
 {
     this.report = report;
 }