tradestation_rs/
client.rs

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
305
306
307
308
309
310
311
312
313
314
315
use crate::token::RefreshedToken;
use crate::{Error, Token};
use reqwest::{header, Response};
use serde::Serialize;
use serde_json::Value;
use std::collections::HashMap;

/// TradeStation API Client
#[derive(Clone, Debug)]
pub struct Client {
    http_client: reqwest::Client,
    client_id: String,
    client_secret: String,
    /// Bearer Token for TradeStation's API
    pub token: Token,
}
impl Client {
    /// Send an HTTP request to TradeStation's API, with automatic
    /// token refreshing near, at, or after auth token expiration.
    ///
    /// NOTE: You should use `Client::post()` or `Client::get()` in favor of this method.
    pub async fn send_request<F, T>(&mut self, request_fn: F) -> Result<Response, Error>
    where
        F: Fn(&Token) -> T,
        T: std::future::Future<Output = Result<Response, reqwest::Error>>,
    {
        match request_fn(&self.token).await {
            Ok(resp) => {
                // Check if the client gets a 401 unauthorized to try and re auth the client
                // this happens when auth token expires.
                if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
                    // Refresh the clients token
                    self.refresh_token().await?;

                    // Retry sending the request to TradeStation's API
                    let retry_response = request_fn(&self.token).await?;
                    Ok(retry_response)
                } else {
                    Ok(resp)
                }
            }
            Err(e) => Err(Error::Request(e)),
        }
    }

    /// Send a POST request from your `Client` to TradeStation's API
    pub async fn post<T: Serialize>(
        &mut self,
        endpoint: &str,
        payload: &T,
    ) -> Result<Response, Error> {
        let url = format!("https://api.tradestation.com/v3/{endpoint}");
        let resp = self
            .clone()
            .send_request(|token| {
                self.http_client
                    .post(&url)
                    .header("Content-Type", "application/json")
                    .header(
                        header::AUTHORIZATION,
                        format!("Bearer {}", token.access_token),
                    )
                    .json(payload)
                    .send()
            })
            .await?;

        Ok(resp)
    }

    /// Send a GET request from your `Client` to TradeStation's API
    pub async fn get(&mut self, endpoint: &str) -> Result<Response, Error> {
        let url = format!("https://api.tradestation.com/v3/{endpoint}");
        let resp = self
            .clone()
            .send_request(|token| {
                self.http_client
                    .get(&url)
                    .header(
                        header::AUTHORIZATION,
                        format!("Bearer {}", token.access_token),
                    )
                    .send()
            })
            .await?;

        Ok(resp)
    }

    /// Start a stream from the TradeStation API to the `Client`
    ///
    /// NOTE: You need to provide a processing function for handeling the stream chunks
    pub async fn stream<F>(&mut self, endpoint: &str, mut process_chunk: F) -> Result<(), Error>
    where
        F: FnMut(Value) -> Result<(), Error>,
    {
        let url = format!("https://api.tradestation.com/v3/{endpoint}");
        let mut resp = self
            .clone()
            .send_request(|token| {
                self.http_client
                    .get(&url)
                    .header(
                        reqwest::header::AUTHORIZATION,
                        format!("Bearer {}", token.access_token),
                    )
                    .send()
            })
            .await?;

        if !resp.status().is_success() {
            return Err(Error::StreamIssue(format!(
                "Request failed with status: {}",
                resp.status()
            )));
        }

        let mut buffer = String::new();
        while let Some(chunk) = resp.chunk().await? {
            let chunk_str = std::str::from_utf8(&chunk).unwrap_or("");
            buffer.push_str(chunk_str);

            while let Some(pos) = buffer.find("\n") {
                let json_str = buffer[..pos].trim().to_string();
                buffer = buffer[pos + 1..].to_string();
                if json_str.is_empty() {
                    continue;
                }

                match serde_json::from_str::<Value>(&json_str) {
                    Ok(json_value) => {
                        if let Err(e) = process_chunk(json_value) {
                            if matches!(e, Error::StopStream) {
                                return Ok(());
                            } else {
                                return Err(e);
                            }
                        }
                    }
                    Err(e) => {
                        return Err(Error::Json(e));
                    }
                }
            }
        }

        // Handle any leftover data in the buffer
        if !buffer.trim().is_empty() {
            match serde_json::from_str::<Value>(&buffer) {
                Ok(json_value) => {
                    if let Err(e) = process_chunk(json_value) {
                        if matches!(e, Error::StopStream) {
                            return Ok(());
                        } else {
                            return Err(e);
                        }
                    }
                }
                Err(e) => {
                    return Err(Error::Json(e));
                }
            }
        }

        Ok(())
    }

    /// Refresh your clients bearer token used for authentication
    /// with TradeStation's API.
    pub async fn refresh_token(&mut self) -> Result<(), Error> {
        let form_data: HashMap<String, String> = HashMap::from([
            ("grant_type".into(), "refresh_token".into()),
            ("client_id".into(), self.client_id.clone()),
            ("client_secret".into(), self.client_secret.clone()),
            ("refresh_token".into(), self.token.refresh_token.clone()),
            ("redirect_uri".into(), "http://localhost:8080/".into()),
        ]);

        let new_token = self
            .http_client
            .post("https://signin.tradestation.com/oauth/token")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .form(&form_data)
            .send()
            .await?
            .json::<RefreshedToken>()
            .await?;

        // Update the clients token
        self.token = Token {
            refresh_token: self.token.refresh_token.clone(),
            access_token: new_token.access_token,
            id_token: new_token.id_token,
            scope: new_token.scope,
            token_type: new_token.token_type,
            expires_in: new_token.expires_in,
        };

        Ok(())
    }
}

#[derive(Debug, Default)]
/// Builder for `Client`
pub struct ClientBuilder;

#[derive(Debug, Default)]
pub struct Step1;
#[derive(Debug, Default)]
pub struct Step2;
#[derive(Debug, Default)]
pub struct Step3;

#[derive(Debug, Default)]
/// Phantom Type for compile time enforcement
/// on the order of builder steps used.
pub struct ClientBuilderStep<CurrentStep> {
    _current_step: CurrentStep,
    http_client: Option<reqwest::Client>,
    client_id: Option<String>,
    client_secret: Option<String>,
    token: Option<Token>,
}

impl ClientBuilder {
    /// Instantiate a new instance of `ClientBuilder`
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> Result<ClientBuilderStep<Step1>, Error> {
        Ok(ClientBuilderStep {
            _current_step: Step1,
            http_client: Some(reqwest::Client::new()),
            ..Default::default()
        })
    }
}
impl ClientBuilderStep<Step1> {
    /// Set your client id/key and secret
    pub fn set_credentials(
        self,
        client_id: &str,
        client_secret: &str,
    ) -> Result<ClientBuilderStep<Step2>, Error> {
        Ok(ClientBuilderStep {
            _current_step: Step2,
            http_client: Some(self.http_client.unwrap()),
            client_id: Some(client_id.into()),
            client_secret: Some(client_secret.into()),
            ..Default::default()
        })
    }
}
impl ClientBuilderStep<Step2> {
    /// Use your authorization code to get and set auth token
    pub async fn authorize(
        self,
        authorization_code: &str,
    ) -> Result<ClientBuilderStep<Step3>, Error> {
        // NOTE: These unwraps are panic safe due to type invariant
        // with compile time enforced order of steps for `ClientBuilderStep`
        let http_client = self.http_client.unwrap();
        let client_id = self.client_id.as_ref().unwrap();
        let client_secret = self.client_secret.as_ref().unwrap();

        // Send HTTP request to TradeStation API to get auth token
        let form_data = HashMap::from([
            ("grant_type", "authorization_code"),
            ("client_id", client_id),
            ("client_secret", client_secret),
            ("code", authorization_code),
            ("redirect_uri", "http://localhost:8080/"),
        ]);
        let token = http_client
            .post("https://signin.tradestation.com/oauth/token")
            .header("Content-Type", "application/x-www-form-urlencoded")
            .form(&form_data)
            .send()
            .await?
            .json::<Token>()
            .await?;

        Ok(ClientBuilderStep {
            _current_step: Step3,
            http_client: Some(http_client),
            client_id: self.client_id,
            client_secret: self.client_secret,
            token: Some(token),
        })
    }

    /// Set the current `Token` for the `Client` to use
    pub fn set_token(self, token: Token) -> Result<ClientBuilderStep<Step3>, Error> {
        Ok(ClientBuilderStep {
            _current_step: Step3,
            http_client: self.http_client,
            client_id: self.client_id,
            client_secret: self.client_secret,
            token: Some(token),
        })
    }
}
impl ClientBuilderStep<Step3> {
    pub async fn build(self) -> Result<Client, Error> {
        let http_client = self.http_client.unwrap();
        let client_id = self.client_id.unwrap();
        let client_secret = self.client_secret.unwrap();
        let token = self.token.unwrap();

        Ok(Client {
            http_client,
            client_id,
            client_secret,
            token,
        })
    }
}