Example #1
0
        /// <summary>
        /// Place a secure request and get back an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="result">Result object from the </param>
        /// <returns>T typed object response</returns>
        public bool TryRequest <T>(RestRequest request, out T result)
            where T : RestResponse
        {
            var responseContent = string.Empty;

            try
            {
                //Generate the hash each request
                // Add the UTC timestamp to the request header.
                // Timestamps older than 1800 seconds will not work.
                var timestamp = (int)Time.TimeStamp();
                var hash      = Api.CreateSecureHash(timestamp, _token);
                request.AddHeader("Timestamp", timestamp.ToStringInvariant());

                Client.Authenticator = new HttpBasicAuthenticator(_userId, hash);

                // Execute the authenticated REST API Call
                var restsharpResponse = Client.Execute(request);

                // Use custom converter for deserializing live results data
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    Converters = { new LiveAlgorithmResultsJsonConverter(), new OrderJsonConverter() }
                };

                //Verify success
                if (restsharpResponse.ErrorException != null)
                {
                    Log.Error($"ApiConnection.TryRequest({request.Resource}): Error: {restsharpResponse.ErrorException.Message}");
                    result = null;
                    return(false);
                }

                if (!restsharpResponse.IsSuccessful)
                {
                    Log.Error($"ApiConnect.TryRequest(): Content: {restsharpResponse.Content}");
                }

                responseContent = restsharpResponse.Content;
                result          = JsonConvert.DeserializeObject <T>(responseContent);

                if (result == null || !result.Success)
                {
                    Log.Debug($"ApiConnection.TryRequest(): Raw response: '{responseContent}'");
                    return(false);
                }
            }
            catch (Exception err)
            {
                Log.Error($"ApiConnection.TryRequest({request.Resource}): Error: {err.Message}, Response content: {responseContent}");
                result = null;
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Place a secure request and get back an object of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="result">Result object from the </param>
        /// <returns>T typed object response</returns>
        public bool TryRequest <T>(RestRequest request, out T result)
            where T : RestResponse
        {
            try
            {
                //Generate the hash each request
                // Add the UTC timestamp to the request header.
                // Timestamps older than 1800 seconds will not work.
                var timestamp = (int)Time.TimeStamp();
                var hash      = Api.CreateSecureHash(timestamp, _token);
                request.AddHeader("Timestamp", timestamp.ToString());
                Client.Authenticator = new HttpBasicAuthenticator(_userId, hash);

                // Execute the authenticated REST API Call
                var restsharpResponse = Client.Execute(request);

                // Use custom converter for deserializing live results data
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    Converters = { new LiveAlgorithmResultsJsonConverter(), new OrderJsonConverter() }
                };

                //Verify success
                result = JsonConvert.DeserializeObject <T>(restsharpResponse.Content);
                if (!result.Success)
                {
                    //result;
                    return(false);
                }
            }
            catch (Exception err)
            {
                Log.Error(err, "Api.ApiConnection() Failed to make REST request.");
                result = null;
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Initialize the web socket connection to the live data server
        /// </summary>
        public void Initialize()
        {
            _initialized = true;

            _builder = new UriBuilder(new Uri(_liveDataUrl))
            {
                Port = _liveDataPort
            };
            _ws = new WebSocket(_builder.ToString());

            var connectionRetryAttempts = 0;

            var timeStamp = (int)Time.TimeStamp();
            var hash      = Api.CreateSecureHash(timeStamp, _token);

            _ws.SetCookie(new Cookie("Timestamp", timeStamp.ToString()));
            _ws.SetCookie(new Cookie("hash", hash));
            _ws.SetCookie(new Cookie("uid", _userId.ToString()));

            // Message received from server
            _ws.OnMessage += (sender, e) =>
            {
                lock (_locker)
                {
                    IEnumerable <BaseData> baseDatas = new List <BaseData>();
                    try
                    {
                        baseDatas = BaseData.DeserializeMessage(e.Data);
                    }
                    catch
                    {
                        Log.Error("ApiWebSocketConnection.OnMessage(): An error was received from the server: {0}", e.Data);
                    }

                    foreach (var baseData in baseDatas)
                    {
                        _baseDataFromServer.Enqueue(baseData);
                    }
                }
            };

            // Error has in web socket connection
            _ws.OnError += (sender, e) =>
            {
                Log.Error("WebSocketConnection.Initialize(): Web socket connection error: {0}", e.Message);
                if (!_ws.IsAlive && connectionRetryAttempts < MaxRetryAttempts)
                {
                    Log.Trace(
                        "WebSocketConnection.Initialize(): Attempting to reconnect {0}/{1}",
                        connectionRetryAttempts, MaxRetryAttempts);

                    connectionRetryAttempts++;
                    _ws.Connect();
                }
                else
                {
                    Log.Trace(
                        "WebSocketConnection.Initialize(): Could not reconnect to web socket server. " +
                        "Closing web socket.");

                    if (_updateSubscriptions != null)
                    {
                        _updateSubscriptions -= UpdateSubscriptions;
                    }
                    _updateSubscriptions = null;
                }
            };

            // Connection was closed
            _ws.OnClose += (sender, e) =>
            {
                Log.Trace(
                    "WebSocketConnection.Initialize(): Web socket connection closed: {0}, {1}",
                    e.Code, e.Reason);

                if (!_ws.IsAlive && connectionRetryAttempts < MaxRetryAttempts && e.Code == (ushort)CloseStatusCode.Abnormal)
                {
                    Log.Error(
                        "WebSocketConnection.Initialize(): Web socket was closed abnormally. " +
                        "Attempting to reconnect {0}/{1}",
                        connectionRetryAttempts, MaxRetryAttempts);

                    connectionRetryAttempts++;
                    _ws.Connect();
                }
                else
                {
                    Log.Trace(
                        "WebSocketConnection.Initialize(): Could not reconnect to web socket server. " +
                        "Closing web socket.");

                    if (_updateSubscriptions != null)
                    {
                        _updateSubscriptions -= UpdateSubscriptions;
                    }
                    _updateSubscriptions = null;
                }
            };

            // Connection opened
            _ws.OnOpen += (sender, e) =>
            {
                SendSubscription();
                connectionRetryAttempts = 0;
            };

            _updateSubscriptions += UpdateSubscriptions;

            _ws.Connect();
        }