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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! Instrument endpoints: candlestick data and order/position books.
use serde::{Deserialize, Serialize};
use crate::client::Client;
use crate::error::Error;
use crate::models::{
AccountId, CandleSpecification, CandlestickGranularity, DateTime, DecimalNumber,
InstrumentCandles, InstrumentName, OrderBook, PositionBook, PricingComponent, WeeklyAlignment,
};
impl Client {
/// Fetch candlestick data for an instrument.
///
/// `GET /v3/instruments/{instrument}/candles`
///
/// # Examples
///
/// ```no_run
/// # async fn run() -> Result<(), oanda_rs::Error> {
/// # let client = oanda_rs::Client::new(oanda_rs::Environment::Practice, "token");
/// use oanda_rs::models::CandlestickGranularity;
///
/// let candles = client
/// .candles("EUR_USD")
/// .granularity(CandlestickGranularity::H1)
/// .count(500)
/// .send()
/// .await?;
/// println!("got {} candles", candles.candles.len());
/// # Ok(())
/// # }
/// ```
pub fn candles(&self, instrument: impl Into<InstrumentName>) -> CandlesRequest {
CandlesRequest::new(self.clone(), None, instrument.into())
}
/// Fetch candlestick data for an instrument, scoped to an account: the
/// data matches what the account would see, and volume-weighted average
/// prices can be requested via
/// [`units`](CandlesRequest::units).
///
/// `GET /v3/accounts/{accountID}/instruments/{instrument}/candles`
pub fn account_candles(
&self,
account_id: impl Into<AccountId>,
instrument: impl Into<InstrumentName>,
) -> CandlesRequest {
CandlesRequest::new(self.clone(), Some(account_id.into()), instrument.into())
}
/// Get the most recently completed candles within an account for the
/// specified combinations of instrument, granularity, and price
/// component.
///
/// `GET /v3/accounts/{accountID}/candles/latest`
///
/// # Examples
///
/// ```no_run
/// # async fn run() -> Result<(), oanda_rs::Error> {
/// # let client = oanda_rs::Client::new(oanda_rs::Environment::Practice, "token");
/// use oanda_rs::models::{CandleSpecification, CandlestickGranularity, PricingComponent};
///
/// let latest = client
/// .latest_candles(
/// "101-004-1234567-001",
/// [CandleSpecification::new("EUR_USD", CandlestickGranularity::S10)
/// .price(PricingComponent::BID.with_mid())],
/// )
/// .send()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn latest_candles(
&self,
account_id: impl Into<AccountId>,
specifications: impl IntoIterator<Item = CandleSpecification>,
) -> LatestCandlesRequest {
LatestCandlesRequest {
client: self.clone(),
account_id: account_id.into(),
specifications: specifications.into_iter().collect(),
params: Vec::new(),
}
}
/// Fetch an order book for an instrument.
///
/// `GET /v3/instruments/{instrument}/orderBook`
pub fn instrument_order_book(&self, instrument: impl Into<InstrumentName>) -> OrderBookRequest {
OrderBookRequest {
client: self.clone(),
instrument: instrument.into(),
time: None,
}
}
/// Fetch a position book for an instrument.
///
/// `GET /v3/instruments/{instrument}/positionBook`
pub fn instrument_position_book(
&self,
instrument: impl Into<InstrumentName>,
) -> PositionBookRequest {
PositionBookRequest {
client: self.clone(),
instrument: instrument.into(),
time: None,
}
}
}
/// Builder for [`Client::candles`] and [`Client::account_candles`].
#[derive(Debug)]
pub struct CandlesRequest {
client: Client,
account_id: Option<AccountId>,
instrument: InstrumentName,
params: Vec<(&'static str, String)>,
}
impl CandlesRequest {
fn new(client: Client, account_id: Option<AccountId>, instrument: InstrumentName) -> Self {
CandlesRequest {
client,
account_id,
instrument,
params: Vec::new(),
}
}
/// The price component(s) to get candlestick data for (default mid).
pub fn price(mut self, price: PricingComponent) -> Self {
self.params.push(("price", price.to_string()));
self
}
/// The granularity of the candlesticks to fetch (default `S5`).
pub fn granularity(mut self, granularity: CandlestickGranularity) -> Self {
self.params.push(("granularity", granularity.to_string()));
self
}
/// The number of candlesticks to return (default 500, maximum 5000).
/// May not be specified when both `from` and `to` are provided.
pub fn count(mut self, count: u32) -> Self {
self.params.push(("count", count.to_string()));
self
}
/// The start of the time range to fetch candlesticks for.
pub fn from(mut self, from: impl Into<DateTime>) -> Self {
self.params.push(("from", from.into().0));
self
}
/// The end of the time range to fetch candlesticks for.
pub fn to(mut self, to: impl Into<DateTime>) -> Self {
self.params.push(("to", to.into().0));
self
}
/// Whether the candlestick is "smoothed" (uses the previous candle's
/// close as its open; default `false`).
pub fn smooth(mut self, smooth: bool) -> Self {
self.params.push(("smooth", smooth.to_string()));
self
}
/// Whether the candlestick covered by the `from` time should be
/// included (default `true`).
pub fn include_first(mut self, include_first: bool) -> Self {
self.params
.push(("includeFirst", include_first.to_string()));
self
}
/// The hour of the day (in `alignment_timezone`) used for granularities
/// with daily alignment (default 17).
pub fn daily_alignment(mut self, hour: u8) -> Self {
self.params.push(("dailyAlignment", hour.to_string()));
self
}
/// The timezone used for `daily_alignment` (default
/// `America/New_York`).
pub fn alignment_timezone(mut self, timezone: impl Into<String>) -> Self {
self.params.push(("alignmentTimezone", timezone.into()));
self
}
/// The day of the week used for granularities with weekly alignment
/// (default `Friday`).
pub fn weekly_alignment(mut self, alignment: WeeklyAlignment) -> Self {
self.params.push(("weeklyAlignment", alignment.to_string()));
self
}
/// The number of units used to calculate the volume-weighted average
/// bid/ask prices. Only supported on the account-scoped
/// [`Client::account_candles`] endpoint.
pub fn units(mut self, units: impl Into<DecimalNumber>) -> Self {
self.params.push(("units", units.into().to_string()));
self
}
/// Performs the request.
pub async fn send(self) -> Result<InstrumentCandles, Error> {
let request = match &self.account_id {
Some(account_id) => self.client.get(&[
"accounts",
account_id.as_str(),
"instruments",
self.instrument.as_str(),
"candles",
]),
None => self
.client
.get(&["instruments", self.instrument.as_str(), "candles"]),
};
self.client.execute(request.query(&self.params)).await
}
}
/// Builder for [`Client::latest_candles`].
#[derive(Debug)]
pub struct LatestCandlesRequest {
client: Client,
account_id: AccountId,
specifications: Vec<CandleSpecification>,
params: Vec<(&'static str, String)>,
}
impl LatestCandlesRequest {
/// The number of units used to calculate the volume-weighted average
/// bid/ask prices.
pub fn units(mut self, units: impl Into<DecimalNumber>) -> Self {
self.params.push(("units", units.into().to_string()));
self
}
/// Whether the candlestick is "smoothed" (default `false`).
pub fn smooth(mut self, smooth: bool) -> Self {
self.params.push(("smooth", smooth.to_string()));
self
}
/// The hour of the day (in `alignment_timezone`) used for granularities
/// with daily alignment (default 17).
pub fn daily_alignment(mut self, hour: u8) -> Self {
self.params.push(("dailyAlignment", hour.to_string()));
self
}
/// The timezone used for `daily_alignment` (default
/// `America/New_York`).
pub fn alignment_timezone(mut self, timezone: impl Into<String>) -> Self {
self.params.push(("alignmentTimezone", timezone.into()));
self
}
/// The day of the week used for granularities with weekly alignment
/// (default `Friday`).
pub fn weekly_alignment(mut self, alignment: WeeklyAlignment) -> Self {
self.params.push(("weeklyAlignment", alignment.to_string()));
self
}
/// Performs the request.
pub async fn send(self) -> Result<LatestCandlesResponse, Error> {
let specs = self
.specifications
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(",");
let request = self
.client
.get(&["accounts", self.account_id.as_str(), "candles", "latest"])
.query(&[("candleSpecifications", specs)])
.query(&self.params);
self.client.execute(request).await
}
}
/// Response of [`Client::latest_candles`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LatestCandlesResponse {
/// The latest candle sets for each candle specification.
#[serde(
rename = "latestCandles",
default,
skip_serializing_if = "Vec::is_empty"
)]
pub latest_candles: Vec<InstrumentCandles>,
}
/// Builder for [`Client::instrument_order_book`].
#[derive(Debug)]
pub struct OrderBookRequest {
client: Client,
instrument: InstrumentName,
time: Option<DateTime>,
}
impl OrderBookRequest {
/// The time of the snapshot to fetch. If not specified, then the most
/// recent snapshot is fetched.
pub fn time(mut self, time: impl Into<DateTime>) -> Self {
self.time = Some(time.into());
self
}
/// Performs the request.
pub async fn send(self) -> Result<OrderBookResponse, Error> {
let mut request = self
.client
.get(&["instruments", self.instrument.as_str(), "orderBook"]);
if let Some(time) = &self.time {
request = request.query(&[("time", time.as_str())]);
}
let (mut response, headers): (OrderBookResponse, _) =
self.client.execute_with_headers(request).await?;
response.link = crate::transport::header_str(&headers, "Link").map(str::to_owned);
Ok(response)
}
}
/// Response of [`Client::instrument_order_book`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct OrderBookResponse {
/// The instrument's order book.
#[serde(rename = "orderBook")]
pub order_book: OrderBook,
/// The `Link` response header, containing links to the next/previous
/// order book snapshots (when a `time` was requested).
#[serde(skip)]
pub link: Option<String>,
}
/// Builder for [`Client::instrument_position_book`].
#[derive(Debug)]
pub struct PositionBookRequest {
client: Client,
instrument: InstrumentName,
time: Option<DateTime>,
}
impl PositionBookRequest {
/// The time of the snapshot to fetch. If not specified, then the most
/// recent snapshot is fetched.
pub fn time(mut self, time: impl Into<DateTime>) -> Self {
self.time = Some(time.into());
self
}
/// Performs the request.
pub async fn send(self) -> Result<PositionBookResponse, Error> {
let mut request =
self.client
.get(&["instruments", self.instrument.as_str(), "positionBook"]);
if let Some(time) = &self.time {
request = request.query(&[("time", time.as_str())]);
}
let (mut response, headers): (PositionBookResponse, _) =
self.client.execute_with_headers(request).await?;
response.link = crate::transport::header_str(&headers, "Link").map(str::to_owned);
Ok(response)
}
}
/// Response of [`Client::instrument_position_book`].
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PositionBookResponse {
/// The instrument's position book.
#[serde(rename = "positionBook")]
pub position_book: PositionBook,
/// The `Link` response header, containing links to the next/previous
/// position book snapshots (when a `time` was requested).
#[serde(skip)]
pub link: Option<String>,
}