/// <summary>
        /// Subscrube a follower to a specified system
        /// </summary>
        /// <param name="followerID">followers ID</param>
        /// <param name="systemID">systems ID</param>
        public void Subscribe(String followerID, Int32 systemID)
        {
            FollowerPropereties followerProps;
            //Перевірити чи існує такий користувач
            TradingClass follower = Program.GetFollowerById(followerID);

            if (follower == null)
            {
                lock (_syncFollowerList)
                {
                    IEnumerable <FollowerPropereties> followerToStart = from f in _notInitializedFollowers
                                                                        where f.FollowerID == followerID
                                                                        select f;
                    if (followerToStart.Count() == 0)
                    {
                        throw new Exception("Cannot find follower by id '" + followerID + "' at list of followers");
                    }
                    if (followerToStart.Count() != 0)
                    {
                        throw new Exception("There are more than 1 follower (" + followerToStart.Count());
                    }
                    //Створити фоловера
                    followerProps = followerToStart.ElementAt(0);
                    _notInitializedFollowers.Remove(followerProps);
                }
                follower = new TradingClass(followerProps.FollowerID, followerProps.FollowerBrokerLogin, followerProps.FollowerBrokerLogin,
                                            url, followerProps.FollowerEmail, Program.dbHandler, followerProps.FollowerSynchMode);
            }
            //Перевірити чи користувач вже не підписаний на цю систему
            List <TradingClass> listOfFollowers;

            lock (Program.usersLock)
            {
                try
                {
                    listOfFollowers = Program.idUsers[systemID];
                }
                catch (KeyNotFoundException)
                {
                    listOfFollowers = new List <TradingClass>();
                }
                IEnumerable <TradingClass> finded = from searchedFollower in listOfFollowers
                                                    where searchedFollower.FollowerID == followerID
                                                    select searchedFollower;

                if (finded.Count() != 0)
                {
                    throw new Exception("follower '" + followerID + "' allready subscribe to system " + systemID);
                }
                // Підписати фоловера
                listOfFollowers.Add(follower);
            }
        }
        public void StopFollower(String followerId)
        {
            TradingClass follower = Program.GetFollowerById(followerId);

            try
            {
                follower.StopUser();
            }
            catch (Exception e)
            {
                Program.log.Error(e.Message);
                Program.log.Debug(e.StackTrace.ToString());
                Program.WriteError("Error in ExternalClientManager.StopUser. Additional info : " + e.Message);
            }
        }
Beispiel #3
0
        private static void ProcessUsersSolveProblem(DateTime initialTime)
        {
            //Отримати список користувачів для синхронізації
            List <String> usersToSync = GetUsersMarkedToSync();

            foreach (String aUserID in usersToSync)
            {
                TradingClass someUser = GetFollowerById(aUserID);

                if (someUser == null)
                {
                    WriteError("Cannot find user by ID : " + aUserID);
                }
                else
                {
                    //Видалити користувача зі списку
                    UnmarkUserToSync(aUserID);
                    try
                    {
                        //Отримати ордери - вирішення проблеми
                        List <Order> syncOrders = syncSolver.solve(aUserID, getListenedID(aUserID), initialTime);
                        //Видалити ордери з списку непідтверджених
                        someUser.ClearOrders();
                        //Розблокувати користувача (він ймовірно заблокований)
                        someUser.UnlockUser();
                        foreach (Order order in syncOrders)
                        {
                            order.PrevScanTime = initialTime;
                            someUser.SendOrder(order);
                        }
                    }
                    catch (Exception e)
                    {
                        Program.WriteError("Exception in  Program while resolving sync problem. Detail info : " + e.Message);
                        Program.log.Error("" + e.GetType().Name + " exception");
                        Program.log.Debug("Exception in  Program while resolving sync problem. Error message : " + e.Message + "\n" + e.StackTrace.ToString());
                    }
                }
            }
        }
Beispiel #4
0
        public void processReq(object osocket)
        {
            Socket socket = (Socket)osocket;
            byte[] buffData = new byte[300];
            int recLen = 0;
            string message = "";
            int endls = 0;

            try
            {
                while (isRunning)
                {
                    recLen = socket.Receive(buffData);
                    message += _stringCoder.GetString(buffData, 0, recLen);

                    endls = 0;
                    for (int i = 0; i < message.Length; ++i)
                    {
                        if (message[i] == '\n') ++endls;
                    }
                    if (endls != 0) break;
                }
            }
            catch(Exception e)
            {
                Program.log.Error("Error occured when try to recieve data from socket");
                Program.log.Debug(e.Message);
                Program.log.Debug(e.StackTrace);
            }

            if (!isRunning)
            {
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch (Exception e)
                {
                    Program.log.Error("Error trying to Shutdown client socket");
                    Program.log.Debug(e.Message);
                    Program.log.Debug(e.StackTrace);
                }
                socket.Close();
                return;
            }

            string[] funcArgs = message.Split(';');
            Int32 strategyID = Convert.ToInt32(funcArgs[2]);
            List<TradingClass> connectObjList;

            System.Console.WriteLine("NET listener get request. try to process it");
            
            switch (funcArgs[0].ToLower().Trim())
            {
                case "stop" :
                    TradingClass tc = Program.GetFollowerById(funcArgs[1]);
                    tc.StopUser();
                    break;
                case "continue" :
                    Program.MarkUserToSync(funcArgs[1]);
                    break;
            }
             
        }
Beispiel #5
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);
            }
        }