Esempio n. 1
0
 public TradingClass(String _userID, String userName, String userPassword, String url, String email, ErrorDbHandler _dbHandler, Presets.SynchronizationMode syncMode = Presets.SynchronizationMode.SynchronizePositions)
 {
     FollowerEmail =  email;
     dbHandler     = _dbHandler;
     _followerID   = _userID;
     _syncMode     = syncMode;
     randomGenerator  = new Random((int)(DateTime.Now.Ticks / 10000));
     _enabledLock     = new Object();
     _inProgressLock  = new Object();
     orderTransaction = new OrderTransaction(new Presets.OrderEvent(onOrder), new Presets.ErrorEvent(onError), _userID);
     _api             = new API(url, userName, userPassword, new Presets.APIEvent(OnApievent));
     _enabled         = true; //<--- Place to the end???
     _emailNotifier   = null;
     // Configure objects
     switch (syncMode)
     {
         case Presets.SynchronizationMode.SynchronizePositions:
             Program.MarkUserToSync(_userID);
             _enabled = false;
             break;
     }
     //Create inlternal sync class
 }
Esempio n. 2
0
        /// <summary>
        /// This method create a dictionary. The kay in the dictionary is the user listened systemID, the values of the Dictionary 
        /// is a list of users TradingClass that represents the current user account, that listen the current key SystemID
        /// </summary>
        /// <returns>a dictionary : key - user listened SystemID, value - a list of users thet listening current SystemID(key)</returns>
        public Dictionary<Int32, List<TradingClass>> getConnectedUsers(ErrorDbHandler mainDBhandler, ErrorHandler errorHandler)
        {
            Dictionary<Int32, List<TradingClass>> initializedFollowers = new Dictionary<Int32, List<TradingClass>>();
            List<CompleteFollower> followers = new List<CompleteFollower>();
            SqlDataReader reader = null;
            SqlCommand sqlCmd = null;
            StringBuilder sqlStrBuilder = new StringBuilder();

            //Отримати користувачів
            sqlStrBuilder.Append("SELECT TEMP.AccountId_,    TEMP.AccountType_,    TEMP.SubscriptionType_,\n")
                .Append("TEMP.BrockerName_,  TEMP.BrockerLogin_ ,  TEMP.BrockerPassswd_,\n")
                .Append("TEMP.SyncMethod_,   [USERS].[dbo].[aspnet_Membership].[Email]\n")
                .Append("FROM  [USERS].[dbo].[aspnet_Membership],\n")
                .Append("( SELECT [USERS].[dbo].[USERBROKERS].[AccountId] AS AccountId_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[UserId]			AS UserId_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[BrokerLogin]      AS BrockerLogin_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[BrokerName]		AS BrockerName_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[BrokerPassword]   AS BrockerPassswd_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[SubscriptionType] AS SubscriptionType_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[AccountType]	    AS AccountType_,\n")
                .Append("[USERS].[dbo].[USERBROKERS].[SyncMethod]       AS SyncMethod_\n")
                .Append(" FROM [USERS].[dbo].[USERBROKERS]\n")
                .Append("WHERE [USERS].[dbo].[USERBROKERS].[BrokerName] = '").Append(PLATFORM).Append("'\n")
                .Append("AND [USERS].[dbo].[USERBROKERS].[SubscriptionType] = 'Signal receiver'\n")
                .Append(") AS TEMP\n")
                .Append("WHERE [USERS].[dbo].[aspnet_Membership].[UserId] = TEMP.UserId_");

            sqlCmd = new SqlCommand(sqlStrBuilder.ToString(), conn);

            lock (sqlQueryLock)
            {
                try
                {
                    reader = sqlCmd.ExecuteReader();
                    while (reader.Read())
                    {
                        followers.Add(new CompleteFollower(reader, fieldsMatching));
                    }
                    sqlCmd.Dispose();
                    reader.Close();
                }
                catch (Exception e0)
                {
                    String errorStr = "Exception in DatabaseClass while try to get registered users/account from db";
                    Program.log.Error(errorStr);
                    Program.log.Debug("SQL command is " + sqlCmd.CommandText);
                    Program.log.Debug(e0.Message);
                    Program.log.Debug(e0.StackTrace);
                    Program.WriteError(errorStr + "\n" + e0.Message);
                }
                if (followers.Count == 0) return initializedFollowers;

                //Отримати список провайдерів на які підписані отримані користувачі
                sqlStrBuilder.Clear();
                sqlStrBuilder.Append("SELECT [USERS].[DBO].[AccountIdToSystemId].[AccountId],\n")
                    .Append("[USERS].[DBO].[AccountIdToSystemId].[SystemId]\n")
                    .Append("FROM [USERS].[dbo].[AccountIdToSystemId]\n")
                    .Append("WHERE [USERS].[DBO].[AccountIdToSystemId].[AccountId] = '").Append(followers[0].AccountId).Append("'\n");

                for (int i = 1; i < followers.Count; ++i)
                {
                    sqlStrBuilder.Append("OR [USERS].[DBO].[AccountIdToSystemId].[AccountId] = '").Append(followers[i].AccountId).Append("'\n");
                }
                sqlCmd = new SqlCommand(sqlStrBuilder.ToString(), conn);
                reader = sqlCmd.ExecuteReader();

                Dictionary<String, List<Int32>> readedMathing = new Dictionary<string, List<int>>();
                List<Int32> systems = new List<int>();
                String readedAccountId;

                while (reader.Read())
                {
                    readedAccountId = Convert.ToString(reader["AccountId"]);
                    try
                    {
                        systems = readedMathing[readedAccountId];
                    }
                    catch (KeyNotFoundException)
                    {
                        systems = new List<int>();
                    }
                    systems.Add(Convert.ToInt32(reader["SystemId"].ToString().GetHashCode()));
                    readedMathing[readedAccountId] = systems;
                }
                sqlCmd.Dispose();
                reader.Close();

                for (int i = 0; i < followers.Count; ++i)
                {
                    //Можлива ситуація що фоловер ще не підписаний ні наякі системи
                    try { followers[i].AddListenedSystems(readedMathing[followers[i].AccountId]); }
                    catch (KeyNotFoundException) { followers.RemoveAt(i--); }
                }
                //Ініціалізувати кожного фоловера (створити для них обєкти їх АРІ)
                TradingClass initializedFollower;
                List<TradingClass> initializedFollowersList;

                foreach (CompleteFollower follower in followers)
                {
                    initializedFollower = new TradingClass(
                         follower.AccountId, follower.BrokerLogin, follower.BrokerPassword,
                         "https://testapi.lmaxtrader.com/", follower.Email, mainDBhandler,
                         Presets.GetSyncMode(follower.SynchronizationType)
                         );
                    initializedFollower.Login();

                    foreach (Int32 system in follower.ListenedSystems)
                    {
                        try
                        {
                            initializedFollowersList = initializedFollowers[system];
                        }
                        catch (KeyNotFoundException)
                        {
                            initializedFollowersList = new List<TradingClass>();
                        }
                        initializedFollowersList.Add(initializedFollower);
                        initializedFollowers[system] = initializedFollowersList;
                    }
                }
                return initializedFollowers;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// This method create a dictionary. The kay in the dictionary is the user listened systemID, the values of the Dictionary
        /// is a list of users TradingClass that represents the current user account, that listen the current key SystemID
        /// </summary>
        /// <returns>a dictionary : key - user listened SystemID, value - a list of users thet listening current SystemID(key)</returns>
        public Dictionary <Int32, List <TradingClass> > getConnectedUsers(ErrorDbHandler mainDBhandler, ErrorHandler errorHandler)
        {
            Dictionary <Int32, List <TradingClass> > initializedFollowers = new Dictionary <Int32, List <TradingClass> >();
            List <CompleteFollower> followers = new List <CompleteFollower>();
            SqlDataReader           reader    = null;
            SqlCommand    sqlCmd        = null;
            StringBuilder sqlStrBuilder = new StringBuilder();

            //Отримати користувачів
            sqlStrBuilder.Append("SELECT TEMP.AccountId_,    TEMP.AccountType_,    TEMP.SubscriptionType_,\n")
            .Append("TEMP.BrockerName_,  TEMP.BrockerLogin_ ,  TEMP.BrockerPassswd_,\n")
            .Append("TEMP.SyncMethod_,   [USERS].[dbo].[aspnet_Membership].[Email]\n")
            .Append("FROM  [USERS].[dbo].[aspnet_Membership],\n")
            .Append("( SELECT [USERS].[dbo].[USERBROKERS].[AccountId] AS AccountId_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[UserId]			AS UserId_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[BrokerLogin]      AS BrockerLogin_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[BrokerName]		AS BrockerName_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[BrokerPassword]   AS BrockerPassswd_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[SubscriptionType] AS SubscriptionType_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[AccountType]	    AS AccountType_,\n")
            .Append("[USERS].[dbo].[USERBROKERS].[SyncMethod]       AS SyncMethod_\n")
            .Append(" FROM [USERS].[dbo].[USERBROKERS]\n")
            .Append("WHERE [USERS].[dbo].[USERBROKERS].[BrokerName] = '").Append(PLATFORM).Append("'\n")
            .Append("AND [USERS].[dbo].[USERBROKERS].[SubscriptionType] = 'Signal receiver'\n")
            .Append(") AS TEMP\n")
            .Append("WHERE [USERS].[dbo].[aspnet_Membership].[UserId] = TEMP.UserId_");

            sqlCmd = new SqlCommand(sqlStrBuilder.ToString(), conn);

            lock (sqlQueryLock)
            {
                try
                {
                    reader = sqlCmd.ExecuteReader();
                    while (reader.Read())
                    {
                        followers.Add(new CompleteFollower(reader, fieldsMatching));
                    }
                    sqlCmd.Dispose();
                    reader.Close();
                }
                catch (Exception e0)
                {
                    String errorStr = "Exception in DatabaseClass while try to get registered users/account from db";
                    Program.log.Error(errorStr);
                    Program.log.Debug("SQL command is " + sqlCmd.CommandText);
                    Program.log.Debug(e0.Message);
                    Program.log.Debug(e0.StackTrace);
                    Program.WriteError(errorStr + "\n" + e0.Message);
                }
                if (followers.Count == 0)
                {
                    return(initializedFollowers);
                }

                //Отримати список провайдерів на які підписані отримані користувачі
                sqlStrBuilder.Clear();
                sqlStrBuilder.Append("SELECT [USERS].[DBO].[AccountIdToSystemId].[AccountId],\n")
                .Append("[USERS].[DBO].[AccountIdToSystemId].[SystemId]\n")
                .Append("FROM [USERS].[dbo].[AccountIdToSystemId]\n")
                .Append("WHERE [USERS].[DBO].[AccountIdToSystemId].[AccountId] = '").Append(followers[0].AccountId).Append("'\n");

                for (int i = 1; i < followers.Count; ++i)
                {
                    sqlStrBuilder.Append("OR [USERS].[DBO].[AccountIdToSystemId].[AccountId] = '").Append(followers[i].AccountId).Append("'\n");
                }
                sqlCmd = new SqlCommand(sqlStrBuilder.ToString(), conn);
                reader = sqlCmd.ExecuteReader();

                Dictionary <String, List <Int32> > readedMathing = new Dictionary <string, List <int> >();
                List <Int32> systems = new List <int>();
                String       readedAccountId;

                while (reader.Read())
                {
                    readedAccountId = Convert.ToString(reader["AccountId"]);
                    try
                    {
                        systems = readedMathing[readedAccountId];
                    }
                    catch (KeyNotFoundException)
                    {
                        systems = new List <int>();
                    }
                    systems.Add(Convert.ToInt32(reader["SystemId"].ToString().GetHashCode()));
                    readedMathing[readedAccountId] = systems;
                }
                sqlCmd.Dispose();
                reader.Close();

                for (int i = 0; i < followers.Count; ++i)
                {
                    //Можлива ситуація що фоловер ще не підписаний ні наякі системи
                    try { followers[i].AddListenedSystems(readedMathing[followers[i].AccountId]); }
                    catch (KeyNotFoundException) { followers.RemoveAt(i--); }
                }
                //Ініціалізувати кожного фоловера (створити для них обєкти їх АРІ)
                TradingClass        initializedFollower;
                List <TradingClass> initializedFollowersList;

                foreach (CompleteFollower follower in followers)
                {
                    initializedFollower = new TradingClass(
                        follower.AccountId, follower.BrokerLogin, follower.BrokerPassword,
                        "https://testapi.lmaxtrader.com/", follower.Email, mainDBhandler,
                        Presets.GetSyncMode(follower.SynchronizationType)
                        );
                    initializedFollower.Login();

                    foreach (Int32 system in follower.ListenedSystems)
                    {
                        try
                        {
                            initializedFollowersList = initializedFollowers[system];
                        }
                        catch (KeyNotFoundException)
                        {
                            initializedFollowersList = new List <TradingClass>();
                        }
                        initializedFollowersList.Add(initializedFollower);
                        initializedFollowers[system] = initializedFollowersList;
                    }
                }
                return(initializedFollowers);
            }
        }
Esempio n. 4
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();
            log.Info("Starting program");

            //Loading configuration from file
            try
            {
                config = new ConfLoader().loadConfFromFile("LMAX_sender_config.txt");
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                log.Debug(e.StackTrace.ToString());
                log.Error("Exit program");
                return;
            }
            random = new Random((int)DateTime.Now.Ticks / 10000);
            isQuit = isRefrash = false;
            Thread t = new Thread(new ThreadStart(KeyReadHandler));
            t.Name = "Key handler thread";
            t.Start();

            syncUsers = new List<string>();
            NewUsers  = new List<string>();

            //Create lock objects
            usersLock      = new Object();
            errorWriteLock = new Object();
            mustSyncLock   = new Object();
            randomLock     = new Object();
            newUserLock    = new Object();

            //Create necessary datas
            BlockingCollection<Operations>  blokingQueue = new BlockingCollection<Operations>();

            //create sender db handler
            dbHandler = new ErrorDbHandler();

            //create object for manipulat with local DB
            localDbHandler = new LocalDbHandler();

            //Create error handler class for error solutions
            ErrorHandler errorHandler = new ErrorHandler("ytsnotify", "YTS_admin password");

            // Get datas from DB about users
            remoteDbHandler = new DataBase();

            try
            {
                lock (usersLock)
                {
                    idUsers = remoteDbHandler.getConnectedUsers(dbHandler, errorHandler);
                    /*
                    idUsers = new Dictionary<int, List<TradingClass>>();
                    List<TradingClass> list1 = new List<TradingClass>();
                    List<TradingClass> list2 = new List<TradingClass>();

                    for (int i = 0; i < 2; ++i)
                    {
                        list.Add(new TradingClass("user_"+i,"userName_"+i,"Passwd_0"+i,"URL","userEmail",dbHandler));
                        list[i].Login();
                        Console.WriteLine("\tConnected users {0}", i);
                    }

                    list1.Add(new TradingClass("user_1", "userName_1", "Passwd_1", "URL", "userEmail", dbHandler));
                    list2.Add(new TradingClass("user_2", "userName_2", "Passwd_2", "URL", "userEmail", dbHandler));
                    list1[0].Login();
                    list2[0].Login();
                    idUsers.Add(10001, list1);
                    idUsers.Add(10002, list2);*/
                }
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                log.Debug(e.StackTrace.ToString());
                log.Error("Exit program");
                log.Info("Exit program becouse of error");
                return;
            }
            System.Console.WriteLine("Get {0} users from DB", idUsers.Values.Count);

            //Create class for user control directly after create users
            externalClientManager = new ExternalClientManager();

            //Create listen port
            Type serviceType = typeof(ExternalClientManager);
            Uri  serviceUri  = new Uri("http://localhost:9081/");
            System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(serviceType, serviceUri);
            host.Open();

            // Start NETlistener to get new users from DB
            //NETlistener netListener = new NETlistener();

            DateTime time0 = new DateTime();
            DateTime oTime = new DateTime();

            //Create time reader from file
            DateFileWritter dateFile = new DateFileWritter();

            time0 = dateFile.ReadTime();

            //Create systemContainer to cach DB lastest data
            systemContainer = new SystemContainer(blokingQueue,time0);

            //Create sender class
            SenderClass sender = new SenderClass(blokingQueue);

            List<DBResult> res = new List<DBResult>();

            Console.WriteLine("Loaded time value : {0}", time0.ToString("yyyy-MM-dd HH:mm:ss.fff"));

            long start;
            long finish;
            long waitTime;

            while (true)
            {
                if (isQuit)
                {
                    Console.WriteLine("Buy....");
                    return;
                }
                //Створити нових фоловерів якщо вони є в списку
                //CreateFromMarketFollowers(time0);
                //Вирішити проблеми синхронізації
                ProcessUsersSolveProblem(time0);

                start = DateTime.Now.Ticks / 10000;

                res = (List<DBResult>)remoteDbHandler.GetDBResult(time0);

                if(res != null && res.Count > 0)
                {
                    System.Console.WriteLine("Get results : {0}", res.Count);
                    oTime = time0;
                    time0 = res[0].DbTime;
                    dateFile.WriteTime(time0);

                    foreach (DBResult item in res)
                    {
                        systemContainer.AddElement(item);
                    }
                    systemContainer.processSystems(idUsers, oTime);
                }

                finish = DateTime.Now.Ticks / 10000;
                waitTime = MUST_WAIT - (finish - start);

                if (waitTime > 0)
                {
                    Thread.Sleep((int)waitTime);
                }
                Console.WriteLine("wait in main loop");
            }
            //netListener.ShutDown();
            sender.ShutDown();
        }