private OrderFilled GenerateOrderFilledEvent(ExecutionReport message)
        {
            var orderId          = this.GetOrderId(message);
            var executionId      = new ExecutionId(message.GetField(Tags.ExecID));
            var positionIdBroker = new PositionIdBroker(message.GetField(FxcmTags.PosID));
            var symbol           = this.GetSymbol(message.GetString(Tags.Symbol));
            var orderSide        = FxcmMessageHelper.GetOrderSide(message.GetField(Tags.Side));
            var filledQuantity   = Quantity.Create(message.GetDecimal(Tags.CumQty));
            var averagePrice     = Price.Create(message.GetDecimal(Tags.AvgPx));
            var quoteCurrency    = this.GetQuoteCurrency(symbol, message.GetField(Tags.Currency));
            var executionTime    = FxcmMessageHelper.ParseTimestamp(message.GetField(Tags.TransactTime));

            return(new OrderFilled(
                       this.accountId,
                       orderId,
                       executionId,
                       positionIdBroker,
                       symbol,
                       orderSide,
                       filledQuantity,
                       averagePrice,
                       quoteCurrency,
                       executionTime,
                       this.NewGuid(),
                       this.TimeNow()));
        }
        private OrderAccepted GenerateOrderAcceptedEvent(ExecutionReport message)
        {
            var orderId       = this.GetOrderId(message);
            var orderIdBroker = new OrderIdBroker(message.GetField(Tags.OrderID));
            var acceptedTime  = FxcmMessageHelper.ParseTimestamp(message.GetField(Tags.TransactTime));

            return(new OrderAccepted(
                       this.accountId,
                       orderId,
                       orderIdBroker,
                       acceptedTime,
                       this.NewGuid(),
                       this.TimeNow()));
        }
        private OrderRejected GenerateOrderRejectedEvent(ExecutionReport message)
        {
            var orderId      = this.GetOrderId(message);
            var rejectedTime = FxcmMessageHelper.ParseTimestamp(message.GetField(Tags.TransactTime));
            var rejectReason = message.GetField(FxcmTags.ErrorDetails).TrimEnd('.');

            return(new OrderRejected(
                       this.accountId,
                       orderId,
                       rejectedTime,
                       rejectReason,
                       this.NewGuid(),
                       this.TimeNow()));
        }
        private OrderModified GenerateOrderModifiedEvent(ExecutionReport message)
        {
            var orderId       = this.GetOrderId(message);
            var orderIdBroker = new OrderIdBroker(message.GetField(Tags.OrderID));
            var orderType     = FxcmMessageHelper.GetOrderType(message.GetField(Tags.OrdType));
            var quantity      = message.IsSetField(Tags.LeavesQty)
                ? Quantity.Create(message.GetDecimal(Tags.LeavesQty))
                : Quantity.Create(message.GetDecimal(Tags.OrderQty));
            var price        = FxcmMessageHelper.GetOrderPrice(orderType, message);
            var modifiedTime = FxcmMessageHelper.ParseTimestamp(message.GetField(Tags.TransactTime));

            return(new OrderModified(
                       this.accountId,
                       orderId,
                       orderIdBroker,
                       quantity,
                       price,
                       modifiedTime,
                       this.NewGuid(),
                       this.TimeNow()));
        }
        private OrderWorking GenerateOrderWorkingEvent(ExecutionReport message)
        {
            var orderId       = this.GetOrderId(message);
            var orderIdBroker = new OrderIdBroker(message.GetField(Tags.OrderID));
            var symbol        = this.GetSymbol(message.GetField(Tags.Symbol));
            var orderSide     = FxcmMessageHelper.GetOrderSide(message.GetField(Tags.Side));
            var orderType     = FxcmMessageHelper.GetOrderType(message.GetField(Tags.OrdType));
            var quantity      = Quantity.Create(message.GetDecimal(Tags.OrderQty));
            var price         = FxcmMessageHelper.GetOrderPrice(orderType, message);
            var timeInForce   = FxcmMessageHelper.GetTimeInForce(message.GetField(Tags.TimeInForce));
            var expireTime    = FxcmMessageHelper.GetExpireTime(message);
            var workingTime   = FxcmMessageHelper.ParseTimestamp(message.GetField(Tags.TransactTime));

            return(new OrderWorking(
                       this.accountId,
                       orderId,
                       orderIdBroker,
                       symbol,
                       orderSide,
                       orderType,
                       quantity,
                       price,
                       timeInForce,
                       expireTime,
                       workingTime,
                       this.NewGuid(),
                       this.TimeNow()));
        }
 private static string ObtenerIdTransaccionContraparte(ExecutionReport reporteEjecucion)
 {
     return(reporteEjecucion.GetField(new NumericOrderID(NumericOrderID.NumericOrderIDTag)).getValue());
 }
        public override object GetField(Fields field)
        {
            if (ExecutionReport == null)
            {
                return(ExecutionReportFields.NULL);
            }

            if (field == Fields.KEY)
            {
                return(Key);
            }
            else
            {
                ExecutionReportFields xrField = (ExecutionReportFields)field;

                if (xrField == ExecutionReportFields.OrderID)
                {
                    return(GetOrdId(ExecutionReport, QuickFix.Fields.Tags.OrderID));
                }
                else if (xrField == ExecutionReportFields.ClOrdID)
                {
                    return(GetOrdId(ExecutionReport, QuickFix.Fields.Tags.ClOrdID));
                }
                else if (xrField == ExecutionReportFields.OrigClOrdID)
                {
                    return(GetOrdId(ExecutionReport, QuickFix.Fields.Tags.OrigClOrdID));
                }
                else if (xrField == ExecutionReportFields.ExecType)
                {
                    return(GetExecType(ExecutionReport.GetChar(QuickFix.Fields.Tags.ExecType)));
                }
                else if (xrField == ExecutionReportFields.ExecID)
                {
                    return(ExecutionReport.GetString(QuickFix.Fields.Tags.ExecID));
                }
                else if (xrField == ExecutionReportFields.OrdStatus)
                {
                    return(GetOrdStatus(ExecutionReport.GetChar(QuickFix.Fields.Tags.OrdStatus)));
                }
                else if (xrField == ExecutionReportFields.OrdRejReason)
                {
                    return(FixHelper.GetNullIntFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.OrdRejReason));
                }
                else if (xrField == ExecutionReportFields.LeavesQty)
                {
                    return(ExecutionReport.GetInt(QuickFix.Fields.Tags.LeavesQty));
                }
                else if (xrField == ExecutionReportFields.CumQty)
                {
                    return(ExecutionReport.GetInt(QuickFix.Fields.Tags.CumQty));
                }
                else if (xrField == ExecutionReportFields.AvgPx)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.AvgPx));
                }
                else if (xrField == ExecutionReportFields.Commission)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.Commission));
                }
                else if (xrField == ExecutionReportFields.Text)
                {
                    return(ExecutionReport.GetField(QuickFix.Fields.Tags.Text));
                }
                else if (xrField == ExecutionReportFields.TransactTime)
                {
                    return(DateTime.Now);
                }
                else if (xrField == ExecutionReportFields.LastQty)
                {
                    return(FixHelper.GetNullIntFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.LastQty));
                }
                else if (xrField == ExecutionReportFields.LastPx)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.LastPx));
                }
                else if (xrField == ExecutionReportFields.LastMkt)
                {
                    return(FixHelper.GetNullFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.LastMkt));
                }


                else if (xrField == ExecutionReportFields.Symbol)
                {
                    return(FixHelper.GetNullFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.Symbol));
                }
                else if (xrField == ExecutionReportFields.OrderQty)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.OrderQty));
                }
                else if (xrField == ExecutionReportFields.CashOrderQty)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.CashOrderQty));
                }
                else if (xrField == ExecutionReportFields.OrdType)
                {
                    return(GetOrdType(ExecutionReport.GetChar(QuickFix.Fields.Tags.OrdType)));
                }
                else if (xrField == ExecutionReportFields.Price)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.Price));
                }
                else if (xrField == ExecutionReportFields.StopPx)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.StopPx));
                }
                else if (xrField == ExecutionReportFields.Currency)
                {
                    return(FixHelper.GetNullFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.Currency));
                }
                else if (xrField == ExecutionReportFields.ExpireDate)
                {
                    return(FixHelper.GetDateTimeFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.ExpireDate));
                }
                else if (xrField == ExecutionReportFields.MinQty)
                {
                    return(FixHelper.GetNullDoubleFieldIfSet(ExecutionReport, QuickFix.Fields.Tags.MinQty));
                }
                else if (xrField == ExecutionReportFields.Side)
                {
                    GetSide(ExecutionReport.GetChar(QuickFix.Fields.Tags.Side));
                }
                else if (xrField == ExecutionReportFields.QuantityType)
                {
                    return(QuantityType.SHARES);
                }
                else if (xrField == ExecutionReportFields.PriceType)
                {
                    return(PriceType.FixedAmount);
                }
                else if (xrField == ExecutionReportFields.Account)
                {
                    return(ExecutionReport.GetField(QuickFix.Fields.Tags.Account));
                }
                else if (xrField == ExecutionReportFields.ExecInst)
                {
                    return(ExecutionReport.GetField(QuickFix.Fields.Tags.ExecInst));
                }
            }

            return(ExecutionReportFields.NULL);
        }
        public void OnMessage(ExecutionReport message)
        {
            Debug.NotNull(this.tradingGateway, nameof(this.tradingGateway));

            switch (message.OrdStatus.Obj)
            {
            case OrdStatus.REJECTED:
            {
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.REJECTED)})");

                this.tradingGateway?.Send(this.GenerateOrderRejectedEvent(message));
                break;
            }

            case OrdStatus.PENDING_NEW:
            {
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.PENDING_NEW)}).");

                // Do nothing
                break;
            }

            case OrdStatus.NEW:
            {
                var fxcmOrdStatus = message.GetField(FxcmTags.OrdStatus);
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.NEW)}-{fxcmOrdStatus})");

                switch (fxcmOrdStatus)
                {
                case "P":         // In Process
                    this.tradingGateway?.Send(this.GenerateOrderAcceptedEvent(message));
                    this.tradingGateway?.Send(this.GenerateOrderWorkingEvent(message));
                    break;

                case "I":         // Dealer Intervention
                    this.tradingGateway?.Send(this.GenerateOrderAcceptedEvent(message));
                    this.tradingGateway?.Send(this.GenerateOrderWorkingEvent(message));
                    break;

                case "W":         // Waiting (conditional order inactive state)
                    if (message.IsSetField(Tags.SecondaryOrderID))
                    {
                        // Accepted Conditional Order
                        this.tradingGateway?.Send(this.GenerateOrderAcceptedEvent(message));
                    }
                    else
                    {
                        // Working Primary Order
                        this.tradingGateway?.Send(this.GenerateOrderWorkingEvent(message));
                    }

                    break;

                default:
                    this.Logger.LogError(LogId.Network, $"Cannot process event (FXCMOrdStatus {fxcmOrdStatus} not recognized).");
                    break;
                }

                break;
            }

            case OrdStatus.PENDING_CANCEL:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.PENDING_CANCEL)}).");
#endif

                // Do nothing
                break;
            }

            case OrdStatus.CANCELED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.CANCELED)})");
#endif

                this.tradingGateway?.Send(this.GenerateOrderCancelledEvent(message));
                break;
            }

            case OrdStatus.REPLACED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.REPLACED)})");
#endif

                this.tradingGateway?.Send(this.GenerateOrderModifiedEvent(message));
                break;
            }

            case OrdStatus.EXPIRED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.EXPIRED)})");
#endif

                this.tradingGateway?.Send(this.GenerateOrderExpiredEvent(message));
                break;
            }

            case OrdStatus.STOPPED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.STOPPED)}).");
#endif

                // Order is executing
                break;
            }

            case OrdStatus.FILLED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.FILLED)})");
#endif

                this.tradingGateway?.Send(this.GenerateOrderFilledEvent(message));
                break;
            }

            case OrdStatus.PARTIALLY_FILLED:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.PARTIALLY_FILLED)})");
#endif

                this.tradingGateway?.Send(this.GenerateOrderPartiallyFilledEvent(message));
                break;
            }

            case OrdStatus.SUSPENDED:
            {
                this.Logger.LogError(LogId.Network, $"{Received}{Fix} Unhandled {nameof(ExecutionReport)}({nameof(OrdStatus.SUSPENDED)}).");
                break;
            }

            case OrdStatus.CALCULATED:
            {
                this.Logger.LogError(LogId.Network, $"{Received}{Fix} Unhandled {nameof(ExecutionReport)}({nameof(OrdStatus.CALCULATED)}).");
                break;
            }

            case OrdStatus.DONE_FOR_DAY:
            {
#if DEBUG
                this.Logger.LogDebug(LogId.Network, $"{Received}{Fix} {nameof(ExecutionReport)}({nameof(OrdStatus.DONE_FOR_DAY)}).");
#endif

                this.tradingGateway?.Send(this.GenerateOrderExpiredEvent(message));
                break;
            }

            case OrdStatus.PENDING_REPLACE:
            {
                this.Logger.LogError(LogId.Network, $"{Received}{Fix} Unhandled {nameof(ExecutionReport)}({nameof(OrdStatus.PENDING_REPLACE)}).");
                break;
            }

            case OrdStatus.ACCEPTED_FOR_BIDDING:
            {
                this.Logger.LogError(LogId.Network, $"{Received}{Fix} Unhandled {nameof(ExecutionReport)}({nameof(OrdStatus.ACCEPTED_FOR_BIDDING)}).");
                break;
            }

            default:
                throw ExceptionFactory.InvalidSwitchArgument(message.OrdStatus, nameof(message.OrdStatus));
            }
        }
Beispiel #9
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);
 }
Beispiel #10
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);
            }
        }