private void ConnectWebSocketEndpoint <T>(Uri endpoint, WebSocketMessageHandler <T> messageHandler, ResponseParseHandler <T> customParseHandler = null) where T : WebSocketMessageBase
        {
            var ws = CreateNewWebSocket(endpoint);

            ws.OnMessage += (sender, e) =>
            {
                logger.Debug("Msg: " + e.Data);
                var eventData = customParseHandler == null?
                                JsonConvert.DeserializeObject <T>(e.Data) :
                                    customParseHandler(e.Data);

                messageHandler(eventData);
            };
            ws.Connect();
            ActiveSockets.Add(ws);
        }
Example #2
0
        protected async Task <T> SendRequest <T>(string methodName, string version, ApiMethodType apiMethod, HttpMethod httpMethod,
                                                 Dictionary <string, string> parameters = null, ResponseParseHandler <T> customHandler = null)
        {
            if ((apiMethod == ApiMethodType.ApiKey && string.IsNullOrEmpty(_apiKey)) ||
                (apiMethod == ApiMethodType.Signed &&
                 (string.IsNullOrEmpty(_apiKey) || string.IsNullOrEmpty(_apiSecret))))
            {
                throw new Exception("You have to instantiate client with proper keys in order to make ApiKey or Signed API requests!");
            }

            if (parameters == null)
            {
                parameters = new Dictionary <string, string>();
            }

            if (apiMethod == ApiMethodType.Signed)
            {
                var timestamp = Util.GetCurrentMilliseconds();
                parameters.Add("timestamp", timestamp.ToString(CultureInfo.InvariantCulture));

                var parameterTextForSignature = GetParameterText(parameters);
                var signedBytes = Util.Sign(_apiSecret, parameterTextForSignature);
                parameters.Add("signature", Util.GetHexString(signedBytes));
            }

            var parameterTextPrefix = parameters.Count > 0 ? "?" : string.Empty;
            var parameterText       = GetParameterText(parameters);

            string response;

            using (var client = new WebClient())
            {
                if (apiMethod == ApiMethodType.Signed || apiMethod == ApiMethodType.ApiKey)
                {
                    client.Headers.Add("X-MBX-APIKEY", _apiKey);
                }

                try
                {
                    var getRequestUrl  = $"{BaseUrl}/{version}/{methodName}{parameterTextPrefix}{parameterText}";
                    var postRequestUrl = $"{BaseUrl}/{version}/{methodName}";

                    response = httpMethod == HttpMethod.Get ?
                               await client.DownloadStringTaskAsync(getRequestUrl) :
                               await client.UploadStringTaskAsync(postRequestUrl, httpMethod.Method, parameterText);
                }
                catch (WebException webException)
                {
                    using (var reader = new StreamReader(webException.Response.GetResponseStream(), Encoding.UTF8))
                    {
                        var errorObject  = JObject.Parse(reader.ReadToEnd());
                        var errorCode    = (int)errorObject["code"];
                        var errorMessage = (string)errorObject["msg"];
                        throw new Exception($"{errorCode}{errorMessage}");
                    }
                }
            }
            return(customHandler != null?customHandler(response) : JsonConvert.DeserializeObject <T>(response));
        }