forked from jmoral4/TradeStationWebApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TradeStationWebAPI.cs
304 lines (252 loc) · 11.1 KB
/
TradeStationWebAPI.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Web;
namespace TradeStationWebApiDemo
{
public class TradeStationWebApi
{
private string Key { get; set; }
private string Secret { get; set; }
private string Host { get; set; }
private string RedirectUri { get; set; }
private AccessToken Token { get; set; }
private readonly HttpClient _httpClient = new();
public TradeStationWebApi(string key, string secret, string environment, string redirecturi)
{
this.Key = key;
this.Secret = secret;
this.RedirectUri = redirecturi;
if (environment.Equals("LIVE")) this.Host = "https://api.tradestation.com/v2";
if (environment.Equals("SIM")) this.Host = "https://sim.api.tradestation.com/v2";
// Disable Tls 1.0 and use Tls 1.2
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
this.Token = GetAccessToken(GetAuthorizationCode()).Result; // Note: this blocking call is for the sake of the example
}
private string GetAuthorizationCode()
{
// Display the authorization URL
Console.WriteLine("Go here and login:");
Console.WriteLine(string.Format("{0}/{1}", this.Host,
string.Format(
"authorize?client_id={0}&response_type=code&redirect_uri={1}",
this.Key,
this.RedirectUri)));
// Ask the user to manually enter the code
Console.WriteLine("\nAfter authorizing the application, you will be redirected to a webpage.");
Console.WriteLine("Please copy the 'code' parameter from the redirected URL and paste it here.");
// Read the code from the console
string code = Console.ReadLine();
code = code.Replace("%3D", "=");
return code;
}
private string GetAuthorizationCode2()
{
Console.WriteLine("Go here and login:");
Console.WriteLine(string.Format("{0}/{1}", this.Host,
string.Format(
"authorize?client_id={0}&response_type=code&redirect_uri={1}",
this.Key,
this.RedirectUri)));
using (var listener = new HttpListener())
{
listener.Prefixes.Add(this.RedirectUri);
listener.Start();
Console.WriteLine("\nEmbedded HTTP Server is Listening for Authorization Code...");
var context = listener.GetContext();
var req = context.Request;
var res = context.Response;
var responseString = "<html><body><script>window.open('','_self').close();</script></body></html>";
var buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
res.ContentLength64 = buffer.Length;
var output = res.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.Stop();
return req.QueryString.Get("code");
}
}
private async Task<AccessToken> GetAccessToken(string authcode)
{
Console.WriteLine("Trading the Auth Code for an Access Token...");
var requestUri = $"{Host}/security/authorize";
var postData = new Dictionary<string, string>
{
["grant_type"] = "authorization_code",
["code"] = authcode,
["client_id"] = Key,
["redirect_uri"] = RedirectUri,
["client_secret"] = Secret
};
using var content = new FormUrlEncodedContent(postData);
try
{
var response = await _httpClient.PostAsync(requestUri, content);
var responseBody = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<AccessToken>(responseBody);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Environment.Exit(-1);
throw;
}
}
private async Task<T> GetDeserializedResponse<T>(HttpRequestMessage request)
{
var response = await _httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseBody);
}
internal async Task<IEnumerable<Symbol>> SymbolSuggest(string suggestText)
{
var resourceUri = new Uri($"{this.Host}/data/symbols/suggest/{suggestText}?oauth_token={this.Token.access_token}");
Console.WriteLine("Searching for symbols ... ");
try
{
var response = await _httpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<IEnumerable<Symbol>>(content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
internal async Task<IEnumerable<AccountInfo>> GetUserAccounts()
{
var resourceUri = new Uri($"{this.Host}/users/{this.Token.userid}/accounts?oauth_token={this.Token.access_token}");
Console.WriteLine("Getting Accounts");
try
{
var response = await _httpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<IEnumerable<AccountInfo>>(content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
internal async Task GetQuoteChanges(string symbols)
{
var resourceUri = new Uri($"{this.Host}/stream/quote/changes/{symbols}?oauth_token={this.Token.access_token}");
Console.WriteLine("Streaming Quote/Changes");
try
{
using var response = await _httpClient.GetStreamAsync(resourceUri);
using var reader = new StreamReader(response, Encoding.UTF8);
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync();
if (line == null) break;
var quote = JsonSerializer.Deserialize<Quote>(line);
Console.WriteLine($"{quote.Symbol}: ASK = {quote.Ask}; BID = {quote.Bid}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
public async Task<IEnumerable<OrderDetail>> GetOrders(IEnumerable<int> accountKeys)
{
var resourceUri = new Uri($"{this.Host}/accounts/{String.Join(",", accountKeys)}/orders?oauth_token={this.Token.access_token}");
Console.WriteLine("Getting Orders");
try
{
var response = await _httpClient.GetAsync(resourceUri);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<IEnumerable<OrderDetail>>(content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
public async Task<IEnumerable<Quote>> GetQuotes(IEnumerable<string> symbols)
{
// encode symbols (eg: replace " " with "%20")
var encodedSymbols = symbols.Select(symbol =>
{
var urlEncode = System.Web.HttpUtility.UrlEncode(symbol);
return urlEncode != null ? urlEncode.Replace("+", "%20") : null;
});
var resourceUri = new Uri($"{this.Host}/data/quote/{String.Join(",", encodedSymbols)}?oauth_token={this.Token.access_token}");
Console.WriteLine("Getting Quotes");
try
{
var response = await _httpClient.GetStringAsync(resourceUri);
return JsonSerializer.Deserialize<IEnumerable<Quote>>(response);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
public async Task<IEnumerable<Confirmation>> GetConfirmations(Order order)
{
var orderJson = JsonSerializer.Serialize(order);
var resourceUri = new Uri($"{this.Host}/orders/confirm?oauth_token={this.Token.access_token}");
Console.WriteLine("Getting Order Confirmation");
using var content = new StringContent(orderJson, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync(resourceUri, content);
var responseContent = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<IEnumerable<Confirmation>>(responseContent);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
Environment.Exit(-1);
throw;
}
}
public async Task<IEnumerable<OrderResult>> PlaceOrder(Order order)
{
var requestUri = $"{Host}/orders?oauth_token={Token.access_token}";
Console.WriteLine("Placing Order");
var orderjson = JsonSerializer.Serialize(order);
using var content = new StringContent(orderjson, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync(requestUri, content);
var responseBody = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<IEnumerable<OrderResult>>(responseBody);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Environment.Exit(-1);
throw;
}
}
}
}