Skip to main content

oanda_v20_openapi/apis/
trade_api.rs

1/*
2 * OANDA v20 API
3 *
4 * The full OANDA v20 API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
5 *
6 * The version of the OpenAPI document: 0.2.1
7 * Contact: jmicoud02@gmail.com
8 * Generated by: https://openapi-generator.tech
9 */
10
11
12use reqwest;
13use serde::{Deserialize, Serialize, de::Error as _};
14use crate::{apis::ResponseContent, models};
15use super::{Error, configuration, ContentType};
16
17
18/// struct for typed errors of method [`close_trade`]
19#[derive(Debug, Clone, Serialize, Deserialize)]
20#[serde(untagged)]
21pub enum CloseTradeError {
22    Status400(models::CloseTradeBadRequestResponse),
23    Status401(models::Error401),
24    Status404(models::CloseTradeNotFoundResponse),
25    Status405(models::Error405),
26    UnknownValue(serde_json::Value),
27}
28
29/// struct for typed errors of method [`get_open_trades`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum GetOpenTradesError {
33    Status401(models::Error401),
34    Status404(models::Error404),
35    Status405(models::Error405),
36    UnknownValue(serde_json::Value),
37}
38
39/// struct for typed errors of method [`get_trade`]
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(untagged)]
42pub enum GetTradeError {
43    Status401(models::Error401),
44    Status404(models::Error404),
45    Status405(models::Error405),
46    UnknownValue(serde_json::Value),
47}
48
49/// struct for typed errors of method [`get_trades`]
50#[derive(Debug, Clone, Serialize, Deserialize)]
51#[serde(untagged)]
52pub enum GetTradesError {
53    Status401(models::Error401),
54    Status404(models::Error404),
55    Status405(models::Error405),
56    UnknownValue(serde_json::Value),
57}
58
59/// struct for typed errors of method [`set_trade_extensions`]
60#[derive(Debug, Clone, Serialize, Deserialize)]
61#[serde(untagged)]
62pub enum SetTradeExtensionsError {
63    Status400(models::TradeExtensionsBadRequestResponse),
64    Status401(models::Error401),
65    Status404(models::TradeExtensionsNotFoundResponse),
66    Status405(models::Error405),
67    UnknownValue(serde_json::Value),
68}
69
70/// struct for typed errors of method [`set_trade_orders`]
71#[derive(Debug, Clone, Serialize, Deserialize)]
72#[serde(untagged)]
73pub enum SetTradeOrdersError {
74    Status400(models::DependentTradeOrdersBadRequestResponse),
75    Status401(models::Error401),
76    Status404(models::Error404),
77    Status405(models::Error405),
78    UnknownValue(serde_json::Value),
79}
80
81
82/// Close (partially or fully) a specific open Trade in an Account
83pub async fn close_trade(configuration: &configuration::Configuration, account_id: &str, trade_specifier: &str, close_trade_request: models::CloseTradeRequest, accept_datetime_format: Option<models::DateTimeFormat>) -> Result<models::CloseTradeResponse, Error<CloseTradeError>> {
84    // add a prefix to parameters to efficiently prevent name collisions
85    let p_account_id = account_id;
86    let p_trade_specifier = trade_specifier;
87    let p_close_trade_request = close_trade_request;
88    let p_accept_datetime_format = accept_datetime_format;
89
90    let uri_str = format!("{}/accounts/{accountId}/trades/{tradeSpecifier}/close", configuration.base_path, accountId=crate::apis::urlencode(p_account_id), tradeSpecifier=crate::apis::urlencode(p_trade_specifier));
91    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);
92
93    if let Some(ref user_agent) = configuration.user_agent {
94        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
95    }
96    if let Some(param_value) = p_accept_datetime_format {
97        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
98    }
99    if let Some(ref token) = configuration.bearer_access_token {
100        req_builder = req_builder.bearer_auth(token.to_owned());
101    };
102    req_builder = req_builder.json(&p_close_trade_request);
103
104    let req = req_builder.build()?;
105    let resp = configuration.client.execute(req).await?;
106
107    let status = resp.status();
108    let content_type = resp
109        .headers()
110        .get("content-type")
111        .and_then(|v| v.to_str().ok())
112        .unwrap_or("application/octet-stream");
113    let content_type = super::ContentType::from(content_type);
114
115    if !status.is_client_error() && !status.is_server_error() {
116        let content = resp.text().await?;
117        match content_type {
118            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
119            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::CloseTradeResponse`"))),
120            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::CloseTradeResponse`")))),
121        }
122    } else {
123        let content = resp.text().await?;
124        let entity: Option<CloseTradeError> = serde_json::from_str(&content).ok();
125        Err(Error::ResponseError(ResponseContent { status, content, entity }))
126    }
127}
128
129/// Get the list of open Trades for an Account
130pub async fn get_open_trades(configuration: &configuration::Configuration, account_id: &str, accept_datetime_format: Option<models::DateTimeFormat>) -> Result<models::OpenTradeResponse, Error<GetOpenTradesError>> {
131    // add a prefix to parameters to efficiently prevent name collisions
132    let p_account_id = account_id;
133    let p_accept_datetime_format = accept_datetime_format;
134
135    let uri_str = format!("{}/accounts/{accountId}/openTrades", configuration.base_path, accountId=crate::apis::urlencode(p_account_id));
136    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
137
138    if let Some(ref user_agent) = configuration.user_agent {
139        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
140    }
141    if let Some(param_value) = p_accept_datetime_format {
142        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
143    }
144    if let Some(ref token) = configuration.bearer_access_token {
145        req_builder = req_builder.bearer_auth(token.to_owned());
146    };
147
148    let req = req_builder.build()?;
149    let resp = configuration.client.execute(req).await?;
150
151    let status = resp.status();
152    let content_type = resp
153        .headers()
154        .get("content-type")
155        .and_then(|v| v.to_str().ok())
156        .unwrap_or("application/octet-stream");
157    let content_type = super::ContentType::from(content_type);
158
159    if !status.is_client_error() && !status.is_server_error() {
160        let content = resp.text().await?;
161        match content_type {
162            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
163            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::OpenTradeResponse`"))),
164            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::OpenTradeResponse`")))),
165        }
166    } else {
167        let content = resp.text().await?;
168        let entity: Option<GetOpenTradesError> = serde_json::from_str(&content).ok();
169        Err(Error::ResponseError(ResponseContent { status, content, entity }))
170    }
171}
172
173/// Get the details of a specific Trade in an Account
174pub async fn get_trade(configuration: &configuration::Configuration, account_id: &str, trade_specifier: &str, accept_datetime_format: Option<models::DateTimeFormat>) -> Result<models::TradeResponse, Error<GetTradeError>> {
175    // add a prefix to parameters to efficiently prevent name collisions
176    let p_account_id = account_id;
177    let p_trade_specifier = trade_specifier;
178    let p_accept_datetime_format = accept_datetime_format;
179
180    let uri_str = format!("{}/accounts/{accountId}/trades/{tradeSpecifier}", configuration.base_path, accountId=crate::apis::urlencode(p_account_id), tradeSpecifier=crate::apis::urlencode(p_trade_specifier));
181    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
182
183    if let Some(ref user_agent) = configuration.user_agent {
184        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
185    }
186    if let Some(param_value) = p_accept_datetime_format {
187        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
188    }
189    if let Some(ref token) = configuration.bearer_access_token {
190        req_builder = req_builder.bearer_auth(token.to_owned());
191    };
192
193    let req = req_builder.build()?;
194    let resp = configuration.client.execute(req).await?;
195
196    let status = resp.status();
197    let content_type = resp
198        .headers()
199        .get("content-type")
200        .and_then(|v| v.to_str().ok())
201        .unwrap_or("application/octet-stream");
202    let content_type = super::ContentType::from(content_type);
203
204    if !status.is_client_error() && !status.is_server_error() {
205        let content = resp.text().await?;
206        match content_type {
207            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
208            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TradeResponse`"))),
209            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TradeResponse`")))),
210        }
211    } else {
212        let content = resp.text().await?;
213        let entity: Option<GetTradeError> = serde_json::from_str(&content).ok();
214        Err(Error::ResponseError(ResponseContent { status, content, entity }))
215    }
216}
217
218/// Get a list of Trades for an Account
219pub async fn get_trades(configuration: &configuration::Configuration, account_id: &str, accept_datetime_format: Option<models::DateTimeFormat>, ids: Option<Vec<i32>>, state: Option<&str>, instrument: Option<models::InstrumentName>, count: Option<i32>, before_id: Option<i32>) -> Result<models::TradesResponse, Error<GetTradesError>> {
220    // add a prefix to parameters to efficiently prevent name collisions
221    let p_account_id = account_id;
222    let p_accept_datetime_format = accept_datetime_format;
223    let p_ids = ids;
224    let p_state = state;
225    let p_instrument = instrument;
226    let p_count = count;
227    let p_before_id = before_id;
228
229    let uri_str = format!("{}/accounts/{accountId}/trades", configuration.base_path, accountId=crate::apis::urlencode(p_account_id));
230    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
231
232    if let Some(ref param_value) = p_ids {
233        req_builder = match "csv" {
234            "multi" => req_builder.query(&param_value.into_iter().map(|p| ("ids".to_owned(), p.to_string())).collect::<Vec<(std::string::String, std::string::String)>>()),
235            _ => req_builder.query(&[("ids", &param_value.into_iter().map(|p| p.to_string()).collect::<Vec<String>>().join(",").to_string())]),
236        };
237    }
238    if let Some(ref param_value) = p_state {
239        req_builder = req_builder.query(&[("state", &param_value.to_string())]);
240    }
241    if let Some(ref param_value) = p_instrument {
242        req_builder = req_builder.query(&[("instrument", &param_value.to_string())]);
243    }
244    if let Some(ref param_value) = p_count {
245        req_builder = req_builder.query(&[("count", &param_value.to_string())]);
246    }
247    if let Some(ref param_value) = p_before_id {
248        req_builder = req_builder.query(&[("beforeID", &param_value.to_string())]);
249    }
250    if let Some(ref user_agent) = configuration.user_agent {
251        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
252    }
253    if let Some(param_value) = p_accept_datetime_format {
254        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
255    }
256    if let Some(ref token) = configuration.bearer_access_token {
257        req_builder = req_builder.bearer_auth(token.to_owned());
258    };
259
260    let req = req_builder.build()?;
261    let resp = configuration.client.execute(req).await?;
262
263    let status = resp.status();
264    let content_type = resp
265        .headers()
266        .get("content-type")
267        .and_then(|v| v.to_str().ok())
268        .unwrap_or("application/octet-stream");
269    let content_type = super::ContentType::from(content_type);
270
271    if !status.is_client_error() && !status.is_server_error() {
272        let content = resp.text().await?;
273        match content_type {
274            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
275            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TradesResponse`"))),
276            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TradesResponse`")))),
277        }
278    } else {
279        let content = resp.text().await?;
280        let entity: Option<GetTradesError> = serde_json::from_str(&content).ok();
281        Err(Error::ResponseError(ResponseContent { status, content, entity }))
282    }
283}
284
285/// Update the Client Extensions for a Trade. Do not add, update, or delete the Client Extensions if your account is associated with MT4.
286pub async fn set_trade_extensions(configuration: &configuration::Configuration, account_id: &str, trade_specifier: &str, trade_extensions_request: models::TradeExtensionsRequest, accept_datetime_format: Option<models::DateTimeFormat>) -> Result<models::TradeExtensionsResponse, Error<SetTradeExtensionsError>> {
287    // add a prefix to parameters to efficiently prevent name collisions
288    let p_account_id = account_id;
289    let p_trade_specifier = trade_specifier;
290    let p_trade_extensions_request = trade_extensions_request;
291    let p_accept_datetime_format = accept_datetime_format;
292
293    let uri_str = format!("{}/accounts/{accountId}/trades/{tradeSpecifier}/clientExtensions", configuration.base_path, accountId=crate::apis::urlencode(p_account_id), tradeSpecifier=crate::apis::urlencode(p_trade_specifier));
294    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);
295
296    if let Some(ref user_agent) = configuration.user_agent {
297        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
298    }
299    if let Some(param_value) = p_accept_datetime_format {
300        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
301    }
302    if let Some(ref token) = configuration.bearer_access_token {
303        req_builder = req_builder.bearer_auth(token.to_owned());
304    };
305    req_builder = req_builder.json(&p_trade_extensions_request);
306
307    let req = req_builder.build()?;
308    let resp = configuration.client.execute(req).await?;
309
310    let status = resp.status();
311    let content_type = resp
312        .headers()
313        .get("content-type")
314        .and_then(|v| v.to_str().ok())
315        .unwrap_or("application/octet-stream");
316    let content_type = super::ContentType::from(content_type);
317
318    if !status.is_client_error() && !status.is_server_error() {
319        let content = resp.text().await?;
320        match content_type {
321            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
322            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::TradeExtensionsResponse`"))),
323            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::TradeExtensionsResponse`")))),
324        }
325    } else {
326        let content = resp.text().await?;
327        let entity: Option<SetTradeExtensionsError> = serde_json::from_str(&content).ok();
328        Err(Error::ResponseError(ResponseContent { status, content, entity }))
329    }
330}
331
332/// Create, replace and cancel a Trade's dependent Orders (Take Profit, Stop Loss and Trailing Stop Loss) through the Trade itself
333pub async fn set_trade_orders(configuration: &configuration::Configuration, account_id: &str, trade_specifier: &str, dependent_trade_orders_request: models::DependentTradeOrdersRequest, accept_datetime_format: Option<models::DateTimeFormat>) -> Result<models::DependentTradeOrdersResponse, Error<SetTradeOrdersError>> {
334    // add a prefix to parameters to efficiently prevent name collisions
335    let p_account_id = account_id;
336    let p_trade_specifier = trade_specifier;
337    let p_dependent_trade_orders_request = dependent_trade_orders_request;
338    let p_accept_datetime_format = accept_datetime_format;
339
340    let uri_str = format!("{}/accounts/{accountId}/trades/{tradeSpecifier}/orders", configuration.base_path, accountId=crate::apis::urlencode(p_account_id), tradeSpecifier=crate::apis::urlencode(p_trade_specifier));
341    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &uri_str);
342
343    if let Some(ref user_agent) = configuration.user_agent {
344        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
345    }
346    if let Some(param_value) = p_accept_datetime_format {
347        req_builder = req_builder.header("Accept-Datetime-Format", param_value.to_string());
348    }
349    if let Some(ref token) = configuration.bearer_access_token {
350        req_builder = req_builder.bearer_auth(token.to_owned());
351    };
352    req_builder = req_builder.json(&p_dependent_trade_orders_request);
353
354    let req = req_builder.build()?;
355    let resp = configuration.client.execute(req).await?;
356
357    let status = resp.status();
358    let content_type = resp
359        .headers()
360        .get("content-type")
361        .and_then(|v| v.to_str().ok())
362        .unwrap_or("application/octet-stream");
363    let content_type = super::ContentType::from(content_type);
364
365    if !status.is_client_error() && !status.is_server_error() {
366        let content = resp.text().await?;
367        match content_type {
368            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
369            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::DependentTradeOrdersResponse`"))),
370            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::DependentTradeOrdersResponse`")))),
371        }
372    } else {
373        let content = resp.text().await?;
374        let entity: Option<SetTradeOrdersError> = serde_json::from_str(&content).ok();
375        Err(Error::ResponseError(ResponseContent { status, content, entity }))
376    }
377}
378