Beispiel #1
0
        private void Run()
        {
            long antes;
            long depois;

            while (_bKeepRunning)
            {
                MarketDataIncrementalRefresh mensagem;
                try
                {
                    mensagem = filaMensagensFIX.Pop();
                }
                catch (Exception e)
                {
                    logger.Error("Falha na leitura da fila: " + e.Message);
                    break;
                }

                antes = DateTime.Now.Ticks;

                trataMensagemFIX(mensagem);

                depois = DateTime.Now.Ticks;
                TimeSpan elapsed = new TimeSpan(depois - antes);
                logger.Debug("Duracao: " + elapsed.TotalMilliseconds +
                             " ms (Mensagens na fila: " + filaMensagensFIX.Count + ")");
            }
        }
Beispiel #2
0
        public void TestPerformance()
        {
            int numEvents  = 1;
            int numThreads = 2;

            Configuration config = new Configuration();

            config.EngineDefaults.Threading.IsListenerDispatchPreserveOrder = false;
            EPServiceProvider engine = EPServiceProviderManager.GetDefaultProvider(config);

            engine.EPAdministrator.Configuration.AddEventType(typeof(TransactionEvent));
            engine.EPAdministrator.Configuration.AddPlugInSingleRowFunction("MyDynModel", GetType().FullName, "MyDynModel");

            String      epl  = "select MyDynModel({Col_001, Col_002, Col_003}) as model_score from TransactionEvent";
            EPStatement stmt = engine.EPAdministrator.CreateEPL(epl);

            stmt.Subscriber = new MySubscriber();

            var queue = new LinkedBlockingQueue <Runnable>();
            var latch = new CountDownLatch(numEvents);

            for (int i = 0; i < numEvents; i++)
            {
                queue.Push((new MyRunnable(engine.EPRuntime, latch, new TransactionEvent(1, 2, 3))).Run);
            }

            var threads = Executors.NewFixedThreadPool(numThreads);

            var delta = PerformanceObserver.TimeMillis(
                () =>
            {
                for (int ii = 0; ii < numThreads; ii++)
                {
                    threads.Submit(
                        () =>
                    {
                        Runnable runnable;
                        while (queue.Pop(0, out runnable))
                        {
                            runnable.Invoke();
                        }
                    });
                }


                //ThreadPoolExecutor threads = new ThreadPoolExecutor(numThreads, numThreads, 10, TimeUnit.SECONDS, queue);
                //threads.PrestartAllCoreThreads();
                latch.Await(TimeSpan.FromMinutes(1));
                if (latch.Count > 0)
                {
                    throw new Exception("Failed to complete in 1 minute");
                }
            });

            Console.WriteLine("Took " + delta + " millis");
            threads.Shutdown();
            threads.AwaitTermination(TimeSpan.FromSeconds(10));
        }
Beispiel #3
0
        private void Run()
        {
            string    linha;
            EventoBMF evento;
            long      antes;
            long      depois;

            while (_bKeepRunning)
            {
                linha = null;
                try
                {
                    linha = filaMensagensRetransmissorBMF.Pop();
                }
                catch (Exception intExcept)
                {
                    logger.Error("InterruptedException na leitura da fila de mensagens:");
                    logger.Debug(intExcept.Message);
                    return;
                }
                antes = DateTime.Now.Ticks;

                string sequencia = linha.Substring(
                    EventoBMF.SEQNUM_INI,
                    EventoBMF.SEQNUM_FIM - EventoBMF.SEQNUM_INI).Trim();
                string tipo = linha.Substring(
                    EventoBMF.TYPE_INI,
                    EventoBMF.TYPE_FIM - EventoBMF.TYPE_INI).Trim();
                string instrumento = linha.Substring(
                    EventoBMF.SYMBOL_INI,
                    EventoBMF.SYMBOL_FIM - EventoBMF.SYMBOL_INI).Trim();
                string codigoInstrumento = linha.Substring(
                    EventoBMF.SECURITYID_INI,
                    EventoBMF.SECURITYID_FIM - EventoBMF.SECURITYID_INI).Trim();
                string mensagem = linha.Substring(
                    EventoBMF.BODY_INI);

                if (tipo.Equals(ConstantesMDS.TIPO_REQUISICAO_BMF_HEARTBEAT))
                {
                    continue;
                }

                evento = new EventoBMF(sequencia, tipo, instrumento, codigoInstrumento, mensagem);
                epService.EPRuntime.SendEvent(evento);

                depois = DateTime.Now.Ticks;
                TimeSpan elapsed = new TimeSpan(depois - antes);
                logger.Debug("Mensagem[" + linha + "] Duracao: " + elapsed.TotalMilliseconds + "ms");
            }
        }
Beispiel #4
0
 public void Next()
 {
     var next = emittables.Pop();
     if (next is EPDataFlowSignal)
     {
         var signal = (EPDataFlowSignal) next;
         graphContext.SubmitSignal(signal);
     }
     else if (next is PortAndMessagePair)
     {
         var pair = (PortAndMessagePair) next;
         graphContext.SubmitPort(pair.Port, pair.Message);
     }
     else
     {
         graphContext.Submit(next);
     }
 }
Beispiel #5
0
        public void Run()
        {
            try
            {
                logger.Info("*** Iniciado Retransmissor BMF!");



                // Cria sessao que será usada para mandar as mensagens
                SessionID _session =
                    new SessionID(
                        new BeginString(_config.BeginString),
                        new SenderCompID(_config.SenderCompID),
                        new TargetCompID(_config.TargetCompID));

                // Cria dicionario da configuracao
                Dictionary mainDic = new Dictionary();

                mainDic.setLong("SocketConnectPort", _config.SocketConnectPort);
                mainDic.setLong("HeartBtInt", _config.HeartBtInt);
                mainDic.setLong("ReconnectInterval", _config.ReconnectInterval);

                mainDic.setBool("ResetOnLogon", _config.ResetSeqNum);
                mainDic.setBool("PersistMessages", _config.PersistMessages);

                // Ver
                // ret.setString("ConnectionType", ConnectionType.ToLower());
                mainDic.setString("SocketConnectHost", _config.Host);
                mainDic.setString("FileStorePath", _config.FileStorePath);

                logger.Debug("FileLogPath: " + _config.FileLogPath);

                mainDic.setString("FileLogPath", _config.FileLogPath);
                mainDic.setString("StartTime", _config.StartTime);
                mainDic.setString("EndTime", _config.EndTime);
                mainDic.setString("ConnectionType", "initiator");

                Dictionary sessDic = new Dictionary();

                sessDic.setString("BeginString", _config.BeginString);
                sessDic.setString("SenderCompID", _config.SenderCompID);
                sessDic.setString("TargetCompID", _config.TargetCompID);
                sessDic.setString("DataDictionary", _config.DataDictionary);
                sessDic.setBool("UseDataDictionary", true);

                if (_config.RawData != null && _config.RawData.Length > 0)
                {
                    sessDic.setString(SessaoFIX.FIX_RAWDATA, _config.RawData);
                }

                if (_config.NewPassword != null && _config.NewPassword.Length > 0)
                {
                    sessDic.setString(SessaoFIX.FIX_NEWPASSWORD, _config.NewPassword);
                }

                if (_config.FiltroListaInstrumentos != null && _config.FiltroListaInstrumentos.Length > 0)
                {
                    sessDic.setString(SessaoFIX.FIX_FILTRO_LISTA_INSTRUMENTOS, _config.FiltroListaInstrumentos);
                }

                if (_config.MdReqID != null && _config.MdReqID.Length > 0)
                {
                    sessDic.setString(SessaoFIX.FIX_MDREQID_PADRAO, _config.MdReqID);
                }

                // Configure the session settings
                SessionSettings sessionSettings = new SessionSettings();

                sessionSettings.set(mainDic);
                sessionSettings.set(_session, sessDic);

                //MemoryStoreFactory fileStore = new MemoryStoreFactory();
                FileStoreFactory          fileStore = new FileStoreFactory(sessionSettings);
                FileLogFactory            fileLog   = new FileLogFactory(sessionSettings);
                QuickFix44.MessageFactory message   = new QuickFix44.MessageFactory();


                SessaoFIX sessaoFIX = new SessaoFIX(
                    sessionSettings,
                    dadosGlobais,
                    filaMensagensFIXInstantaneo,
                    filaMensagensFIXIncremental,
                    filaMensagensRetransmissorBMF);

                while (this.dadosGlobais.KeepRunning)
                {
                    Initiator sessao =
                        new ThreadedSocketInitiator(
                            sessaoFIX, fileStore, sessionSettings, fileLog, message);

                    try
                    {
                        logger.Info("Iniciando Sessao FIX...");

                        sessao.start();

                        string mensagem = filaFeeder.Pop();
                        if (mensagem.Contains(ConstantesMDS.TIPOMSG_FIM_CONEXAO))
                        {
                            break;
                        }

                        logger.Info("Finalizando Sessao FIX...");
                        sessao.stop();
                    }

                    catch (Exception ex)
                    {
                        logger.Error("Falha ao enviar mensagem na fila do Retransmissor BMF: " +
                                     ex.Message, ex);
                        continue;
                    }
                }
            }
            catch (ConfigError e)
            {
                logger.Error("Falha durante configuracao do QuickFix:" + e.Message);
                return;
            }
            catch (Exception ex)
            {
                logger.Error("Run(): " + ex.Message, ex);
                return;
            }
        }
Beispiel #6
0
 public void Next()
 {
     object next = emittables.Pop();
     graphContext.Submit(next);
 }
Beispiel #7
0
        public void Run()
        {
            EventoBovespa evento;
            long          antes;
            long          depois;

            logger.Info("Iniciando thread BovespaLivroOfertasConsumer");

            while (_dadosGlobais.KeepRunning)
            {
                evento = null;
                try
                {
                    evento = filaMensagensLivroOfertas.Pop();
                }
                catch (Exception intExcept)
                {
                    logger.Error("InterruptedException na leitura da fila de mensagens do retransmissor:");
                    logger.Debug(intExcept.Message);
                    continue;
                }

                antes = DateTime.Now.Ticks;

                string instrumento = evento.Instrumento;
                string tipo        = evento.Tipo;
                string corpo       = evento.Corpo;

                logger.Debug(evento.MsgID + " " + evento.Cabecalho + " S4 " + instrumento);

                try
                {
                    if (tipo.Equals("S0"))
                    {
                        processReenvio(corpo);
                        logger.Debug(evento.Cabecalho + " S0 " + instrumento);
                    }
                    else
                    {
                        BovespaLivroOfertas livro = null;

                        // S3 e S4 irão manipular o livro correspondente ao instrumento
                        if (todosLivros.ContainsKey(instrumento))
                        {
                            livro = todosLivros[instrumento];
                        }
                        else
                        {
                            logger.Debug("Livro do instrumento " + instrumento + " não existe, criando novo livro");
                            livro = new BovespaLivroOfertas();
                            todosLivros.Add(instrumento, livro);
                        }

                        if (tipo.Equals("S3"))
                        {
                            processAtualizacao(instrumento, livro, corpo);
                        }
                        else if (tipo.Equals("S4"))
                        {
                            processCancelamento(instrumento, livro, corpo);
                        }

                        if (!emReenvio)
                        {
                            // Buffer de montagem da mensagem
                            StringBuilder cabecalho = new StringBuilder();

                            // Cabeçalho
                            cabecalho.Append(ConstantesMDS.TIPO_REQUISICAO_LIVRO);
                            cabecalho.Append(ConstantesMDS.DESCRICAO_DE_BOLSA_BOVESPA);
                            cabecalho.Append(DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                            cabecalho.Append(string.Format("%1$-20s", instrumento));

                            EventoAtualizacaoLivroOfertas atualof =
                                new EventoAtualizacaoLivroOfertas(instrumento,
                                                                  ConstantesMDS.PLATAFORMA_TODAS,
                                                                  cabecalho.ToString(),
                                                                  livro.serializarLivroRobot(BovespaLivroOfertas.LIVRO_COMPRA),
                                                                  livro.serializarLivroRobot(BovespaLivroOfertas.LIVRO_VENDA));


                            // Gera evento de atualização
                            // ATP: implementar ?
                            //o eventoAtualizaLivro =
                            //    new EventoAtualizacaoLivroOfertas(
                            //        instrumento, ConstantesMDS.PLATAFORMA_TODAS,
                            //        cabecalho.toString(),
                            //        livroCompra.toString(),
                            //        livroVenda.toString());

                            //epService.EPRuntime.SendEvent(eventoAtualizaLivro);
                        }

                        if (this._dadosGlobais.Parametros.DebugLOFBovespa &&
                            this._dadosGlobais.Parametros.DebugLOFBovPapel != null &&
                            this._dadosGlobais.Parametros.DebugLOFBovPapel.Equals(instrumento))
                        {
                            string loffile = string.Format("{0}\\{1}.txt",
                                                           _dadosGlobais.Parametros.DiretorioDump,
                                                           _dadosGlobais.Parametros.DebugLOFBovPapel);

                            FileStream   fs     = File.Open(loffile, FileMode.Create, FileAccess.Write);
                            StreamWriter writer = new StreamWriter(fs, Encoding.ASCII);


                            writer.WriteLine("=".PadRight(100, '='));
                            writer.WriteLine(evento.MsgID + "," + evento.Cabecalho + evento.Corpo);
                            List <string> livroCompraSerializado = livro.imprimirLivro(BovespaLivroOfertas.LIVRO_COMPRA);
                            List <string> livroVendaSerializado  = livro.imprimirLivro(BovespaLivroOfertas.LIVRO_VENDA);
                            for (int i = 0; (i < livroCompraSerializado.Count || i < livroVendaSerializado.Count); i++)
                            {
                                string linha = "";
                                if (i < livroCompraSerializado.Count)
                                {
                                    linha += livroCompraSerializado[i];
                                }
                                else
                                {
                                    linha += " ".PadLeft(20);
                                }

                                linha += "|";
                                if (i < livroVendaSerializado.Count)
                                {
                                    linha += livroVendaSerializado[i];
                                }
                                else
                                {
                                    linha += " ".PadLeft(20);
                                }

                                writer.WriteLine(linha);
                            }

                            writer.WriteLine("=".PadRight(100, '='));
                            writer.Close();
                            fs.Close();
                        }
                    }

                    _dadosGlobais.LastMdgIDBov = evento.MsgID;
                }
                catch (Exception e)
                {
                    logger.Error("Exception em BovespaLivroOfertasListener: ", e);
                    logger.Error("Processando a mensagem:");
                    logger.Error(evento.MsgID + "," + evento.Cabecalho + evento.Corpo);
                }

                depois = DateTime.Now.Ticks;
                TimeSpan duracao = new TimeSpan(depois - antes);
                logger.Debug("Duracao do processamento: " + duracao.TotalMilliseconds +
                             " ms (Mensagens na fila: " + filaMensagensLivroOfertas.Count + ")");
            }
        }
Beispiel #8
0
        private void Run()
        {
            EventoBMF evento;
            string    instrumento;
            string    mensagem;
            string    cabecalho;
            string    tipo;
            long      antes;
            long      depois;

            //Calendar dataHoraCorrente = Calendar.getInstance();
            //SimpleDateFormat mascaraDataHora = new SimpleDateFormat("yyyyMMddHHmmssSSS");

            while (this.dadosGlobais.KeepRunning)
            {
                evento = null;
                try
                {
                    evento = filaMensagensLivroOfertas.Pop();
                }
                catch (Exception intExcept)
                {
                    logger.Error("InterruptedException na leitura da fila de mensagens:" + intExcept.Message, intExcept);
                    return;
                }
                antes = DateTime.Now.Ticks;

                instrumento = evento.Instrumento;
                tipo        = evento.Tipo;
                mensagem    = evento.Mensagem;

                // Inicializa os Livros de Ofertas de instrumentos em memoria,
                // durante o recebimento das mensagens de instrumentos BMF
                if (tipo.Equals(ConstantesMDS.TIPO_REQUISICAO_BMF_INSTRUMENTO))
                {
                    if (todosLivrosBMF.ContainsKey(instrumento))
                    {
                        todosLivrosBMF[instrumento].inicializaBMFLivrosOfertas();
                    }
                    continue;
                }

                contabilizaLivroOfertas(instrumento, tipo, mensagem);


                // Cabecalho da mensagem
                cabecalho = ConstantesMDS.TIPO_REQUISICAO_LIVRO;
                cabecalho = cabecalho + ConstantesMDS.DESCRICAO_DE_BOLSA_BMF;
                cabecalho = cabecalho + DateTime.Now.ToString("yyyyMMddHHmmssfff");;
                cabecalho = cabecalho + string.Format("%1$-20s", instrumento);

                logger.Info("LOF [" + instrumento + "]");

                geraEvento(instrumento,
                           cabecalho,
                           dadosGlobais.TodosLivrosBMF[instrumento].LivrosCompraBMF,
                           dadosGlobais.TodosLivrosBMF[instrumento].LivrosVendaBMF);

                depois = DateTime.Now.Ticks;
                TimeSpan duracao = new TimeSpan(depois - antes);
                logger.Debug("Duracao do processamento: " + duracao.TotalMilliseconds +
                             "ms (Mensagens na fila: " + filaMensagensLivroOfertas.Count + ")");

                if (instrumento.Equals("WINZ10"))
                {
                    FileStream   fs     = File.Open(@"c:\temp\WINZ10.txt", FileMode.Create, FileAccess.Write);
                    StreamWriter writer = new StreamWriter(fs, Encoding.ASCII);


                    writer.WriteLine("================================================================================");
                    writer.WriteLine(evento.Sequencia + "," + evento.Mensagem);
                    List <string> livroCompraSerializado = todosLivrosBMF[instrumento].serializarLivro(BovespaLivroOfertas.LIVRO_COMPRA);
                    List <string> livroVendaSerializado  = todosLivrosBMF[instrumento].serializarLivro(BovespaLivroOfertas.LIVRO_VENDA);
                    for (int i = 0; (i < livroCompraSerializado.Count || i < livroVendaSerializado.Count); i++)
                    {
                        string linha = "";
                        if (i < livroCompraSerializado.Count)
                        {
                            linha += livroCompraSerializado[i].PadLeft(30);
                        }
                        else
                        {
                            linha += " ".PadLeft(30);
                        }

                        linha += "|";
                        if (i < livroVendaSerializado.Count)
                        {
                            linha += livroVendaSerializado[i].PadLeft(30);
                        }
                        else
                        {
                            linha += " ".PadLeft(30);
                        }

                        writer.WriteLine(linha);
                    }

                    writer.WriteLine("================================================================================");
                    writer.Close();
                    fs.Close();
                }
            }
        }