Beispiel #1
0
        // 1: return by chave
        // 2: return by chaveExchNumber
        public int GetOrder(string chave, out TOOrderSession to, string chaveExchNumber = "", int keyType = 1, string exchange = "")
        {
            try
            {
                //TOOrderSession ord = null;
                lock (_dicMsgsCl)
                {
                    if (_dicMsgsCl.TryGetValue(chave, out to))
                    {
                        return(FindType.CLORDID);
                    }
                    else
                    {
                        //if (string.IsNullOrEmpty(chaveExchNumber))
                        //    return FindType.CLORDID;

                        {
                            //KeyValuePair<string, TOOrderSession> item = new KeyValuePair<string, TOOrderSession>();
                            List <TOOrderSession> lst = _dicMsgsCl.Select(x => x.Value).Where(x => x.ExchangeNumberID == chaveExchNumber).ToList();

                            TOOrderSession item = null;
                            if (KeyType.CLORDID == keyType)
                            {
                                item = lst.OrderByDescending(x => x.ExchangeSeqNum).FirstOrDefault();
                            }
                            else
                            {
                                item = lst.OrderByDescending(x => x.ExchangeSeqNum).LastOrDefault();
                            }

                            to = item;
                            if (null != to)
                            {
                                return(FindType.EXCHANGE_NUMBER);
                            }
                            // Nao achou a ordem. Tentará busca a partir do banco de dados. //TODO[FF]: Fazer a busca e remontar o TO com as informacoes existentes
                            else
                            {
                                string[] arr = chave.Split('-');
                                string   clord;
                                string   strAcc = string.Empty;
                                int      account;
                                string   symbol;
                                if (arr.Length != 3)
                                {
                                    return(FindType.UNDEFINED);
                                }
                                clord = arr[0];
                                if (exchange.Equals(ExchangePrefixes.BOVESPA, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    strAcc = arr[1].Substring(0, arr[1].Length - 1);
                                }
                                else
                                {
                                    strAcc = arr[1];
                                }
                                account = Convert.ToInt32(strAcc);
                                symbol  = arr[2];
                                DbFix       db     = new DbFix();
                                OrderDbInfo retOrd = db.BuscarOrdem(clord, account, symbol);
                                if (0 == retOrd.OrderID)
                                {
                                    to = null;
                                    return(FindType.UNDEFINED);
                                }
                                else
                                {
                                    TOOrderSession toAux = this.OrderDbInfo2OrderSession(retOrd, chave);
                                    to = toAux;
                                    return(FindType.DB);
                                }
                            }
                        }
                    }
                }
                to = null;
                return(FindType.UNDEFINED);
            }
            catch (Exception ex)
            {
                logger.Error("Erro ao buscar o TOOrderSession: " + ex.Message, ex);
                to = null;
                return(FindType.UNDEFINED);
            }
        }
Beispiel #2
0
        public void SaveOrderSessionIDsToDB(int idSessao)
        {
            try
            {
                // Serialize Dictionary to dat file
                if (!_serializing)
                {
                    _serializing = true;
                    Dictionary <string, TOOrderSession> regs = new Dictionary <string, TOOrderSession>(_dicMsgsCl);
                    DbFix dbFix = new DbFix();
                    logger.Info("Inicio da Gravacao");

                    // Efetuar a limpeza para "re-gravar" os registros
                    if (!dbFix.LimparOrderSessionIDs(idSessao))
                    {
                        logger.Info("Problemas na limpeza dos OrderSessionIDs");
                        return;
                    }

                    foreach (KeyValuePair <string, TOOrderSession> item in regs)
                    {
                        TOMessageBackup to = new TOMessageBackup();

                        to.Key           = item.Key;
                        to.BeginString   = item.Value.Sessao.BeginString;
                        to.SenderCompID  = item.Value.Sessao.SenderCompID;
                        to.SenderSubID   = item.Value.Sessao.SenderSubID;
                        to.TargetCompID  = item.Value.Sessao.TargetCompID;
                        to.TargetSubID   = item.Value.Sessao.TargetSubID;
                        to.TipoExpiracao = item.Value.TipoExpiracao;
                        to.DataExpiracao = item.Value.DataExpiracao;
                        to.DataEnvio     = item.Value.DataEnvio;
                        to.MsgSeqNum     = item.Value.MsgSeqNum.ToString();
                        to.ClOrdID       = item.Value.ClOrdID;
                        to.OrigClOrdID   = item.Value.OrigClOrdID;
                        to.Account       = item.Value.Account.ToString();
                        int lenPid = item.Value.PartyIDs.Count;
                        for (int i = 0; i < lenPid; i++)
                        {
                            PartyIDBackup pId = new PartyIDBackup();
                            pId.PartyID       = item.Value.PartyIDs[i].GetField(Tags.PartyID);
                            pId.PartyIDSource = item.Value.PartyIDs[i].GetChar(Tags.PartyIDSource);
                            pId.PartyRole     = item.Value.PartyIDs[i].GetInt(Tags.PartyRole);
                            to.PartyIDs.Add(pId);
                        }
                        to.TipoLimite       = (int)item.Value.TipoLimite;
                        to.Order            = item.Value.Order;
                        to.MensagemQF       = item.Value.MensagemQF.ToString();
                        to.ExchangeNumberID = item.Value.ExchangeNumberID;
                        to.ExchangeSeqNum   = item.Value.ExchangeSeqNum;
                        dbFix.InserirOrderSessionItem(idSessao, to);
                        to = null;
                    }
                    logger.InfoFormat("Gravando OrderSessions da Sessao: [{0}] Registros: [{1}]", idSessao, regs.Count);
                    //BinaryFormatter bs = new BinaryFormatter();
                    //bs.Serialize(fs, lst);
                    //bs = null;
                    //fs.Close();
                    //fs = null;
                    regs.Clear();
                    regs         = null;
                    _serializing = false;
                }
                else
                {
                    if (_serializing)
                    {
                        logger.Debug("SaveSessionIDS(): Processo de serializacao já em execucao!!!");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("SaveSessionIDS(): Erro na serializacao dos registros do dicionario: " + ex.Message, ex);
                _serializing = false; // mudar para false para tentar backupear no proximo "ciclo"
                //fs.Close();
                //fs = null;
            }
        }
Beispiel #3
0
        public void IniciarServico()
        {
            try
            {
                logger.Info("**********************************************************************");
                logger.Info("**********************************************************************");
                logger.Info("*** IniciarServico(): FixServer....");
                // Thread.Sleep(20000);
                // Carrega configurações a partir do banco de dados
                _dbFix = new DbFix();
                string strExecFile = Process.GetCurrentProcess().MainModule.FileName;

                strExecFile = strExecFile.Substring(strExecFile.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                logger.Info("ExecFile: " + strExecFile);

                _lstCfg = _dbFix.BuscarSessoesFIXServer(strExecFile);
                List <FixSessionItem> lstInit     = new List <FixSessionItem>();
                List <FixSessionItem> lstAccept   = new List <FixSessionItem>();
                List <FixSessionItem> lstDropCopy = new List <FixSessionItem>();

                //logger.Info("Iniciando Gerenciador de Limites");
                //LimiteManager.GetInstance().Start();
                string strServerName = System.Net.Dns.GetHostName() + "." + System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;
                logger.Info("Atualizando 'server names' das sessoes fix");
                foreach (FixSessionItem item in _lstCfg)
                {
                    if (item.ConnectionType.ToLower().Equals(FixConnectionType.ACCEPTOR))
                    {
                        lstAccept.Add(item);
                    }

                    if (item.ConnectionType.ToLower().Equals(FixConnectionType.INITIATOR))
                    {
                        lstInit.Add(item);
                    }

                    if (item.ConnectionType.ToLower().Equals(FixConnectionType.DROPCOPY_ACCEPTOR))
                    {
                        lstDropCopy.Add(item);
                    }

                    // Atualizar o nome do servidor para definir a "origem" das sessoes
                    _dbFix.AtualizarServerName(item.IdSessaoFix, strServerName);
                }

                // Criar primeiramente Initiator, para ser passado como parametro para as sessoes acceptor
                if (lstInit.Count == 0)
                {
                    logger.Info("Configurações de FixInitiator não encontradas. Não criará o SocketInitiator");
                }
                else
                {
                    foreach (FixSessionItem item in lstInit)
                    {
                        FixInitiator aux = new FixInitiator(item);
                        _lstfixInitiator.Add(aux);
                        logger.Info("IniciarServico(): iniciando SocketInitiator");
                        aux.Start();
                    }
                    // Atribuir as sessoes para executar as tarefas (como dump do dicionario de msgs)
                    _tasks.SetFixInitiators(_lstfixInitiator);
                }

                if (lstDropCopy.Count == 0)
                {
                    logger.Info("Configurações de FixDropCopy não encontradas. Não criará o SocketAcceptor DropCopy");
                }
                else
                {
                    logger.Info("IniciarServico(): iniciando Sessao Drop Copy ");
                    _fixDropCopy = new FixDropCopy(lstDropCopy);
                    _fixDropCopy.Start();
                    //_lstfixDropCopy.Add(aux);
                }

                if (lstAccept.Count == 0)
                {
                    logger.Info("Configurações de FixAcceptor não encontradas. Não criará o SocketAcceptor");
                }
                else
                {
                    logger.Info("IniciarServico(): iniciando SocketAcceptor");
                    _fixAcceptor = new FixAcceptor(lstAccept, _lstfixInitiator, _fixDropCopy);
                    _fixAcceptor.Start();
                }

                logger.Info("IniciarServico(): iniciando crontab Scheduler");
                if (null == _cron)
                {
                    _cron = new Util.CronStyleScheduler();
                }
                _cron.Start();


                logger.Info("*** IniciarServico(): FixServer inicializado...");

                _dbFix  = null;
                _status = ServicoStatus.EmExecucao;
            }
            catch (Exception ex)
            {
                logger.Error("Erro inicializacao: " + ex.Message, ex);
                throw ex;
            }
        }
Beispiel #4
0
        /*
         * public void SaveSessionIDS(string filename)
         * {
         *  FileStream fs = File.Open(filename, FileMode.Create, FileAccess.Write);
         *  try
         *  {
         *      // Serialize Dictionary to dat file
         *      List<TOMessageBackup> lst = new List<TOMessageBackup>();
         *      if (!_serializing)
         *      {
         *          _serializing = true;
         *          Dictionary<string, TOOrderSession> regs = new Dictionary<string, TOOrderSession>(_dicMsgsCl);
         *
         *
         *          foreach (KeyValuePair<string, TOOrderSession> item in regs)
         *          {
         *              TOMessageBackup to = new TOMessageBackup();
         *
         *              to.Key = item.Key;
         *              to.BeginString = item.Value.Sessao.BeginString;
         *              to.SenderCompID = item.Value.Sessao.SenderCompID;
         *              to.SenderSubID = item.Value.Sessao.SenderSubID;
         *              to.TargetCompID = item.Value.Sessao.TargetCompID;
         *              to.TargetSubID = item.Value.Sessao.TargetSubID;
         *              to.TipoExpiracao = item.Value.TipoExpiracao;
         *              to.DataExpiracao = item.Value.DataExpiracao;
         *              to.DataEnvio = item.Value.DataEnvio;
         *              to.MsgSeqNum = item.Value.MsgSeqNum.ToString();
         *              to.ClOrdID = item.Value.ClOrdID;
         *              to.OrigClOrdID = item.Value.OrigClOrdID;
         *              to.Account = item.Value.Account.ToString();
         *              int lenPid = item.Value.PartyIDs.Count;
         *              for (int i = 0; i < lenPid; i++)
         *              {
         *                  PartyIDBackup pId = new PartyIDBackup();
         *                  pId.PartyID = item.Value.PartyIDs[i].GetField(Tags.PartyID);
         *                  pId.PartyIDSource = item.Value.PartyIDs[i].GetChar(Tags.PartyIDSource);
         *                  pId.PartyRole = item.Value.PartyIDs[i].GetInt(Tags.PartyRole);
         *                  to.PartyIDs.Add(pId);
         *              }
         *              // to.MensagemQF = item.Value.MensagemQF.ToString();
         *              to.TipoLimite = (int)item.Value.TipoLimite;
         *              to.Order = item.Value.Order;
         *              to.MensagemQF = item.Value.MensagemQF.ToString();
         *              to.ExchangeNumberID = item.Value.ExchangeNumberID;
         *              to.ExchangeSeqNum = item.Value.ExchangeSeqNum;
         *              //to.SecondaryOrderID = item.Value.SecondaryOrderID;
         *              //to.TradeDate = item.Value.TradeDate;
         *              lst.Add(to);
         *              to = null;
         *          }
         *
         *          BinaryFormatter bs = new BinaryFormatter();
         *          bs.Serialize(fs, lst);
         *          bs = null;
         *          logger.InfoFormat("SaveSessionIDS(): Registros serializados: [{0}] [{1}]", lst.Count, filename);
         *          // Efetuar limpeza da lista
         *          int len = lst.Count;
         *          for (int i = 0; i < len; i++)
         *          {
         *              TOMessageBackup aux = lst[i];
         *              aux = null;
         *          }
         *
         *          lst.Clear();
         *          lst = null;
         *          fs.Close();
         *          fs = null;
         *          regs.Clear();
         *          regs = null;
         *          _serializing = false;
         *      }
         *      else
         *      {
         *          if (_serializing)
         *              logger.Debug("SaveSessionIDS(): Processo de serializacao já em execucao!!!");
         *      }
         *  }
         *  catch (Exception ex)
         *  {
         *      logger.Error("SaveSessionIDS(): Erro na serializacao dos registros do dicionario: " + ex.Message, ex);
         *      _serializing = false; // mudar para false para tentar backupear no proximo "ciclo"
         *      fs.Close();
         *      fs = null;
         *  }
         * }
         */
        /*
         * public void LoadSessionIDs(string fileName, QuickFix.DataDictionary.DataDictionary dataDic)
         * {
         *  string msgQF = string.Empty;
         *  try
         *  {
         *      if (File.Exists(fileName))
         *      {
         *          List<TOMessageBackup> lst = new List<TOMessageBackup>();
         *          FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
         *          BinaryFormatter bformatter = new BinaryFormatter();
         *          lst = (List<TOMessageBackup>)bformatter.Deserialize(fs);
         *          int length = lst.Count;
         *          if (lst.Count > 0)
         *          {
         *              lock (_dicMsgsCl)
         *              {
         *                  for (int i = 0; i < length; i++)
         *                  {
         *                      TOMessageBackup to = lst[i];
         *                      TOOrderSession toOrder = new TOOrderSession();
         *                      SessionID ssID = null;
         *                      if (!string.IsNullOrEmpty(to.SenderSubID) && (!string.IsNullOrEmpty(to.TargetSubID)))
         *                          ssID = new SessionID(to.BeginString, to.SenderCompID, to.SenderSubID, to.TargetCompID, to.TargetSubID);
         *                      else
         *                          ssID = new SessionID(to.BeginString, to.SenderCompID, to.TargetCompID);
         *                      toOrder.Sessao = ssID;
         *                      toOrder.TipoExpiracao = to.TipoExpiracao;
         *                      toOrder.DataExpiracao = to.DataExpiracao;
         *                      toOrder.DataEnvio = to.DataEnvio;
         *                      toOrder.MsgSeqNum = Convert.ToInt32(to.MsgSeqNum);
         *                      toOrder.ClOrdID = to.ClOrdID;
         *                      toOrder.OrigClOrdID = to.OrigClOrdID;
         *                      toOrder.Account = Convert.ToInt32(to.Account);
         *                      int len = to.PartyIDs.Count;
         *                      for (int j = 0; j < len; j++)
         *                      {
         *                          QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup grp = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup();
         *                          grp.Set(new PartyID(to.PartyIDs[j].PartyID));
         *                          grp.Set(new PartyIDSource(to.PartyIDs[j].PartyIDSource));
         *                          grp.Set(new PartyRole(to.PartyIDs[j].PartyRole));
         *                          toOrder.PartyIDs.Add(grp);
         *                      }
         *
         *                      toOrder.TipoLimite = (TipoLimiteEnum)to.TipoLimite;
         *                      toOrder.Order = to.Order;
         *                      toOrder.MensagemQF = new QuickFix.Message(to.MensagemQF, dataDic, true);
         *                      toOrder.ExchangeNumberID = to.ExchangeNumberID;
         *                      toOrder.ExchangeSeqNum = to.ExchangeSeqNum;
         *                      //toOrder.SecondaryOrderID = to.SecondaryOrderID;
         *                      //toOrder.TradeDate = to.TradeDate;
         *                      _dicMsgsCl.Add(to.Key, toOrder);
         *                  }
         *              }
         *              logger.Info("LoadSessionIDs(): Registros recuperados: " + lst.Count);
         *              lst.Clear();
         *              lst = null;
         *          }
         *          if (fs != null)
         *          {
         *              fs.Close();
         *              fs = null;
         *          }
         *      }
         *  }
         *  catch (Exception ex)
         *  {
         *      logger.Error("LoadSessionIDs(): Erro na deserializacao dos registros do dicionario: MsgQF: " + msgQF + " " + ex.Message, ex);
         *  }
         * }
         */
        public void LoadOrderSessionIDsFromDB(int idSession, QuickFix.DataDictionary.DataDictionary dataDic)
        {
            try
            {
                DbFix dbFix = new DbFix();
                List <TOMessageBackup> lst = dbFix.BuscarOrderSessionIDs(idSession);

                int length = lst.Count;
                if (lst.Count > 0)
                {
                    lock (_dicMsgsCl)
                    {
                        for (int i = 0; i < length; i++)
                        {
                            TOMessageBackup to      = lst[i];
                            TOOrderSession  toOrder = new TOOrderSession();
                            SessionID       ssID    = null;
                            if (!string.IsNullOrEmpty(to.SenderSubID) && (!string.IsNullOrEmpty(to.TargetSubID)))
                            {
                                ssID = new SessionID(to.BeginString, to.SenderCompID, to.SenderSubID, to.TargetCompID, to.TargetSubID);
                            }
                            else
                            {
                                ssID = new SessionID(to.BeginString, to.SenderCompID, to.TargetCompID);
                            }
                            toOrder.Sessao        = ssID;
                            toOrder.TipoExpiracao = to.TipoExpiracao;
                            toOrder.DataExpiracao = to.DataExpiracao;
                            toOrder.DataEnvio     = to.DataEnvio;
                            toOrder.MsgSeqNum     = Convert.ToInt32(to.MsgSeqNum);
                            toOrder.ClOrdID       = to.ClOrdID;
                            toOrder.OrigClOrdID   = to.OrigClOrdID;
                            toOrder.Account       = Convert.ToInt32(to.Account);
                            int len = to.PartyIDs.Count;
                            for (int j = 0; j < len; j++)
                            {
                                QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup grp = new QuickFix.FIX44.NewOrderSingle.NoPartyIDsGroup();
                                grp.Set(new PartyID(to.PartyIDs[j].PartyID));
                                grp.Set(new PartyIDSource(to.PartyIDs[j].PartyIDSource));
                                grp.Set(new PartyRole(to.PartyIDs[j].PartyRole));
                                toOrder.PartyIDs.Add(grp);
                            }

                            toOrder.TipoLimite       = (TipoLimiteEnum)to.TipoLimite;
                            toOrder.Order            = to.Order;
                            toOrder.MensagemQF       = new QuickFix.Message(to.MensagemQF, dataDic, true);
                            toOrder.ExchangeNumberID = to.ExchangeNumberID;
                            toOrder.ExchangeSeqNum   = to.ExchangeSeqNum;
                            _dicMsgsCl.Add(to.Key, toOrder);
                        }
                    }
                    logger.Info("LoadOrderSessionIDsFromDB(): Registros recuperados: " + lst.Count);
                    lst.Clear();
                    lst = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error("LoadOrderSessionIDsFromDB(): Erro na deserializacao dos registros a partir do banco de dados: " + ex.Message, ex);
            }
        }
Beispiel #5
0
        public void PararServico()
        {
            try
            {
                logger.Info("*** Parando FixServer");
                if (_fixAcceptor != null)
                {
                    logger.Info("Parando Fix SocketAcceptor");
                    _fixAcceptor.Stop();
                    _fixAcceptor = null;
                }

                if (_fixDropCopy != null)
                {
                    logger.Info("Parando Fix SocketAcceptor - Drop Copy");
                    _fixDropCopy.Stop();
                    _fixDropCopy = null;
                }

                if (_lstfixInitiator != null)
                {
                    int length = _lstfixInitiator.Count;
                    for (int i = 0; i < length; i++)
                    {
                        logger.Info("Parando Fix SocketInitiator");
                        _lstfixInitiator[i].Stop();
                        _lstfixInitiator[i] = null;
                    }
                    _lstfixInitiator.Clear();
                    _lstfixInitiator = null;
                }
                _tasks = null;
                DbFix dbFix = new DbFix();
                logger.Info("Atualizando 'server names' das sessoes fix");
                foreach (FixSessionItem item in _lstCfg)
                {
                    dbFix.AtualizarServerName(item.IdSessaoFix, null);
                }
                _lstCfg.Clear();
                _lstCfg = null;
                dbFix   = null;
                //logger.Info("Parando Gerenciador de Limites");
                //LimiteManager.GetInstance().Stop();
                //logger.Info("Parando Cron Tab Scheduler");

                if (null != _cron)
                {
                    _cron.Stop();
                    _cron = null;
                }

                _status = ServicoStatus.Parado;


                logger.Info("*** FixServer finalizado");

                // Forcar queda do executavel
            }
            catch (Exception ex)
            {
                logger.Error("*** Erro na parada do servico: " + ex.Message, ex);
            }
        }