Skip to main content

alpaca_sdk/
config.rs

1//! Endpoints, retry policy, and shared constants.
2
3use std::time::Duration;
4
5/// Maximum number of items the market data API returns per page.
6pub const DATA_MAX_LIMIT: u32 = 10_000;
7
8/// How long a stream session must last before it counts as healthy.
9///
10/// The reconnect backoff curve is indexed by consecutive *failures*, and a
11/// connection that came up and immediately dropped is a failure however far it
12/// got through the handshake. Resetting the counter on connect alone pins the
13/// delay at its minimum against a server that accepts and hangs up — roughly one
14/// connection a second, at an endpoint that allows one per account.
15///
16/// So a session resets the curve when it either delivered data or stayed up this
17/// long. That covers the case the reset exists for — a quiet stream whose server
18/// recycles it — without rewarding a server that is only pretending to work.
19///
20/// Lives here rather than in either stream module so that both can re-export the
21/// same item: two constants of the same name would collide under a glob import
22/// of `data::*` and `trading::*`.
23pub const DEFAULT_STABLE_SESSION: Duration = Duration::from_secs(30);
24
25/// Maximum number of orders `/v2/orders` and its broker twin serve in one page.
26///
27/// The default is 50; this is the ceiling, and what the order walkers ask for.
28pub const ORDERS_MAX_LIMIT: u32 = 500;
29
30/// Default page size for the broker account-activities endpoint.
31pub const ACCOUNT_ACTIVITIES_DEFAULT_PAGE_SIZE: u32 = 100;
32
33/// Maximum number of documents accepted by a single broker upload request.
34pub const BROKER_DOCUMENT_UPLOAD_LIMIT: usize = 10;
35
36/// Retries attempted after the initial request, matching alpaca-py's
37/// `DEFAULT_RETRY_ATTEMPTS`, which carries the same name.
38pub const DEFAULT_RETRY_ATTEMPTS: u32 = 3;
39
40/// Base delay before the first retry, doubling from there.
41///
42/// This is the ~1 second the [rate-limit page][rate-limits] asks for, and the
43/// same base the stream reconnect uses ([`crate::backoff::DEFAULT_MIN_BACKOFF`]).
44/// See [`RetryConfig`] for how to wait a flat interval instead.
45///
46/// [rate-limits]: https://docs.alpaca.markets/us/docs/broker-api-rate-limits
47pub const DEFAULT_RETRY_WAIT: Duration = crate::backoff::DEFAULT_MIN_BACKOFF;
48
49/// Ceiling the retry delay is capped at, shared with the stream reconnect.
50pub const DEFAULT_RETRY_MAX_WAIT: Duration = crate::backoff::DEFAULT_MAX_BACKOFF;
51
52/// HTTP statuses that trigger a retry, matching `DEFAULT_RETRY_EXCEPTION_CODES`.
53pub const DEFAULT_RETRY_STATUS_CODES: &[u16] = &[429, 504];
54
55/// The `User-Agent` sent with every request.
56///
57/// `APCA-RS/<sdk> Rust/<rustc>`, following the `APCA-<lang>` convention Alpaca's
58/// clients use. The compiler version is captured in `build.rs`.
59#[must_use]
60pub fn user_agent() -> &'static str {
61    concat!(
62        "APCA-RS/",
63        env!("CARGO_PKG_VERSION"),
64        " Rust/",
65        env!("ALPACA_RUSTC_VERSION"),
66    )
67}
68
69/// The Alpaca API endpoints.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum BaseUrl {
73    /// Broker API sandbox.
74    BrokerSandbox,
75    /// Broker API production.
76    BrokerProduction,
77    /// Trading API paper environment.
78    TradingPaper,
79    /// Trading API live environment.
80    TradingLive,
81    /// Market data API.
82    Data,
83    /// Market data API sandbox.
84    DataSandbox,
85    /// Market data websocket stream.
86    MarketDataStream,
87    /// Trading updates websocket stream, paper environment.
88    TradingStreamPaper,
89    /// Trading updates websocket stream, live environment.
90    TradingStreamLive,
91}
92
93impl BaseUrl {
94    /// The URL as a string, without a trailing slash.
95    #[must_use]
96    pub const fn as_str(self) -> &'static str {
97        match self {
98            Self::BrokerSandbox => "https://broker-api.sandbox.alpaca.markets",
99            Self::BrokerProduction => "https://broker-api.alpaca.markets",
100            Self::TradingPaper => "https://paper-api.alpaca.markets",
101            Self::TradingLive => "https://api.alpaca.markets",
102            Self::Data => "https://data.alpaca.markets",
103            Self::DataSandbox => "https://data.sandbox.alpaca.markets",
104            Self::MarketDataStream => "wss://stream.data.alpaca.markets",
105            Self::TradingStreamPaper => "wss://paper-api.alpaca.markets/stream",
106            Self::TradingStreamLive => "wss://api.alpaca.markets/stream",
107        }
108    }
109
110    /// Selects the trading endpoint for the paper or live environment.
111    #[must_use]
112    pub const fn trading(paper: bool) -> Self {
113        if paper {
114            Self::TradingPaper
115        } else {
116            Self::TradingLive
117        }
118    }
119
120    /// Selects the trading stream endpoint for the paper or live environment.
121    #[must_use]
122    pub const fn trading_stream(paper: bool) -> Self {
123        if paper {
124            Self::TradingStreamPaper
125        } else {
126            Self::TradingStreamLive
127        }
128    }
129
130    /// Selects the broker endpoint for the sandbox or production environment.
131    #[must_use]
132    pub const fn broker(sandbox: bool) -> Self {
133        if sandbox {
134            Self::BrokerSandbox
135        } else {
136            Self::BrokerProduction
137        }
138    }
139
140    /// Selects the market data endpoint for the sandbox or production environment.
141    #[must_use]
142    pub const fn data(sandbox: bool) -> Self {
143        if sandbox {
144            Self::DataSandbox
145        } else {
146            Self::Data
147        }
148    }
149}
150
151impl std::fmt::Display for BaseUrl {
152    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153        f.write_str(self.as_str())
154    }
155}
156
157impl From<BaseUrl> for String {
158    fn from(url: BaseUrl) -> Self {
159        url.as_str().to_owned()
160    }
161}
162
163/// How the delay between retries grows.
164///
165/// The default is [`Exponential`][Self::Exponential], which is what [Alpaca's
166/// rate-limit page][rate-limits] asks for: "stop, wait, and retry using
167/// exponential backoff". [`Flat`][Self::Flat] waits the same interval every
168/// time, for callers who want a predictable one.
169///
170/// [rate-limits]: https://docs.alpaca.markets/us/docs/broker-api-rate-limits
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172#[non_exhaustive]
173pub enum RetryBackoff {
174    /// Wait [`RetryConfig::wait`] before every retry, however many have failed.
175    Flat,
176    /// Double [`RetryConfig::wait`] per consecutive failure, up to `max`, and
177    /// draw the actual delay uniformly from the top half of that window.
178    ///
179    /// The jitter is not decoration. Alpaca rate-limits per account, so a
180    /// process that fans out concurrent requests answers one 429 with a burst of
181    /// retries that arrive together and 429 again; spreading them is what breaks
182    /// the cycle. This is [`crate::backoff::reconnect_delay`], the same curve the
183    /// stream reconnect uses.
184    Exponential {
185        /// Ceiling the doubling is capped at.
186        max: Duration,
187    },
188}
189
190/// How the client retries requests that fail with a retryable status.
191///
192/// The defaults are up to 3 retries after the initial request — 4 requests total
193/// — on HTTP 429 and 504, waiting about a second before the first and doubling
194/// from there, capped at 30 seconds and jittered.
195///
196/// **The method has a veto.** Whatever this configuration allows, the client
197/// will not replay a `POST` or a `PATCH` on anything except a 429: a 504 on
198/// `POST /v2/orders` means the gateway stopped waiting for the answer, not that
199/// nothing happened, and replaying it places a second order. So a policy of
200/// `status_codes([429, 500, 502, 504])` retries all four on `GET`, `PUT` and
201/// `DELETE`, and only the 429 on `POST` and `PATCH`. See
202/// [`RetryConfig::should_retry`], which reports this configuration's own answer
203/// and not the client's.
204///
205/// **A response carrying `Retry-After` overrides all of that.** The server is
206/// stating the answer this configuration is otherwise guessing at, so its value
207/// is used in place of the computed delay — clamped to the backoff's own ceiling,
208/// since it arrives from the other end. Only the delta-seconds form is read; an
209/// HTTP-date is treated as absent and the delay below applies.
210///
211/// A flat wait is available for callers who want one, and has to be asked for
212/// by name — it does not follow [Alpaca's own rate-limit
213/// documentation][rate-limits], which is why it is not the default:
214///
215/// ```
216/// use std::time::Duration;
217/// use alpaca_sdk::{RetryBackoff, RetryConfig};
218///
219/// let flat = RetryConfig::default()
220///     .backoff(RetryBackoff::Flat)
221///     .wait(Duration::from_secs(3));
222/// ```
223///
224/// It is `#[non_exhaustive]`, so build one from [`RetryConfig::default`] or
225/// [`RetryConfig::none`] and adjust it with the builder methods rather than with a
226/// struct literal. That is what let the backoff strategy arrive as a new field
227/// instead of as a breaking change.
228///
229/// [rate-limits]: https://docs.alpaca.markets/us/docs/broker-api-rate-limits
230#[derive(Debug, Clone, PartialEq, Eq)]
231#[non_exhaustive]
232pub struct RetryConfig {
233    /// Number of retries after the first attempt.
234    pub attempts: u32,
235    /// Delay before the first retry, and the base the growth doubles from.
236    pub wait: Duration,
237    /// How the delay grows across consecutive failures.
238    pub backoff: RetryBackoff,
239    /// Statuses that trigger a retry.
240    pub status_codes: Vec<u16>,
241}
242
243impl RetryConfig {
244    /// A configuration that never retries.
245    #[must_use]
246    pub fn none() -> Self {
247        Self {
248            attempts: 0,
249            wait: Duration::ZERO,
250            backoff: RetryBackoff::Flat,
251            status_codes: Vec::new(),
252        }
253    }
254
255    /// Sets the number of retries attempted after the first request.
256    #[must_use]
257    pub fn attempts(mut self, attempts: u32) -> Self {
258        self.attempts = attempts;
259        self
260    }
261
262    /// Sets the delay before the first retry.
263    #[must_use]
264    pub fn wait(mut self, wait: Duration) -> Self {
265        self.wait = wait;
266        self
267    }
268
269    /// Sets how the delay grows across consecutive failures.
270    #[must_use]
271    pub fn backoff(mut self, backoff: RetryBackoff) -> Self {
272        self.backoff = backoff;
273        self
274    }
275
276    /// Sets the statuses that trigger a retry, replacing the current list.
277    #[must_use]
278    pub fn status_codes(mut self, status_codes: impl Into<Vec<u16>>) -> Self {
279        self.status_codes = status_codes.into();
280        self
281    }
282
283    /// Whether `status` is in this configuration's retry set.
284    ///
285    /// **Not the same question as "will the client retry it".** The method has a
286    /// veto that this type cannot see: a `POST` or `PATCH` is never replayed
287    /// except on a 429, however this is configured. See the type documentation.
288    #[must_use]
289    pub fn should_retry(&self, status: u16) -> bool {
290        self.status_codes.contains(&status)
291    }
292
293    /// The ceiling a server-supplied `Retry-After` is clamped to.
294    ///
295    /// A rate limiter — or a proxy in front of one — answering
296    /// `Retry-After: 86400` must not put the caller to sleep for a day. Under
297    /// [`RetryBackoff::Exponential`] the curve already has a ceiling and it is
298    /// the natural bound; a flat policy has none of its own, so the default
299    /// applies.
300    pub(crate) fn retry_after_cap(&self) -> Duration {
301        match self.backoff {
302            RetryBackoff::Exponential { max } => max,
303            RetryBackoff::Flat => DEFAULT_RETRY_MAX_WAIT,
304        }
305    }
306
307    /// How long to wait after `failures` consecutive failures, 1-based.
308    ///
309    /// Under [`RetryBackoff::Exponential`] the result is sampled, so two calls
310    /// with the same argument do not agree.
311    ///
312    /// This is the curve. A response carrying `Retry-After` overrides it — the
313    /// server is stating the answer the curve is guessing at.
314    #[must_use]
315    pub fn delay(&self, failures: u32) -> Duration {
316        match self.backoff {
317            RetryBackoff::Flat => self.wait,
318            RetryBackoff::Exponential { max } => {
319                crate::backoff::reconnect_delay(failures, self.wait, max)
320            }
321        }
322    }
323}
324
325impl Default for RetryConfig {
326    fn default() -> Self {
327        Self {
328            attempts: DEFAULT_RETRY_ATTEMPTS,
329            wait: DEFAULT_RETRY_WAIT,
330            backoff: RetryBackoff::Exponential {
331                max: DEFAULT_RETRY_MAX_WAIT,
332            },
333            status_codes: DEFAULT_RETRY_STATUS_CODES.to_vec(),
334        }
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn user_agent_has_the_apca_rs_shape() {
344        let ua = user_agent();
345        assert!(ua.starts_with("APCA-RS/"), "{ua}");
346        assert!(ua.contains(" Rust/"), "{ua}");
347    }
348
349    #[test]
350    fn endpoints_are_the_documented_hosts() {
351        assert_eq!(
352            BaseUrl::TradingPaper.as_str(),
353            "https://paper-api.alpaca.markets"
354        );
355        assert_eq!(BaseUrl::TradingLive.as_str(), "https://api.alpaca.markets");
356        assert_eq!(BaseUrl::Data.as_str(), "https://data.alpaca.markets");
357        assert_eq!(
358            BaseUrl::MarketDataStream.as_str(),
359            "wss://stream.data.alpaca.markets"
360        );
361        assert_eq!(
362            BaseUrl::BrokerSandbox.as_str(),
363            "https://broker-api.sandbox.alpaca.markets"
364        );
365    }
366
367    #[test]
368    fn environment_selectors_pick_the_right_endpoint() {
369        assert_eq!(BaseUrl::trading(true), BaseUrl::TradingPaper);
370        assert_eq!(BaseUrl::trading(false), BaseUrl::TradingLive);
371        assert_eq!(BaseUrl::trading_stream(true), BaseUrl::TradingStreamPaper);
372        assert_eq!(BaseUrl::broker(true), BaseUrl::BrokerSandbox);
373        assert_eq!(BaseUrl::data(false), BaseUrl::Data);
374    }
375
376    /// The exponential curve already has a ceiling, so it is the one a
377    /// server-supplied `Retry-After` is held to.
378    #[test]
379    fn retry_after_is_capped_by_the_exponential_ceiling() {
380        let cfg = RetryConfig::default().backoff(RetryBackoff::Exponential {
381            max: Duration::from_secs(5),
382        });
383        assert_eq!(cfg.retry_after_cap(), Duration::from_secs(5));
384    }
385
386    /// A flat policy has no ceiling of its own, so the default one applies —
387    /// otherwise a caller who asked for a flat 1s would clamp every
388    /// `Retry-After` to 1s, which honours the header in name only.
389    #[test]
390    fn a_flat_policy_caps_retry_after_at_the_default_ceiling() {
391        let cfg = RetryConfig::default().backoff(RetryBackoff::Flat);
392        assert_eq!(cfg.retry_after_cap(), DEFAULT_RETRY_MAX_WAIT);
393    }
394
395    /// The wait is the rate-limit page's, not a flat interval — see
396    /// [`RetryConfig`].
397    #[test]
398    fn retry_defaults_follow_the_rate_limit_page() {
399        let cfg = RetryConfig::default();
400        assert_eq!(cfg.attempts, 3);
401        assert_eq!(cfg.wait, Duration::from_secs(1));
402        assert_eq!(
403            cfg.backoff,
404            RetryBackoff::Exponential {
405                max: Duration::from_secs(30)
406            }
407        );
408        assert!(cfg.should_retry(429));
409        assert!(cfg.should_retry(504));
410        assert!(!cfg.should_retry(500));
411    }
412
413    #[test]
414    fn flat_backoff_waits_the_same_amount_every_time() {
415        let cfg = RetryConfig::default()
416            .backoff(RetryBackoff::Flat)
417            .wait(Duration::from_secs(3));
418
419        for failures in 1..=5 {
420            assert_eq!(cfg.delay(failures), Duration::from_secs(3));
421        }
422    }
423
424    /// Bounds rather than values, because the delay is jittered. The lower bound
425    /// is what proves the growth: by the fourth failure even the unluckiest draw
426    /// exceeds three seconds, which no flat policy at this base would ever do.
427    #[test]
428    fn exponential_backoff_grows_and_stays_under_the_cap() {
429        let cfg = RetryConfig::default();
430
431        for failures in 1..=10 {
432            let capped = crate::backoff::capped_delay(failures, cfg.wait, Duration::from_secs(30));
433            let delay = cfg.delay(failures);
434            assert!(
435                delay >= capped / 2 && delay <= capped,
436                "failures={failures}: {delay:?} outside [{:?}, {capped:?}]",
437                capped / 2
438            );
439            assert!(delay <= Duration::from_secs(30));
440        }
441
442        assert!(cfg.delay(4) > Duration::from_secs(3));
443    }
444
445    /// The zero-wait configuration the transport tests use must not start
446    /// sleeping just because the default strategy changed.
447    #[test]
448    fn a_zero_wait_stays_instant_under_either_strategy() {
449        assert_eq!(RetryConfig::none().delay(1), Duration::ZERO);
450        assert_eq!(
451            RetryConfig::default().wait(Duration::ZERO).delay(7),
452            Duration::ZERO
453        );
454    }
455
456    /// The struct is `#[non_exhaustive]`, so these methods are the only way a
457    /// caller outside the crate can change one field and keep the others.
458    #[test]
459    fn retry_builders_replace_one_field_at_a_time() {
460        let cfg = RetryConfig::default()
461            .attempts(5)
462            .wait(Duration::ZERO)
463            .status_codes([500, 502]);
464
465        assert_eq!(cfg.attempts, 5);
466        assert_eq!(cfg.wait, Duration::ZERO);
467        assert!(cfg.should_retry(500));
468        assert!(!cfg.should_retry(429));
469
470        let none = RetryConfig::none();
471        assert_eq!(none.attempts, 0);
472        assert!(!none.should_retry(429));
473    }
474}