Ejemplo n.º 1
0
 public HomeBrokerHandlerLivroOfertaAgregado(int clientNumber, Socket clientSocket)
     : base(clientNumber, clientSocket)
 {
     logger       = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     myThreadName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
     MDSUtils.AddAppender("HomeBrokerHandlerLivroOfertaAgregado-", logger.Logger);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="evtCache"></param>
        private void flushEventCache(EventoHttpLivroOfertasAgregado evtCache)
        {
            string mensagem = null;

            try
            {
                mensagem = JsonConvert.SerializeObject(evtCache);
                mensagem = MDSUtils.montaMensagemHttp(ConstantesMDS.TIPO_REQUISICAO_LIVRO_OFERTAS_AGREGADO, evtCache.instrumento, null, mensagem);

                bool bsinaliza = false;
                lock (objLockSnapshot)
                {
                    if (!String.IsNullOrEmpty(mensagem))
                    {
                        bsinaliza = queueToStreamer.IsEmpty;
                        queueToStreamer.Enqueue(mensagem);
                    }
                }

                if (bsinaliza)
                {
                    lock (syncQueueToStreamer)
                    {
                        Monitor.Pulse(syncQueueToStreamer);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("flushEventCache(): " + ex.Message, ex);
            }
        }
        protected override void trataAssinatura(string tipo, string instrumento, string sessionID)
        {
            string mensagem = "";
            NegociosConsumerBase negociosConsumer = ContainerManager.Instance.NegociosConsumer;

            logger.DebugFormat("{0} assinatura de {1} de {2}", sessionID, tipo, instrumento);

            EventoHttpNegocio httpNEG = negociosConsumer.SnapshotStreamerNegocio(instrumento);

            if (httpNEG != null)
            {
                Dictionary <string, string> cabecalho = MDSUtils.montaCabecalhoStreamer(tipo, null, ConstantesMDS.HTTP_OFERTAS_TIPO_ACAO_COMPLETO, instrumento, negociosConsumer.RetornaCasasDecimais(instrumento), sessionID);

                httpNEG.cabecalho = cabecalho;

                mensagem = JsonConvert.SerializeObject(httpNEG);
                mensagem = MDSUtils.montaMensagemHttp(ConstantesMDS.TIPO_REQUISICAO_NEGOCIOS, instrumento, null, mensagem);

                logger.Debug("SNAP Negocio[" + httpNEG.instrumento + "]: " + mensagem);

                bool sinaliza = queueToStreamer.IsEmpty;
                queueToStreamer.Enqueue(mensagem);

                if (sinaliza)
                {
                    lock (syncQueueToStreamer)
                    {
                        Monitor.Pulse(syncQueueToStreamer);
                    }
                }
            }
        }
        protected override void trataAssinatura(string tipo, string instrumento, string sessionID)
        {
            string mensagem  = "";
            bool   bsinaliza = false;
            LivroOfertasConsumerBase lofConsumer = ContainerManager.Instance.LivroOfertasConsumer;

            logger.DebugFormat("{0} assinatura de {1} de {2}", sessionID, tipo, instrumento);

            // Aqui tem o pulo do gato
            // interrompe o processamento dos eventos ate a chegada do snapshot
            // para nao quebrar a sequencia do sinal do livro
            lock (objLockSnapshot)
            {
                EventoHttpLivroOfertasAgregado httpLOA;
                httpLOA = lofConsumer.SnapshotStreamerLivroAgregado(instrumento, sessionID);

                logger.Debug("Snapshot LOA de " + instrumento + ": " + httpLOA.livroCompra.Count + "C/" + httpLOA.livroVenda.Count + "V items");

                mensagem = JsonConvert.SerializeObject(httpLOA);
                mensagem = MDSUtils.montaMensagemHttp(ConstantesMDS.TIPO_REQUISICAO_LIVRO_OFERTAS_AGREGADO, instrumento, null, mensagem);

                bsinaliza = queueToStreamer.IsEmpty;
                queueToStreamer.Enqueue(mensagem);
            }

            if (bsinaliza)
            {
                lock (syncQueueToStreamer)
                {
                    Monitor.Pulse(syncQueueToStreamer);
                }
            }
        }
 public StreamerClientHandlerLivroNegocios(int clientNumber, Socket clientSocket)
     : base(clientNumber, clientSocket)
 {
     logger       = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     myThreadName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
     MDSUtils.AddAppender("StreamerClientHandlerLivroNegocios-", logger.Logger);
 }
        private void despacharEventos(object sender, HttpNegocioEventArgs args)
        {
            try
            {
                string            mensagem = null;
                EventoHttpNegocio httpNEG  = args.Evento;


                if (dctSessions.ContainsKey(httpNEG.instrumento))
                {
                    mensagem = JsonConvert.SerializeObject(httpNEG);
                    mensagem = MDSUtils.montaMensagemHttp(ConstantesMDS.TIPO_REQUISICAO_NEGOCIOS, httpNEG.instrumento, null, mensagem);

                    logger.Debug("INCR Negocio[" + httpNEG.instrumento + "]: " + mensagem);

                    if (!String.IsNullOrEmpty(mensagem))
                    {
                        queueToStreamer.Enqueue(mensagem);
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("despacharEventos(): " + ex.Message, ex);
            }
        }
Ejemplo n.º 7
0
 public AnaliseGraficaClientHandler(int clientNumber, Socket clientSocket)
 {
     this.ClientSocket = clientSocket;
     logger            = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     myThreadName      = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
     MDSUtils.AddAppender("AnaliseGraficaClientHandler", logger.Logger);
 }
        protected override void trataAssinatura(string tipo, string instrumento, string sessionID)
        {
            string mensagem = "";
            NegociosConsumerBase        negociosConsumer = ContainerManager.Instance.NegociosConsumer;
            Dictionary <string, string> cabecalho        = MDSUtils.montaCabecalhoStreamer(tipo, null, ConstantesMDS.HTTP_OFERTAS_TIPO_ACAO_COMPLETO, instrumento, negociosConsumer.RetornaCasasDecimais(instrumento), sessionID);

            logger.DebugFormat("{0} assinatura de {1} de {2}", sessionID, tipo, instrumento);

            // Aqui tem o pulo do gato
            // interrompe o processamento dos eventos ate a chegada do snapshot
            // para nao quebrar a sequencia do sinal do livro
            lock (objLockSnapshot)
            {
                EventoHttpLivroNegocios httpLNG;
                httpLNG           = negociosConsumer.SnapshotStreamerLivroNegocios(instrumento);
                httpLNG.cabecalho = cabecalho;

                logger.Debug("Snapshot LNG de " + instrumento + ": " + httpLNG.negocio.Count + " items");

                mensagem = JsonConvert.SerializeObject(httpLNG);
                mensagem = MDSUtils.montaMensagemHttp(ConstantesMDS.TIPO_REQUISICAO_LIVRO_NEGOCIOS, instrumento, null, mensagem);

                queueToStreamer.Enqueue(mensagem);
            }
        }
Ejemplo n.º 9
0
        public NewsConsumerBase(Dictionary <string, ChannelUDMF> dicCanais)
        {
            this.dicCanais = dicCanais;

            logger       = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            myThreadName = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
            MDSUtils.AddAppender("NewsConsumerBase-", logger.Logger);
        }
Ejemplo n.º 10
0
        protected void eventoUmdfThreadWork(object param)
        {
            EventoUmdfWorkerState workerstate = param as EventoUmdfWorkerState;
            long lastTick       = 0;
            long threadWatchDog = 0;

            if (workerstate != null)
            {
                logger.Info("Iniciando eventoUmdfThreadWork para channelID [" + workerstate.ChannelID + "]");

                while (bKeepRunning)
                {
                    if (MDSUtils.shouldLog(threadWatchDog, 30))
                    {
                        logger.Info("eventoUmdfThreadWork(" + workerstate.ChannelID + ") ativo");
                        threadWatchDog = DateTime.UtcNow.Ticks;
                    }

                    try
                    {
                        EventoUmdf evento;
                        if (workerstate.QueueEventos.TryDequeue(out evento))
                        {
                            //logger.InfoFormat("Processando mensagem UMDF [{0}]", evento.MsgSeqNum);

                            trataEventoUmdf(evento);

                            if (MDSUtils.shouldLog(lastTick))
                            {
                                logger.Info("eventoUmdfThreadWork(" + workerstate.ChannelID + ") msgs na fila: " + workerstate.QueueEventos.Count);
                                lastTick = DateTime.UtcNow.Ticks;
                            }

                            continue;
                        }

                        lock (workerstate.SyncObj)
                        {
                            Monitor.Wait(workerstate.SyncObj, 50);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("eventoUmdfThreadWork(" + workerstate.ChannelID + "): " + ex.Message, ex);
                    }
                }

                logger.Info("Finalizando eventoUmdfThreadWork para channelID [" + workerstate.ChannelID + "]");
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="param"></param>
        protected void messageFixThreadWork(object param)
        {
            FIXMessageWorkerState workerstate = param as FIXMessageWorkerState;
            long lastTick       = 0;
            long threadWatchDog = 0;

            if (workerstate != null)
            {
                logger.Info("Iniciando messageFixThreadWork para channelID [" + workerstate.ChannelID + "]");

                while (bKeepRunning)
                {
                    if (MDSUtils.shouldLog(threadWatchDog, 30))
                    {
                        logger.Info("messageFixThreadWork(" + workerstate.ChannelID + ") ativo");
                        threadWatchDog = DateTime.UtcNow.Ticks;
                    }

                    try
                    {
                        EventoFIX evento;
                        if (workerstate.QueueMensagens.TryDequeue(out evento))
                        {
                            trataMensagemFIX(evento);

                            if (MDSUtils.shouldLog(lastTick))
                            {
                                logger.Info("messageFixThreadWork(" + workerstate.ChannelID + ") msgs na fila: " + workerstate.QueueMensagens.Count);
                                lastTick = DateTime.UtcNow.Ticks;
                            }

                            continue;
                        }

                        lock (workerstate.SyncObjFIX)
                        {
                            Monitor.Wait(workerstate.SyncObjFIX, 50);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("messageFixThreadWork(" + workerstate.ChannelID + "): " + ex.Message, ex);
                    }
                }

                logger.Info("Finalizando messageFixThreadWork para channelID [" + workerstate.ChannelID + "]");
            }
        }
        protected override void queueProcessor()
        {
            logger.Info("Iniciando thread para otimizar eventos");

            thOtimizadorEventos      = new Thread(new ThreadStart(otimizadorEventos));
            thOtimizadorEventos.Name = "thOtimizadorEventos-";
            thOtimizadorEventos.Start();

            logger.Info("Iniciando processamento da fila de envio streamer de LOA");
            long lastLogTicks = 0;

            while (bKeepRunning)
            {
                try
                {
                    string msglof = null;
                    lock (objLockSnapshot)
                    {
                        if (queueToStreamer.TryDequeue(out msglof))
                        {
                            if (!String.IsNullOrEmpty(msglof))
                            {
                                SocketPackage.SendData(msglof, ClientSocket);
                            }

                            if (MDSUtils.shouldLog(lastLogTicks))
                            {
                                lastLogTicks = DateTime.UtcNow.Ticks;
                                logger.Info("Mensagens na fila: " + queueToStreamer.Count);
                            }
                            continue;
                        }
                    }

                    lock (syncQueueToStreamer)
                    {
                        Monitor.Wait(syncQueueToStreamer, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("queueProcessor(): " + ex.Message, ex);
                }
            }

            logger.Info("Finalizando processamento da fila de envio streamer de LOA");
        }
Ejemplo n.º 13
0
        protected virtual void processaMensagemFIX(EventoFIX evento)
        {
            // Se nao existe thread para tratar o evento, cria
            FIXMessageWorkerState workerState = null;

            if (evento == null)
            {
                logger.Error("Mensagem FIX nao pode ser nula");
                return;
            }

            if (String.IsNullOrEmpty(evento.ChannelID))
            {
                logger.Error("Eita porra....channelID nulo");
                return;
            }

            if (!poolFixWorkers.TryGetValue(evento.ChannelID, out workerState))
            {
                logger.Info("Criando worker para  channel [" + evento.ChannelID + "]");
                workerState             = new FIXMessageWorkerState();
                workerState.ChannelID   = evento.ChannelID;
                workerState.Thread      = new Thread(new ParameterizedThreadStart(messageFixThreadWork));
                workerState.Thread.Name = myThreadName + "-Worker-" + workerState.ChannelID;
                workerState.Thread.Start(workerState);

                poolFixWorkers.Add(evento.ChannelID, workerState);
            }

            bool bsinaliza = workerState.QueueMensagens.IsEmpty;

            workerState.QueueMensagens.Enqueue(evento);
            if (MDSUtils.shouldLog(workerState.lastEnqueueLog, 30))
            {
                logger.Info("processaMensagemFIX para channelID [" + workerState.ChannelID + "] fila:" + workerState.QueueMensagens.Count);
                workerState.lastEnqueueLog = DateTime.UtcNow.Ticks;
            }

            //if (bsinaliza)
            //{
            //    lock (workerState.SyncObjFIX)
            //    {
            //        Monitor.Pulse(workerState.SyncObjFIX);
            //    }
            //}
        }
Ejemplo n.º 14
0
        protected virtual void procRun()
        {
            logger.Info(myThreadName + " - iniciando procRun()");
            long threadWatchDog = 0;

            while (bKeepRunning)
            {
                if (MDSUtils.shouldLog(threadWatchDog, 30))
                {
                    logger.Info("procRun() ativo");
                    threadWatchDog = DateTime.UtcNow.Ticks;
                }

                try
                {
                    EventoUmdf evento;
                    if (queueEventos.TryDequeue(out evento))
                    {
                        //logger.InfoFormat("Distribuindo mensagem UMDF [{0}]", evento.MsgSeqNum);

                        processaEventoUmdf(evento);

                        if (MDSUtils.shouldLog(lastEventTicks))
                        {
                            logger.Info("EnqueueEventoUmdf - Mensagens na fila principal: " + queueEventos.Count);
                            lastEventTicks = DateTime.UtcNow.Ticks;
                        }

                        continue;
                    }

                    lock (SyncObj)
                    {
                        Monitor.Wait(SyncObj, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("procRun(): " + ex.Message, ex);
                }
            }

            logger.Info(myThreadName + " End of procRun()");
        }
Ejemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        protected virtual void procRunFix()
        {
            logger.Info(myThreadName + " - iniciando procRunFix()");

            long threadWatchDog = 0;

            while (bKeepRunning)
            {
                if (MDSUtils.shouldLog(threadWatchDog, 30))
                {
                    logger.Info("procRunFix() ativo");
                    threadWatchDog = DateTime.UtcNow.Ticks;
                }

                try
                {
                    EventoFIX evento;
                    if (queueFIX.TryDequeue(out evento))
                    {
                        processaMensagemFIX(evento);

                        if (MDSUtils.shouldLog(lastEventTicks))
                        {
                            logger.Info("procRunFix - Mensagens na fila principal: " + queueFIX.Count);
                            lastEventTicks = DateTime.UtcNow.Ticks;
                        }

                        continue;
                    }

                    lock (SyncObjFix)
                    {
                        Monitor.Wait(SyncObjFix, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("procRunFix(): " + ex.Message, ex);
                }
            }

            logger.Info(myThreadName + " End of procRunFix()");
        }
Ejemplo n.º 16
0
        //protected override EPStatement createStatement(string tipo, string instrumento)
        //{
        //    try
        //    {
        //        string consultaEsper = "";

        //        consultaEsper = "select * from EventoHttpNegocio where instrumento='" + instrumento + "'";

        //        consultaEsper += " output all every 1 msec";

        //        EPStatement comandoEsper = NesperManager.Instance.epService.EPAdministrator.CreateEPL(consultaEsper);
        //        comandoEsper.Events += new UpdateEventHandler(eventUpdateHandler);

        //        logger.Debug("Consulta [" + consultaEsper + "] cadastrada no ESPER!");

        //        return comandoEsper;
        //    }
        //    catch (EPException epex)
        //    {
        //        logger.Error("Exception in createEPL - " + epex.Message, epex);
        //    }
        //    catch (Exception ex)
        //    {
        //        logger.Error("Error in CreateStatement() " + ex.Message, ex);
        //    }

        //    return null;
        //}


        protected override void queueProcessor()
        {
            logger.Info("Iniciando processamento da fila de envio streamer de Negocios");
            long lastLogTicks = 0;

            while (bKeepRunning)
            {
                try
                {
                    string msgneg = null;

                    if (queueToStreamer.TryDequeue(out msgneg))
                    {
                        if (!String.IsNullOrEmpty(msgneg))
                        {
                            SocketPackage.SendData(msgneg, ClientSocket);
                        }

                        if (MDSUtils.shouldLog(lastLogTicks))
                        {
                            lastLogTicks = DateTime.UtcNow.Ticks;
                            logger.Info("Mensagens na fila: " + queueToStreamer.Count);
                        }

                        continue;
                    }

                    lock (syncQueueToStreamer)
                    {
                        Monitor.Wait(syncQueueToStreamer, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("queueProcessor(): " + ex.Message, ex);
                }
            }

            logger.Info("Finalizando processamento da fila de envio streamer de Negocios");
        }
Ejemplo n.º 17
0
        protected void queueProcessor()
        {
            logger.Info("Iniciando processamento da fila de envio Analise Grafica");
            long lastLogTicks = 0;

            while (bKeepRunning)
            {
                try
                {
                    string msgNEG = null;
                    if (queueToAnaliseGrafica.TryDequeue(out msgNEG))
                    {
                        SocketPackage.SendData(msgNEG, ClientSocket);

                        if (MDSUtils.shouldLog(lastLogTicks))
                        {
                            lastLogTicks = DateTime.UtcNow.Ticks;
                            logger.Info("Fila de eventos : " + queueToAnaliseGrafica.Count);
                        }
                        logger.DebugFormat("Mensagem [{0}]", msgNEG);

                        continue;
                    }

                    lock (syncQueueToAnaliseGrafica)
                    {
                        Monitor.Wait(syncQueueToAnaliseGrafica, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("queueProcessor(): " + ex.Message, ex);
                }
            }

            logger.Info("Finalizando processamento da fila de envio home broker de Negocios");
        }
Ejemplo n.º 18
0
        protected void queueProcessor()
        {
            logger.Info("Iniciando processamento da fila de envio home broker de livro de ofertas agregado");
            long lastLogTicks = 0;

            while (bKeepRunning)
            {
                try
                {
                    string msgLOA = null;
                    if (queueToHomeBroker.TryDequeue(out msgLOA))
                    {
                        SocketPackage.SendData(msgLOA, ClientSocket);

                        if (MDSUtils.shouldLog(lastLogTicks))
                        {
                            lastLogTicks = DateTime.UtcNow.Ticks;
                            logger.Info("Fila de eventos : " + queueToHomeBroker.Count);
                        }

                        continue;
                    }

                    lock (syncObj)
                    {
                        Monitor.Wait(syncObj, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("queueProcessor(): " + ex.Message, ex);
                }
            }

            logger.Info("Finalizando processamento da fila de envio home broker de livro de ofertas");
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Monta a string da mensagem de negocio pra envio ao HomeBroker
        /// </summary>
        /// <param name="registroNegocio"></param>
        /// <returns></returns>
        public static string montarNegocioHomeBroker(NegocioBase registroNegocio)
        {
            StringBuilder   builder = new StringBuilder();
            NEGDadosNegocio negocio = registroNegocio.Negocio;


            builder.Append(MDSUtils.montaHeaderHomeBroker(registroNegocio.Instrumento,
                                                          ConstantesMDS.TIPO_REQUISICAO_HB_NEGOCIO, registroNegocio.TipoBolsa));

            // Corpo da mensagem MDS de Negocio
            if (String.IsNullOrEmpty(negocio.Data))
            {
                builder.Append("00000000");
            }
            else
            {
                builder.Append(negocio.Data);
            }

            if (String.IsNullOrEmpty(negocio.Hora))
            {
                builder.Append("000000000");
            }
            else
            {
                builder.Append(negocio.Hora.PadRight(9, '0'));
            }

            if (String.IsNullOrEmpty(negocio.Compradora))
            {
                builder.Append("00000000");
            }
            else
            {
                builder.Append(negocio.Compradora.PadLeft(8, '0'));
            }

            if (String.IsNullOrEmpty(negocio.Vendedora))
            {
                builder.Append("00000000");
            }
            else
            {
                builder.Append(negocio.Vendedora.PadLeft(8, '0'));
            }

            if (negocio.Preco < 0)
            {
                builder.Append("000000000,000");
            }
            else
            {
                builder.Append(negocio.Preco.ToString("000000000.000").Replace('.', ','));
            }

            builder.Append(negocio.Quantidade.ToString().PadLeft(12, '0'));

            if (negocio.PrecoMaximo < 0)
            {
                builder.Append("000000000,000");
            }
            else
            {
                builder.Append(negocio.PrecoMaximo.ToString("000000000.000").Replace('.', ','));
            }

            if (negocio.PrecoMinimo < 0)
            {
                builder.Append("000000000,000");
            }
            else
            {
                builder.Append(negocio.PrecoMinimo.ToString("000000000.000").Replace('.', ','));
            }


            //BigDecimal volumeTotal = new BigDecimal(0);
            //try
            //{
            //    if (dadosInstrumentos.getTipoBolsa().equals(ConstantesMDS.DESCRICAO_DE_BOLSA_BMF))
            //    {
            //        if (dadosInstrumentos.getPrecoMedio() != null && !dadosInstrumentos.getPrecoMedio().trim().isEmpty())
            //        {
            //            BigDecimal precoMedio = new BigDecimal(
            //                    dadosInstrumentos.getPrecoMedio().replace(',', '.'));
            //            if (!precoMedio.equals(new BigDecimal(0)))
            //            {
            //                volumeTotal = dadosInstrumentos.getVolumeTotal().
            //                    divide(precoMedio, 6, RoundingMode.HALF_UP);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        volumeTotal = dadosInstrumentos.getVolumeTotal();
            //    }
            //}
            //catch (Exception ex) { }

            //builder.Append(String.format("%013d", volumeTotal.longValue()));
            builder.Append(negocio.VolumeTotal.ToString("0000000000000", CultureInfo.InvariantCulture));

            builder.Append(negocio.QtdeNegocios.ToString().PadLeft(8, '0'));

            Decimal variacao = Math.Abs(negocio.Variacao);

            if (negocio.Variacao >= Decimal.Zero)
            {
                builder.Append(" ");
            }
            else
            {
                builder.Append("-");
            }

            if (variacao > 99999 || variacao < -99999)
            {
                builder.Append("00000,00");
            }
            else
            {
                builder.Append(variacao.ToString("00000.00", CultureInfo.InvariantCulture).Replace('.', ','));
            }

            builder.Append(negocio.EstadoInstrumento.ToString());

            if (negocio.MelhorQuantidadeCompra < 0)
            {
                builder.Append("000000000000");
            }
            else
            {
                builder.Append(negocio.MelhorQuantidadeCompra.ToString().PadLeft(12, '0'));
            }

            if (negocio.MelhorQuantidadeVenda < 0)
            {
                builder.Append("000000000000");
            }
            else
            {
                builder.Append(negocio.MelhorQuantidadeVenda.ToString().PadLeft(12, '0'));
            }

            builder.Append(negocio.QtdeNegociadaDia.ToString().PadLeft(12, '0'));


            builder.Append(negocio.PrecoMedio.ToString("000000000.000", CultureInfo.InvariantCulture).Replace('.', ','));
            // Dados do Leilao
            builder.Append(negocio.PrecoTeoricoAbertura.ToString("000000000.000", CultureInfo.InvariantCulture).Replace('.', ','));

            if (negocio.Variacao >= Decimal.Zero)
            {
                builder.Append(" ");
            }
            else
            {
                builder.Append("-");
            }
            variacao = Math.Abs(negocio.VariacaoTeorica);

            builder.Append(variacao.ToString("00000.00", CultureInfo.InvariantCulture).Replace('.', ','));
            builder.Append(negocio.HorarioTeorico.ToString("yyyyMMddHHmmss"));

            return(builder.ToString());
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Monta a string da mensagem de negocio pra envio ao HomeBroker
        /// </summary>
        /// <param name="registroNegocio"></param>
        /// <returns></returns>
        public static string montarLivroNegociosHomeBroker(NegocioBase registroNegocio)
        {
            StringBuilder   builder = new StringBuilder();
            NEGDadosNegocio negocio = registroNegocio.Negocio;


            builder.Append(MDSUtils.montaHeaderHomeBroker(registroNegocio.Instrumento,
                                                          ConstantesMDS.TIPO_REQUISICAO_HB_LIVRO_NEGOCIOS, registroNegocio.TipoBolsa));

            int numItens    = 30; //TODO: parametrizar
            int posicaoItem = 0;

            while (posicaoItem < numItens &&
                   posicaoItem < registroNegocio.LivroNegocios.Count)
            {
                LNGDadosNegocio item = registroNegocio.LivroNegocios[posicaoItem];

                if (item != null)
                {
                    if (!String.IsNullOrEmpty(item.NumeroNegocio))
                    {
                        builder.Append(item.NumeroNegocio.PadLeft(8, '0'));
                    }
                    else
                    {
                        builder.Append("00000000");
                    }

                    if (!String.IsNullOrEmpty(item.Hora))
                    {
                        builder.Append(item.Hora.PadLeft(6, '0'));
                    }
                    else
                    {
                        builder.Append("000000");
                    }

                    builder.Append(item.Preco.ToString("0000000000.00"));
                    builder.Append(String.Format("{0:d12}", item.Quantidade));

                    if (!String.IsNullOrEmpty(item.Compradora))
                    {
                        builder.Append(item.Compradora.PadLeft(8, '0'));
                    }
                    else
                    {
                        builder.Append("00000000");
                    }

                    if (!String.IsNullOrEmpty(item.Vendedora))
                    {
                        builder.Append(item.Vendedora.PadLeft(8, '0'));
                    }
                    else
                    {
                        builder.Append("00000000");
                    }
                }

                posicaoItem++;
            }

            return(builder.ToString());
        }
        private void otimizadorEventos()
        {
            logger.Info("Iniciando otimizacao de eventos");
            long   lastLogTicks         = 0;
            long   lastOtimizationTicks = 0;
            string lastInstrumento      = null;

            EventoHttpLivroOfertasAgregado evtCache = null;

            while (bKeepRunning)
            {
                try
                {
                    EventoHttpLivroOfertasAgregado evento;
                    if (queueEventosLOA.TryDequeue(out evento))
                    {
                        // Se houver cache, descarrega
                        if (!String.IsNullOrEmpty(lastInstrumento))
                        {
                            if (!lastInstrumento.Equals(evento.instrumento))
                            {
                                flushEventCache(evtCache);
                                lastInstrumento = null;
                                evtCache        = null;
                            }
                        }

                        // Se cache vazio, cria um novo cache
                        if (String.IsNullOrEmpty(lastInstrumento))
                        {
                            lastInstrumento      = evento.instrumento;
                            evtCache             = new EventoHttpLivroOfertasAgregado();
                            evtCache.cabecalho   = evento.cabecalho;
                            evtCache.instrumento = evento.instrumento;
                            evtCache.livroCompra = new List <Dictionary <string, string> >();
                            evtCache.livroVenda  = new List <Dictionary <string, string> >();
                        }

                        // Se for igual, acrescenta as operacoes de livro no final
                        if (lastInstrumento.Equals(evento.instrumento))
                        {
                            if (evento.livroCompra != null && evento.livroCompra.Count > 0)
                            {
                                evtCache.livroCompra.AddRange(evento.livroCompra);
                            }

                            if (evento.livroVenda != null && evento.livroVenda.Count > 0)
                            {
                                evtCache.livroVenda.AddRange(evento.livroVenda);
                            }
                        }

                        if (MDSUtils.shouldLog(lastLogTicks))
                        {
                            lastLogTicks = DateTime.UtcNow.Ticks;
                            logger.Info("Fila de eventos a serem otimizados: " + queueEventosLOA.Count);
                        }

                        continue;
                    }

                    // Se a fila estiver vazia e estourar o timeout, descarrega o cache
                    //if (!String.IsNullOrEmpty(lastInstrumento) && (DateTime.UtcNow.Ticks - lastOtimizationTicks) > TimeSpan.TicksPerMillisecond)
                    if (!String.IsNullOrEmpty(lastInstrumento))
                    {
                        flushEventCache(evtCache);
                        lastInstrumento = null;
                        evtCache        = null;

                        continue;
                    }

                    lock (syncQueueEventosLOA)
                    {
                        Monitor.Wait(syncQueueEventosLOA, 50);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("otimizadorEventos(): " + ex.Message, ex);
                }
            }
        }