forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApiConnection.cs
127 lines (116 loc) · 4.57 KB
/
ApiConnection.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Newtonsoft.Json;
using QuantConnect.API;
using QuantConnect.Configuration;
using QuantConnect.Logging;
using QuantConnect.Orders;
using RestSharp;
using RestSharp.Authenticators;
namespace QuantConnect.Api
{
/// <summary>
/// API Connection and Hash Manager
/// </summary>
public class ApiConnection
{
/// <summary>
/// Authorized client to use for requests.
/// </summary>
public RestClient Client;
// Authorization Credentials
private readonly string _userId;
private readonly string _token;
/// <summary>
/// Create a new Api Connection Class.
/// </summary>
/// <param name="userId">User Id number from QuantConnect.com account. Found at www.quantconnect.com/account </param>
/// <param name="token">Access token for the QuantConnect account. Found at www.quantconnect.com/account </param>
public ApiConnection(int userId, string token)
{
_token = token;
_userId = userId.ToString();
var apiUrl = Config.Get("cloud-api-url", "https://www.quantconnect.com/api/v2/");
Client = new RestClient(apiUrl);
}
/// <summary>
/// Return true if connected successfully.
/// </summary>
public bool Connected
{
get
{
var request = new RestRequest("authenticate", Method.GET);
AuthenticationResponse response;
if (TryRequest(request, out response))
{
return response.Success;
}
return false;
}
}
/// <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.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
if (restsharpResponse.ErrorException != null)
{
Log.Error(restsharpResponse.ErrorException);
result = null;
return false;
}
responseContent = restsharpResponse.Content;
result = JsonConvert.DeserializeObject<T>(responseContent);
if (!result.Success)
{
//result;
return false;
}
}
catch (Exception err)
{
Log.Error($"Api.ApiConnection.TryRequest({request.Resource}): Failed to make REST request. Response content: {responseContent}, Error: {err}");
result = null;
return false;
}
return true;
}
}
}