예제 #1
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));

                DoLog(string.Format("Building and sending order..."));

                Order newOrder = BuildOrder();
                BuildOrderMessage(newOrder);
            }
            else if (msg is LegacyOrderAck)
            {
                LegacyOrderAck orderAckMsg = (LegacyOrderAck)msg;

                ShowOrderAck(orderAckMsg);
            }
        }
예제 #2
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                //3- Once Logged we request the security master record. We set the request timestamp for timeout calculation
                SecurityMasterRecordRequestStartTime = DateTime.Now;
                SubscriptionTAFinished = false;
                RequestSecurityMasterList();

                //3.1- We launch the thread that will process all the securities once everything is available
                Thread processSecurityMasterRecordThread = new Thread(ProcessSecurityMasterRecordThread);
                processSecurityMasterRecordThread.Start();
            }
            else if (msg is SubscriptionResponse)
            {
                SubscriptionResponse subscrResp = (SubscriptionResponse)msg;
                if (subscrResp.Service == "TA")
                {
                    SubscriptionTAFinished = true;
                }
            }
            else if (msg is SecurityMasterRecord)
            {
                SecurityMasterRecord security = (SecurityMasterRecord)msg;
                //4-Every time we get a security, if the arrival time is less than timeout time, we update the list that hold
                //all the securities
                TimeSpan elapsed = DateTime.Now - SecurityMasterRecordRequestStartTime;
                if (elapsed.TotalSeconds < _SECURITY_MASTER_RECORD_TIMOUT_IN_SECONDS && !SubscriptionTAFinished)
                {
                    SecurityMasterRecords.Add(security);
                }
                else
                {
                    //4.1- Here the security arrive after the timeout. We have to set some warning in the logs to check
                    //     if we have to recalibrate the timeout threshold
                    if (SubscriptionTAFinished)
                    {
                        DoLog(string.Format("TC1-Security Master Record arrived afte subscription response succesfull received!:{0}", security.Symbol));
                    }
                    else if (elapsed.TotalSeconds > _SECURITY_MASTER_RECORD_TIMOUT_IN_SECONDS)
                    {
                        DoLog(string.Format("TC2-Security Master Record arrived after timeout expiration!:{0}", security.Symbol));
                    }
                }
            }
        }
예제 #3
0
        public static async void ClientMessageThread(object param)
        {
            while (true)
            {
                try
                {
                    string resp = "";
                    WebSocketReceiveResult webSocketResp;
                    if (SubscriptionWebSocket.State == WebSocketState.Open)
                    {
                        do
                        {
                            ArraySegment <byte> bytesReceived = new ArraySegment <byte>(new byte[1000]);
                            webSocketResp = await SubscriptionWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None);

                            resp += Encoding.ASCII.GetString(bytesReceived.Array, 0, webSocketResp.Count);
                        }while (!webSocketResp.EndOfMessage);

                        WebSocketMessage wsResp = JsonConvert.DeserializeObject <WebSocketMessage>(resp);

                        if (wsResp.Msg == "ClientLoginResponse")
                        {
                            ClientLoginResponse loginReponse = JsonConvert.DeserializeObject <ClientLoginResponse>(resp);

                            DoLog(string.Format("Client {0} succesfully logged. Token {1}", loginReponse.UserId, loginReponse.JsonWebToken));
                        }
                        else if (wsResp.Msg == "ClientReject")
                        {
                            ClientReject loginRejected = JsonConvert.DeserializeObject <ClientReject>(resp);
                            DoLog(string.Format("Login rejected for user {0}. Reason: {1}", loginRejected.UserId, loginRejected.RejectReason));
                        }
                        else
                        {
                            DoLog(string.Format("Unknown message: {0}", resp));
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch (Exception ex)
                {
                    DoLog(string.Format("Error: {0}", ex.Message));
                }
            }
        }
예제 #4
0
        public async Task Run()
        {
            _logger.LogInformation("WeChat Engine Starting.....");

            var uuid = await _weChatClient.GetUuid();

            GenerateQR(UrlEndpoints.QRCode + uuid);

            _clientLoginResponse = await WaitForLogin(uuid);

            _webLoginResponse = await Login(_clientLoginResponse);

            _weChatInitResponse = await InitApp(_webLoginResponse, _clientLoginResponse);

            await GetContacts();

            SyncMessage();
            IsReady = true;
            _logger.LogInformation("WeChat Engine Started.....");
        }
예제 #5
0
        protected virtual void ProcessClientLoginMock(IWebSocketConnection socket, string m)
        {
            WebSocketLoginMessage wsLogin = JsonConvert.DeserializeObject <WebSocketLoginMessage>(m);


            UserRecord loggedUser = UserRecords.Where(x => x.UserId == wsLogin.UserId).FirstOrDefault();

            DoLog(string.Format("Incoming Login request for user {0}", wsLogin.UUID), MessageType.Information);

            if (loggedUser != null)
            {
                ClientLoginResponse resp = new ClientLoginResponse()
                {
                    Msg          = "ClientLoginResponse",
                    Sender       = wsLogin.Sender,
                    UUID         = wsLogin.UUID,
                    UserId       = wsLogin.UserId,
                    JsonWebToken = _TOKEN
                };


                DoLog(string.Format("user {0} Successfully logged in", wsLogin.UUID), MessageType.Information);
                UserLogged = true;
                DoSend <ClientLoginResponse>(socket, resp);
            }
            else
            {
                ClientReject reject = new ClientReject()
                {
                    Msg          = "ClientReject",
                    Sender       = wsLogin.Sender,
                    UUID         = wsLogin.UUID,
                    UserId       = wsLogin.UserId,
                    RejectReason = string.Format("Invalid user or password")
                };

                DoLog(string.Format("user {0} Rejected because of wrong user or password", wsLogin.UUID), MessageType.Information);
                DoSend <ClientReject>(socket, reject);
                socket.Close();
            }
        }
예제 #6
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                Thread publishOrderBookThread = new Thread(PublishOrderBookThread);
                publishOrderBookThread.Start();

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                SubscribeOrderBook();
            }
            if (msg is DepthOfBook)
            {
                DepthOfBook depthOfBookDelta = (DepthOfBook)msg;
                ProcessDepthOfBook(depthOfBookDelta);
            }
        }
예제 #7
0
        private async Task <WebLoginResponse> Login(ClientLoginResponse response)
        {
            if (response.RedirectUri.Length < 4)
            {
                _logger.LogError("[ERROR] Login failed due to network problem, please try again.");
                return(null);
            }

            var cookie  = new CookieContainer();
            var handler = new HttpClientHandler
            {
                UseCookies      = true,
                CookieContainer = cookie
            };
            var http      = new HttpClient(handler);
            var serverRes = await http.GetAsync(response.RedirectUri);

            var result = await serverRes.Content.ReadAsStringAsync();

            _weChatMessageClient = new WeChatMessageClient(http, _loggerFactory);

            return(Utility.XmlDeserialize <WebLoginResponse>(result, rep => rep.PassTicket = rep.PassTicket.UrlDecode()));
        }
예제 #8
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                Thread publishOrderBookThread = new Thread(PublishOrderBookThread);
                publishOrderBookThread.Start();

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                SubscribeLastSales();
                SubscribeQuotes();
                Thread.Sleep(1000);
                SubscribeOrderBook();
            }
            else if (msg is DepthOfBook)
            {
                DepthOfBook depthOfBookDelta = (DepthOfBook)msg;
                ProcessDepthOfBook(depthOfBookDelta);
            }
            else if (msg is LastSale)
            {
                LastSale lastSale = (LastSale)msg;
                DoLog(string.Format("Received last sale for symbol {1}: {0}", lastSale.LastPrice, lastSale.Symbol));
            }
            else if (msg is Quote)
            {
                Quote quote = (Quote)msg;
                DoLog(string.Format("Received quote for symbol {4}: Bid {0}-{1} -- Ask {2}-{3}",
                                    quote.BidSize, quote.Bid, quote.AskSize, quote.Ask, quote.Symbol));
            }
        }
예제 #9
0
        public ProductionAccess(string username, string password, string applicationKey)
        {
            ClientLoginRequest loginRequest = new ClientLoginRequest(username, password, applicationKey);

            timerRequest          = new System.Timers.Timer(60000);
            timerRequest.Elapsed += new ElapsedEventHandler(stopRequest);
            timerRequest.Enabled  = true;
            errorFlag             = true;
            try
            {
                ClientLoginResponse loginResponse = Authclient.ClientLogin(loginRequest);
                timerRequest.Elapsed += new ElapsedEventHandler(stopRequest);
                timerRequest.Enabled  = true;
                if (!isRequestTimeout)
                {
                    userSecurityToken = loginResponse.ClientLoginResult;
                    errorFlag         = false;
                }
            }
            catch (Exception e)
            {
                exceptionerror = e.Message;
            }
        }
예제 #10
0
        public override async void ReadResponses(object param)
        {
            while (true)
            {
                try
                {
                    string resp = "";
                    WebSocketReceiveResult webSocketResp;
                    if (SubscriptionWebSocket.State == WebSocketState.Open)
                    {
                        do
                        {
                            ArraySegment <byte> bytesReceived = new ArraySegment <byte>(new byte[1000]);
                            webSocketResp = await SubscriptionWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None);

                            resp += Encoding.ASCII.GetString(bytesReceived.Array, 0, webSocketResp.Count);
                        }while (!webSocketResp.EndOfMessage);

                        if (resp != "")
                        {
                            WebSocketMessageV2 wsResp = JsonConvert.DeserializeObject <WebSocketMessageV2>(resp);

                            if (wsResp.Msg == "ClientLoginResponse")
                            {
                                ClientLoginResponse loginReponse = JsonConvert.DeserializeObject <ClientLoginResponse>(resp);
                                OnEvent(loginReponse);
                            }

                            else if (wsResp.Msg == "ClientLogout")
                            {
                                ClientLogout logoutReponse = JsonConvert.DeserializeObject <ClientLogout>(resp);
                                OnEvent(logoutReponse);
                            }
                            else if (wsResp.Msg == "ClientLogout")
                            {
                                ClientOrderAck clientOrderAck = JsonConvert.DeserializeObject <ClientOrderAck>(resp);
                                OnEvent(clientOrderAck);
                            }
                            else if (wsResp.Msg == "ClientOrderRej")
                            {
                                ClientOrderRej clientOrderRej = JsonConvert.DeserializeObject <ClientOrderRej>(resp);
                                OnEvent(clientOrderRej);
                            }
                            else if (wsResp.Msg == "TokenResponse")
                            {
                                TokenResponse tokenReponse = JsonConvert.DeserializeObject <TokenResponse>(resp);
                                OnEvent(tokenReponse);
                            }
                            else if (wsResp.Msg == "SubscriptionResponse")
                            {
                                SubscriptionResponse msg = JsonConvert.DeserializeObject <SubscriptionResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientAccountRecord")
                            {
                                ClientAccountRecord msg = JsonConvert.DeserializeObject <ClientAccountRecord>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientLastSale")
                            {
                                ClientLastSale msg = JsonConvert.DeserializeObject <ClientLastSale>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientBestBidOffer")
                            {
                                ClientBestBidOffer msg = JsonConvert.DeserializeObject <ClientBestBidOffer>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientMarketState")
                            {
                                ClientMarketState msg = JsonConvert.DeserializeObject <ClientMarketState>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientInstrument")
                            {
                                ClientInstrument msg = JsonConvert.DeserializeObject <ClientInstrument>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "DailySettlementPrice")
                            {
                                ClientDSP msg = JsonConvert.DeserializeObject <ClientDSP>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientOrderAck")
                            {
                                ClientOrderAck msg = JsonConvert.DeserializeObject <ClientOrderAck>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientOrderRej")
                            {
                                ClientOrderRej msg = JsonConvert.DeserializeObject <ClientOrderRej>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientOrderReq")
                            {
                                ClientOrderReq msg = JsonConvert.DeserializeObject <ClientOrderReq>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "FirmsCreditLimitUpdateResponse")
                            {
                                FirmsCreditLimitUpdateResponse msg = JsonConvert.DeserializeObject <FirmsCreditLimitUpdateResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "FirmsTradingStatusUpdateResponse")
                            {
                                FirmsTradingStatusUpdateResponse msg = JsonConvert.DeserializeObject <FirmsTradingStatusUpdateResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "EmailNotificationsListResponse")
                            {
                                EmailNotificationsListResponse msg = JsonConvert.DeserializeObject <EmailNotificationsListResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "EmailNotificationsCreateResponse")
                            {
                                EmailNotificationsCreateResponse msg = JsonConvert.DeserializeObject <EmailNotificationsCreateResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "EmailNotificationsUpdateResponse")
                            {
                                EmailNotificationsUpdateResponse msg = JsonConvert.DeserializeObject <EmailNotificationsUpdateResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "EmailNotificationsDeleteResponse")
                            {
                                EmailNotificationsDeleteResponse msg = JsonConvert.DeserializeObject <EmailNotificationsDeleteResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "FirmsListResponse")
                            {
                                FirmsListResponse msg = JsonConvert.DeserializeObject <FirmsListResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientMassCancelResponse")
                            {
                                ClientMassCancelResponse msg = JsonConvert.DeserializeObject <ClientMassCancelResponse>(resp);
                                OnEvent(msg);
                            }
                            else if (wsResp.Msg == "ClientHeartbeat")
                            {
                                OnEvent(JsonConvert.DeserializeObject <ClientHeartbeat>(resp));
                            }
                            else
                            {
                                UnknownMessageV2 unknownMsg = new UnknownMessageV2()
                                {
                                    Msg    = "UnknownMsg",
                                    Resp   = resp,
                                    Reason = string.Format("Unknown message: {0}", resp)
                                };
                                OnEvent(unknownMsg);
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch (Exception ex)
                {
                    ErrorMessageV2 errorMsg = new ErrorMessageV2()
                    {
                        Msg = "ErrorMsg", Error = ex.Message
                    };
                    OnEvent(errorMsg);
                }
            }
        }
예제 #11
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                SubscribeUserRecord(loginResp);
            }
            else if (msg is UserRecord)
            {
                //3.1-We get the UserRecord for the logged user. The main field that we are interested here is the FirmId
                //we have to get all the accounts for that FirmId, and we will use those accounts to fill the Accounts Combo
                UserRecord userRecord = (UserRecord)msg;
                ShowUserRecord(userRecord);
                SubscribeAccountRecord(userRecord);
                Thread.Sleep(1000);
                //3.2-We also want to know how much of credit it's used (CREDIT USAGE).
                // The credit LIMIT is calculated at a firm level and account level
                // In the screen we will show the credit USAGE at the FIRM level.
                // So we will request a Credit Limit for the Firm and based on the selected account (Account Credit Limit)
                //   we will calculate the CREDIT USAGE.
                // So every time we change the account, we will have to calculate a new CREDIT USAGE <USAGE = CreditUsed <FirmLevel> / CreditLimit <AccountLevel>>
                //For mor info about ow to calculate the Credit Usage bar, see specs Order entry panel specs v1.x
                SubscribeCreditRecordUpdate(userRecord);
                WaitForCreditUsageBar();
            }
            else if (msg is AccountRecord)
            {
                //4.1- After subscribing for account record, I will start getting all the accounts
                //I will have to save those accounts in a Collection until the SubscriptionResponse message arrives (or the timout mechanism is activated)
                AccountRecord accRecord = (AccountRecord)msg;

                AccountRecords.Add(accRecord);
            }
            else if (msg is CreditRecordUpdate)
            {
                //5.1- After subscribing for credit record updates, I will start getting all the credit records
                //I will have to save those recordsuntil the SubscriptionResponse message arrives (or the timout mechanism is activated)
                CreditRecordUpdate = (CreditRecordUpdate)msg;
            }
            else if (msg is SubscriptionResponse)
            {
                SubscriptionResponse subscrResp = (SubscriptionResponse)msg;

                if (subscrResp.Service == "TB")
                {
                }
                else if (subscrResp.Service == "TD")
                {
                    ShowAccountRecords();
                    AccountsReceived = true;//4.2 Once we receive all the accounts , we mark the accounts as received
                }
                else if (subscrResp.Service == "CU")
                {
                    CreditUsageReceived = true;//5.2 Once we receive the credit usage for the Firm, we mark the credit usage as received
                }
                //4.2-5.2 --> Once all the accounts and the credit usage is received, we are ready to show the Credit Usage progress bar <see WaitForCreditUsageBar()>
            }
        }
예제 #12
0
 public static void SubscribeUserRecord(ClientLoginResponse loginResp)
 {
     DoSubscribe("TB", ClientLoginResponse.UserId);
 }
예제 #13
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    ClientLoginResponse = loginResp;
                }

                DoLog(string.Format("Client successfully logged with token {0}", loginResp.JsonWebToken));
                //3- Subscribe market data for Security
                //Market data will be delivered through many services, for the moment we will use
                //      LS - LastSales will have all the information regarding the trades that took place (high, low, last, etc.)
                //      LQ - QuoteService will tell us the the best offers (best buy and sell) that we have for a security.
                //           It is what fills the red/green holders that we can see in the image!
                // When we select a Product (SPOT) and Pair (XBT-USD) in the combos, we will have to fill the instrument holder (story 74)
                //      ---> In that context we only need the Quote (LQ) service
                // Only when we CLICK that instrument we will need the trades service (LS) to fill the header
                //      ---> Then we can make this call
                //Of course, every time we subscribe to some security , we will have to ususcribe to another one.
                // That will be covered in the spec document
                RequestMarketData(Security);
            }
            else if (msg is LastSale)
            {
                //4.1 LastSale event arrived! We update the security in memory with the following fields
                LastSale lastSale = (LastSale)msg;

                lock (Security)
                {
                    Security.MarketData.LastTradeDateTime       = lastSale.GetLastTime();
                    Security.MarketData.MDTradeSize             = lastSale.LastShares;
                    Security.MarketData.Trade                   = lastSale.LastPrice;
                    Security.MarketData.NominalVolume           = lastSale.Volume;
                    Security.MarketData.TradingSessionHighPrice = lastSale.High;
                    Security.MarketData.TradingSessionLowPrice  = lastSale.Low;
                    Security.MarketData.OpeningPrice            = lastSale.Open;
                    Security.MarketData.NetChgPrevDay           = lastSale.Change;
                }
                MarketDataRefresh();
            }
            else if (msg is Quote)
            {
                //4.2 Quote event arrived! We update the security in memory with the following fields
                Quote quote = (Quote)msg;

                lock (Security)
                {
                    Security.MarketData.BestBidPrice = quote.Bid;
                    Security.MarketData.BestBidSize  = quote.BidSize;
                    Security.MarketData.BestAskPrice = quote.Ask;
                    Security.MarketData.BestAskSize  = quote.AskSize;
                }
                MarketDataRefresh();
            }
            else if (msg is DailySettlementPrice)
            {
                //4.3 DailySettlementPrice event arrived! We update the security in memory with the following fields
                DailySettlementPrice DSP = (DailySettlementPrice)msg;
                lock (Security)
                {
                    Security.MarketData.SettlementPrice = DSP.Price;
                }
                MarketDataRefresh();
            }
            else if (msg is OfficialFixingPrice)
            {
                //4.4 DailySettlementPrice event arrived! We update the security in memory with the following fields
                OfficialFixingPrice fixingPrice = (OfficialFixingPrice)msg;
                lock (Security)
                {
                    Security.MarketData.FIXPrice = fixingPrice.Price;
                }
                MarketDataRefresh();
            }
            else if (msg is SubscriptionResponse)
            {
                SubscriptionResponse subscrResp = (SubscriptionResponse)msg;
                //We have to process this message to be sure that the subscription was fully processed
            }
        }
예제 #14
0
        private async Task <WeChatInitResponse> InitApp(WebLoginResponse webLoginResponse, ClientLoginResponse clientLoginResponse)
        {
            var base_request = MapperToBaseRequest(webLoginResponse);
            var body         = new
            {
                BaseRequest = base_request
            };

            string initInfo = await _weChatMessageClient.Post(clientLoginResponse.BaseUri + "/webwxinit?r=" + Utility.ConvertDateTimeToInt(DateTime.Now) + "&lang=en_US" + "&pass_ticket=" + webLoginResponse.PassTicket, JsonConvert.SerializeObject(body));

            var init = JsonConvert.DeserializeObject <WeChatInitResponse>(initInfo);

            foreach (var syncKey in init.SyncKey.List)
            {
                _syncKey += (syncKey.Key + "_" + syncKey.Val + "%7C");
            }
            _syncKey = _syncKey.TrimEnd('%', '7', 'C');

            return(init);
        }
예제 #15
0
        public virtual async void ReadResponses(object param)
        {
            while (true)
            {
                try
                {
                    string resp = "";
                    WebSocketReceiveResult webSocketResp;
                    if (SubscriptionWebSocket.State == WebSocketState.Open)
                    {
                        do
                        {
                            ArraySegment <byte> bytesReceived = new ArraySegment <byte>(new byte[1000]);
                            webSocketResp = await SubscriptionWebSocket.ReceiveAsync(bytesReceived, CancellationToken.None);

                            resp += Encoding.ASCII.GetString(bytesReceived.Array, 0, webSocketResp.Count);
                        }while (!webSocketResp.EndOfMessage);

                        if (resp != "")
                        {
                            WebSocketMessage wsResp = JsonConvert.DeserializeObject <WebSocketMessage>(resp);

                            if (wsResp.Msg == "ClientLoginResponse")
                            {
                                ClientLoginResponse loginReponse = JsonConvert.DeserializeObject <ClientLoginResponse>(resp);
                                OnEvent(loginReponse);
                            }
                            else if (wsResp.Msg == "ClientReject")
                            {
                                ClientReject loginRejected = JsonConvert.DeserializeObject <ClientReject>(resp);
                                OnEvent(loginRejected);
                            }
                            else if (wsResp.Msg == "ClientLogoutResponse")
                            {
                                ClientLogoutResponse logoutReponse = JsonConvert.DeserializeObject <ClientLogoutResponse>(resp);
                                OnEvent(logoutReponse);
                            }
                            else if (wsResp.Msg == "SubscriptionResponse")
                            {
                                SubscriptionResponse subscrResponse = JsonConvert.DeserializeObject <SubscriptionResponse>(resp);
                                OnEvent(subscrResponse);
                            }
                            else if (wsResp.Msg == "ClientHeartbeatRequest")
                            {
                                OnEvent(JsonConvert.DeserializeObject <ClientHeartbeat>(resp));
                            }
                            else if (wsResp.Msg == "AccountRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <AccountRecord>(resp));
                            }
                            else if (wsResp.Msg == "CreditRecordUpdate")
                            {
                                OnEvent(JsonConvert.DeserializeObject <CreditRecordUpdate>(resp));
                            }
                            else if (wsResp.Msg == "DailySettlementPrice")
                            {
                                OnEvent(JsonConvert.DeserializeObject <DailySettlementPrice>(resp));
                            }
                            else if (wsResp.Msg == "FirmRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <FirmRecord>(resp));
                            }
                            else if (wsResp.Msg == "OfficialFixingPrice")
                            {
                                OnEvent(JsonConvert.DeserializeObject <OfficialFixingPrice>(resp));
                            }
                            else if (wsResp.Msg == "RefereceRateMsg")
                            {
                                OnEvent(JsonConvert.DeserializeObject <RefereceRateMsg>(resp));
                            }
                            else if (wsResp.Msg == "SecurityMasterRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <SecurityMasterRecord>(resp));
                            }
                            else if (wsResp.Msg == "UserRecord")
                            {
                                OnEvent(JsonConvert.DeserializeObject <UserRecord>(resp));
                            }
                            else if (wsResp.Msg == "CreditRecordUpdate")
                            {
                                OnEvent(JsonConvert.DeserializeObject <CreditRecordUpdate>(resp));
                            }
                            else if (wsResp.Msg == "LastSale")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LastSale>(resp));
                            }
                            else if (wsResp.Msg == "Quote")
                            {
                                OnEvent(JsonConvert.DeserializeObject <Quote>(resp));
                            }
                            else if (wsResp.Msg == "DepthOfBook")
                            {
                                OnEvent(JsonConvert.DeserializeObject <DepthOfBook>(resp));
                            }
                            else if (wsResp.Msg == "LegacyOrderAck")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LegacyOrderAck>(resp));
                            }
                            else if (wsResp.Msg == "LegacyOrderCancelRejAck")
                            {
                                OnEvent(JsonConvert.DeserializeObject <LegacyOrderCancelRejAck>(resp));
                            }
                            else
                            {
                                UnknownMessage unknownMsg = new UnknownMessage()
                                {
                                    Msg    = "UnknownMsg",
                                    Resp   = resp,
                                    Reason = string.Format("Unknown message: {0}", resp)
                                };
                                OnEvent(unknownMsg);
                            }
                        }
                    }
                    else
                    {
                        Thread.Sleep(1000);
                    }
                }
                catch (Exception ex)
                {
                    ErrorMessage errorMsg = new ErrorMessage()
                    {
                        Msg = "ErrorMsg", Error = ex.Message
                    };
                    OnEvent(errorMsg);
                }
            }
        }
예제 #16
0
        private static void ProcessEvent(WebSocketMessageV2 msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    UUID   = loginResp.Uuid;
                    UserId = loginResp.UserId;
                    Token  = loginResp.JsonWebToken;
                    FirmId = null;
                }

                ProcessJsonMessage <ClientLoginResponse>(loginResp);
            }
            else if (msg is TokenResponse)
            {
                ProcessTokenResponse(msg);
            }
            else if (msg is ClientLogout)
            {
                ClientLogout logoutResp = (ClientLogout)msg;

                Token  = null;
                UserId = UserId;
                FirmId = null;
                UUID   = null;

                ProcessJsonMessage <ClientLogout>((ClientLogout)msg);
            }
            else if (msg is ClientHeartbeat)
            {
                ClientHeartbeat heartBeat = (ClientHeartbeat)msg;
                ProcessJsonMessage <ClientHeartbeat>((ClientHeartbeat)msg);
                ProcessHeartbeat(heartBeat);
            }
            else if (msg is SubscriptionResponse)
            {
                ProcessJsonMessage <SubscriptionResponse>((SubscriptionResponse)msg);
            }
            else if (msg is ClientAccountRecord)
            {
                ProcessJsonMessage <ClientAccountRecord>((ClientAccountRecord)msg);
            }
            else if (msg is ClientLastSale)
            {
                ProcessJsonMessage <ClientLastSale>((ClientLastSale)msg);
            }
            else if (msg is FirmsTradingStatusUpdateResponse)
            {
                ProcessJsonMessage <FirmsTradingStatusUpdateResponse>((FirmsTradingStatusUpdateResponse)msg);
            }
            else if (msg is ClientBestBidOffer)
            {
                ProcessJsonMessage <ClientBestBidOffer>((ClientBestBidOffer)msg);
            }
            else if (msg is ClientMarketState)
            {
                ProcessJsonMessage <ClientMarketState>((ClientMarketState)msg);
            }
            else if (msg is ClientInstrument)
            {
                ProcessJsonMessage <ClientInstrument>((ClientInstrument)msg);
            }
            else if (msg is ClientOrderAck)
            {
                ProcessJsonMessage <ClientOrderAck>((ClientOrderAck)msg);
            }
            else if (msg is ClientOrderRej)
            {
                ProcessJsonMessage <ClientOrderRej>((ClientOrderRej)msg);
            }
            else if (msg is ClientMassCancelResponse)
            {
                ProcessJsonMessage <ClientMassCancelResponse>((ClientMassCancelResponse)msg);
            }
            else if (msg is ClientOrderReq)
            {
                ProcessJsonMessage <ClientOrderReq>((ClientOrderReq)msg);
            }
            else if (msg is ClientDSP)
            {
                ProcessJsonMessage <ClientDSP>((ClientDSP)msg);
            }
            else if (msg is FirmsListResponse)
            {
                FirmsListResponse resp = (FirmsListResponse)msg;
                resp.Firms.ToList().ForEach(x => SettlementAgentDict.Add(x.FirmId.ToString(), resp.SettlementAgentId));
                ProcessJsonMessage <FirmsListResponse>(resp);
            }
            else if (msg is FirmsCreditLimitUpdateResponse)
            {
                ProcessJsonMessage <FirmsCreditLimitUpdateResponse>((FirmsCreditLimitUpdateResponse)msg);
            }
            else if (msg is FirmsTradingStatusUpdateResponse)
            {
                ProcessJsonMessage <FirmsTradingStatusUpdateResponse>((FirmsTradingStatusUpdateResponse)msg);
            }
            else if (msg is EmailNotificationsListResponse)
            {
                ProcessJsonMessage <EmailNotificationsListResponse>((EmailNotificationsListResponse)msg);
            }
            else if (msg is EmailNotificationsCreateResponse)
            {
                ProcessJsonMessage <EmailNotificationsCreateResponse>((EmailNotificationsCreateResponse)msg);
            }
            else if (msg is EmailNotificationsUpdateResponse)
            {
                ProcessJsonMessage <EmailNotificationsUpdateResponse>((EmailNotificationsUpdateResponse)msg);
            }
            else if (msg is EmailNotificationsDeleteResponse)
            {
                ProcessJsonMessage <EmailNotificationsDeleteResponse>((EmailNotificationsDeleteResponse)msg);
            }
            else if (msg is UnknownMessageV2)
            {
                UnknownMessageV2 unknownMsg = (UnknownMessageV2)msg;

                DoLog(string.Format("<<unknown {0}", unknownMsg.Resp));
            }
            else if (msg is ErrorMessageV2)
            {
                ErrorMessageV2 errorMsg = (ErrorMessageV2)msg;

                DoLog(string.Format("<<unknown {0}", errorMsg.Error));
            }
            else
            {
                DoLog(string.Format("<<Unknown message type {0}", msg.ToString()));
            }

            Console.WriteLine();
        }
예제 #17
0
        private static void ProcessEvent(WebSocketMessage msg)
        {
            if (msg is ClientLoginResponse)
            {
                ClientLoginResponse loginResp = (ClientLoginResponse)msg;

                if (loginResp.JsonWebToken != null)
                {
                    JWTToken = loginResp.JsonWebToken;
                    UUID     = loginResp.UUID;
                    UserId   = loginResp.UserId;
                }

                ProcessJsonMessage <ClientLoginResponse>(loginResp);
            }
            else if (msg is ClientReject)
            {
                ProcessJsonMessage <ClientReject>((ClientReject)msg);
            }
            else if (msg is SubscriptionResponse)
            {
                ProcessJsonMessage <SubscriptionResponse>((SubscriptionResponse)msg);
            }
            else if (msg is AccountRecord)
            {
                ProcessJsonMessage <AccountRecord>((AccountRecord)msg);
            }
            else if (msg is DailySettlementPrice)
            {
                ProcessJsonMessage <DailySettlementPrice>((DailySettlementPrice)msg);
            }
            else if (msg is FirmRecord)
            {
                ProcessJsonMessage <FirmRecord>((FirmRecord)msg);
            }
            else if (msg is OfficialFixingPrice)
            {
                ProcessJsonMessage <OfficialFixingPrice>((OfficialFixingPrice)msg);
            }
            else if (msg is RefereceRateMsg)
            {
                ProcessJsonMessage <RefereceRateMsg>((RefereceRateMsg)msg);
            }
            else if (msg is SecurityMasterRecord)
            {
                ProcessJsonMessage <SecurityMasterRecord>((SecurityMasterRecord)msg);
            }
            else if (msg is UserRecord)
            {
                ProcessJsonMessage <UserRecord>((UserRecord)msg);
            }
            else if (msg is LastSale)
            {
                ProcessJsonMessage <LastSale>((LastSale)msg);
            }
            else if (msg is Quote)
            {
                ProcessJsonMessage <Quote>((Quote)msg);
            }
            else if (msg is CreditRecordUpdate)
            {
                ProcessJsonMessage <CreditRecordUpdate>((CreditRecordUpdate)msg);
            }
            else if (msg is DepthOfBook)
            {
                ProcessJsonMessage <DepthOfBook>((DepthOfBook)msg);
            }
            else if (msg is LegacyOrderAck)
            {
                ProcessJsonMessage <LegacyOrderAck>((LegacyOrderAck)msg);
            }
            else if (msg is LegacyOrderCancelRejAck)
            {
                ProcessJsonMessage <LegacyOrderCancelRejAck>((LegacyOrderCancelRejAck)msg);
            }
            else if (msg is ClientLogoutResponse)
            {
                ClientLogoutResponse logoutResp = (ClientLogoutResponse)msg;

                JWTToken = null;
                UserId   = null;
                UUID     = null;

                ProcessJsonMessage <ClientLogoutResponse>((ClientLogoutResponse)msg);
            }
            else if (msg is ClientHeartbeat)
            {
                ClientHeartbeat heartBeatReq = (ClientHeartbeat)msg;
                ProcessJsonMessage <ClientHeartbeat>((ClientHeartbeat)msg);
                ProcessHeartbeat(heartBeatReq.SeqNum);
            }
            else if (msg is UnknownMessage)
            {
                UnknownMessage unknownMsg = (UnknownMessage)msg;

                DoLog(string.Format("<<unknown {0}", unknownMsg.Resp));
            }
            else if (msg is ErrorMessage)
            {
                ErrorMessage errorMsg = (ErrorMessage)msg;

                DoLog(string.Format("<<unknown {0}", errorMsg.Error));
            }
            else
            {
                DoLog(string.Format("<<Unknown message type {0}", msg.ToString()));
            }

            Console.WriteLine();
        }