use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use chrono::NaiveDate;
use reqwest::StatusCode;
use reqwest::Url;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use tokio::sync::Semaphore;
use crate::error::{ApiError, Error};
use crate::filters::Clause;
use crate::ratelimit::{RateLimit, parse_rate_limit, parse_retry_after};
use crate::types::*;
pub const DEFAULT_BASE_URL: &str = "https://api.thaler.sh";
fn well_formed(key: &str) -> bool {
key.len() == 45
&& key.starts_with("thaler_")
&& key[7..].bytes().all(|b| b.is_ascii_alphanumeric())
}
pub fn user_agent() -> String {
format!("thaler-rust/{}", crate::VERSION)
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Response<T> {
pub data: T,
pub meta: ResponseMeta,
pub request_id: String,
pub etag: Option<String>,
pub rate_limit: Option<RateLimit>,
pub headers: HeaderMap,
}
#[derive(Deserialize)]
struct Envelope<T> {
data: T,
meta: ResponseMeta,
}
#[derive(Clone)]
pub struct ClientBuilder {
api_key: Option<String>,
base_url: String,
timeout: Duration,
max_retries: u32,
max_concurrent: usize,
max_retry_after: Duration,
backoff: Duration,
http: Option<reqwest::Client>,
}
impl std::fmt::Debug for ClientBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientBuilder")
.field("api_key", &self.api_key.as_ref().map(|_| "thaler_…"))
.field("base_url", &self.base_url)
.field("timeout", &self.timeout)
.field("max_retries", &self.max_retries)
.field("max_concurrent", &self.max_concurrent)
.field("max_retry_after", &self.max_retry_after)
.field("backoff", &self.backoff)
.finish_non_exhaustive()
}
}
impl Default for ClientBuilder {
fn default() -> Self {
ClientBuilder {
api_key: None,
base_url: DEFAULT_BASE_URL.to_string(),
timeout: Duration::from_secs(30),
max_retries: 2,
max_concurrent: 4,
max_retry_after: Duration::from_secs(60),
backoff: Duration::from_millis(500),
http: None,
}
}
}
impl ClientBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn base_url(mut self, url: impl Into<String>) -> Self {
self.base_url = url.into();
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn max_retries(mut self, retries: u32) -> Self {
self.max_retries = retries;
self
}
pub fn max_concurrent(mut self, count: usize) -> Self {
self.max_concurrent = count.clamp(1, Semaphore::MAX_PERMITS);
self
}
pub fn max_retry_after(mut self, wait: Duration) -> Self {
self.max_retry_after = wait;
self
}
pub fn backoff(mut self, first: Duration) -> Self {
self.backoff = first;
self
}
pub fn reqwest_client(mut self, http: reqwest::Client) -> Self {
self.http = Some(http);
self
}
pub fn build(self) -> Result<Client, Error> {
let key = match self.api_key {
Some(key) => key,
None => std::env::var("THALER_API_KEY").unwrap_or_default(),
};
let key = key.trim().to_string();
if key.is_empty() {
return Err(Error::Config(
"An API key is needed: pass one to the builder, or set THALER_API_KEY. Create one at https://thaler.sh/developers/keys".to_string(),
));
}
if !well_formed(&key) {
return Err(Error::Config(
"The key is not a Thaler API key: keys are thaler_ then 38 letters and digits, 45 characters in all".to_string(),
));
}
let base_url = Url::parse(self.base_url.trim_end_matches('/'))
.map_err(|error| Error::Config(format!("base_url: {error}")))?;
let http = match self.http {
Some(http) => http,
None => reqwest::Client::builder()
.timeout(self.timeout)
.connect_timeout(self.timeout.min(Duration::from_secs(10)))
.build()
.map_err(|error| Error::Config(format!("reqwest: {error}")))?,
};
let mut headers = HeaderMap::new();
let mut authorization = HeaderValue::from_str(&format!("Bearer {key}"))
.map_err(|_| Error::Config("the key is not a header value".to_string()))?;
authorization.set_sensitive(true);
headers.insert(AUTHORIZATION, authorization);
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
headers.insert(
USER_AGENT,
HeaderValue::from_str(&user_agent()).expect("the user agent is ASCII"),
);
Ok(Client {
inner: Arc::new(Inner {
http,
base_url,
headers,
max_retries: self.max_retries,
max_retry_after: self.max_retry_after,
backoff: self.backoff,
semaphore: Semaphore::new(self.max_concurrent),
state: Mutex::new(State {
rate_limit: None,
resume_at: None,
}),
}),
})
}
}
struct State {
rate_limit: Option<RateLimit>,
resume_at: Option<Instant>,
}
struct Inner {
http: reqwest::Client,
base_url: Url,
headers: HeaderMap,
max_retries: u32,
max_retry_after: Duration,
backoff: Duration,
semaphore: Semaphore,
state: Mutex<State>,
}
#[derive(Clone)]
pub struct Client {
inner: Arc<Inner>,
}
impl std::fmt::Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("base_url", &self.inner.base_url.as_str())
.finish_non_exhaustive()
}
}
struct Call {
operation: &'static str,
segments: Vec<String>,
query: Vec<(String, String)>,
}
impl Call {
fn new(operation: &'static str, segments: &[&str]) -> Self {
Call {
operation,
segments: segments.iter().map(|s| s.to_string()).collect(),
query: Vec::new(),
}
}
fn push(mut self, key: &str, value: Option<impl ToString>) -> Self {
if let Some(value) = value {
self.query.push((key.to_string(), value.to_string()));
}
self
}
fn push_day(self, key: &str, value: Option<NaiveDate>) -> Self {
self.push(key, value.map(|day| day.format("%Y-%m-%d").to_string()))
}
fn push_list(mut self, key: &str, values: &[String]) -> Self {
if !values.is_empty() {
self.query.push((key.to_string(), values.join(",")));
}
self
}
fn push_each(mut self, key: &str, values: &[String]) -> Self {
for value in values {
self.query.push((key.to_string(), value.clone()));
}
self
}
}
fn ticker(value: &str) -> Result<String, Error> {
let text = value.trim().to_ascii_uppercase();
if text.is_empty() {
return Err(Error::Config("the ticker is empty".to_string()));
}
Ok(text)
}
fn segment(value: &str, what: &str) -> Result<String, Error> {
let text = value.trim();
if text.is_empty() {
return Err(Error::Config(format!("the {what} is empty")));
}
Ok(text.to_string())
}
impl Client {
pub fn new(api_key: impl Into<String>) -> Result<Client, Error> {
ClientBuilder::new().api_key(api_key).build()
}
pub fn from_env() -> Result<Client, Error> {
ClientBuilder::new().build()
}
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub fn base_url(&self) -> &str {
self.inner.base_url.as_str()
}
pub fn rate_limit(&self) -> Option<RateLimit> {
self.inner
.state
.lock()
.unwrap_or_else(|e| e.into_inner())
.rate_limit
.clone()
}
fn url(&self, call: &Call) -> Result<Url, Error> {
let mut url = self.inner.base_url.clone();
{
let mut segments = url
.path_segments_mut()
.map_err(|_| Error::Config("base_url cannot take a path".to_string()))?;
segments.pop_if_empty();
segments.push("v1");
for segment in &call.segments {
segments.push(segment);
}
}
{
let mut pairs = url.query_pairs_mut();
for (key, value) in &call.query {
pairs.append_pair(key, value);
}
}
Ok(url)
}
fn wait_needed(&self) -> Duration {
let state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
state
.resume_at
.map(|at| at.saturating_duration_since(Instant::now()))
.unwrap_or(Duration::ZERO)
}
fn note(&self, headers: &HeaderMap) {
let Some(limits) = parse_rate_limit(headers) else {
return;
};
let mut state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner());
if let Some(minute) = &limits.minute {
match (minute.remaining, minute.reset_seconds) {
(Some(0), Some(seconds)) if seconds > 0 => {
let pause = Duration::from_secs(seconds).min(self.inner.max_retry_after);
state.resume_at = Instant::now().checked_add(pause);
}
(Some(remaining), _) if remaining > 0 => state.resume_at = None,
_ => {}
}
}
state.rate_limit = Some(limits);
}
fn backoff(&self, attempt: u32) -> Duration {
let base = self.inner.backoff.as_secs_f64() * 2f64.powi(attempt as i32);
let capped = base.min(self.inner.backoff.as_secs_f64() * 16.0);
Duration::from_secs_f64(capped * (0.5 + fastrand::f64()))
}
fn retry_delay(&self, error: &ApiError, attempt: u32) -> Option<Duration> {
if attempt >= self.inner.max_retries {
return None;
}
match error.status {
429 => {
let wait = error.retry_after.unwrap_or_else(|| self.backoff(attempt));
if wait > self.inner.max_retry_after {
return None;
}
Some(wait + Duration::from_secs_f64(fastrand::f64() * 0.25))
}
500 | 502 | 503 | 504 => Some(self.backoff(attempt)),
_ => None,
}
}
fn problem(
&self,
operation: &'static str,
status: StatusCode,
headers: HeaderMap,
body: &[u8],
) -> ApiError {
let fields: serde_json::Value =
serde_json::from_slice(body).unwrap_or(serde_json::Value::Null);
let text = |key: &str| fields.get(key).and_then(|v| v.as_str()).map(str::to_string);
let code_text = text("code").unwrap_or_else(|| format!("http_{}", status.as_u16()));
let code: ProblemCode =
serde_json::from_value(serde_json::Value::String(code_text.clone()))
.unwrap_or(ProblemCode::Unknown);
let violated_policies: Vec<LimitPolicy> = fields
.get("violated-policies")
.cloned()
.and_then(|value| serde_json::from_value(value).ok())
.unwrap_or_default();
ApiError {
status: status.as_u16(),
code,
code_text,
title: text("title")
.unwrap_or_else(|| status.canonical_reason().unwrap_or("").to_string()),
detail: text("detail").unwrap_or_else(|| {
format!(
"{operation} answered {} without a problem body",
status.as_u16()
)
}),
type_url: text("type").unwrap_or_default(),
request_id: text("request_id")
.filter(|id| !id.is_empty())
.or_else(|| {
headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(str::to_string)
})
.unwrap_or_default(),
retry_after: parse_retry_after(&headers),
violated_policies,
rate_limit: parse_rate_limit(&headers),
headers,
}
}
async fn send<T: DeserializeOwned>(&self, call: Call) -> Result<Response<T>, Error> {
let url = self.url(&call)?;
let operation = call.operation;
let mut attempt = 0;
loop {
let wait = self.wait_needed();
if !wait.is_zero() {
tokio::time::sleep(wait).await;
}
let permit = self
.inner
.semaphore
.acquire()
.await
.expect("the semaphore is never closed");
if !self.wait_needed().is_zero() {
drop(permit);
continue;
}
let sent = self
.inner
.http
.get(url.clone())
.headers(self.inner.headers.clone())
.send()
.await;
let response = match sent {
Ok(response) => response,
Err(source) => {
drop(permit);
if attempt < self.inner.max_retries {
tokio::time::sleep(self.backoff(attempt)).await;
attempt += 1;
continue;
}
return Err(Error::Transport { operation, source });
}
};
let status = response.status();
let headers = response.headers().clone();
let body = match response.bytes().await {
Ok(body) => body,
Err(source) => {
drop(permit);
if attempt < self.inner.max_retries {
tokio::time::sleep(self.backoff(attempt)).await;
attempt += 1;
continue;
}
return Err(Error::Transport { operation, source });
}
};
self.note(&headers);
drop(permit);
if status == StatusCode::OK {
let mut deserializer = serde_json::Deserializer::from_slice(&body);
let envelope: Envelope<T> = serde_path_to_error::deserialize(&mut deserializer)
.map_err(|error| Error::Decode {
operation,
message: error.to_string(),
})?;
deserializer.end().map_err(|error| Error::Decode {
operation,
message: format!("after the envelope: {error}"),
})?;
let request_id = if envelope.meta.request_id.is_empty() {
headers
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.unwrap_or_default()
.to_string()
} else {
envelope.meta.request_id.clone()
};
return Ok(Response {
data: envelope.data,
meta: envelope.meta,
request_id,
etag: headers
.get("etag")
.and_then(|v| v.to_str().ok())
.map(str::to_string),
rate_limit: parse_rate_limit(&headers),
headers,
});
}
let error = self.problem(operation, status, headers, &body);
let Some(delay) = self.retry_delay(&error, attempt) else {
return Err(error.into());
};
tokio::time::sleep(delay.max(self.wait_needed())).await;
attempt += 1;
}
}
pub fn search_securities(&self, query: impl Into<String>) -> SearchSecuritiesRequest<'_> {
SearchSecuritiesRequest {
client: self,
query: query.into(),
limit: None,
}
}
pub fn profile(&self, ticker: impl Into<String>) -> ProfileRequest<'_> {
ProfileRequest {
client: self,
ticker: ticker.into(),
}
}
pub fn metrics(&self, ticker: impl Into<String>) -> MetricsRequest<'_> {
MetricsRequest {
client: self,
ticker: ticker.into(),
period: None,
keys: Vec::new(),
collapse: None,
limit: None,
as_of: None,
}
}
pub fn metric_catalog(&self) -> MetricCatalogRequest<'_> {
MetricCatalogRequest { client: self }
}
pub fn metric_lineage(
&self,
ticker: impl Into<String>,
metric_key: impl Into<String>,
) -> MetricLineageRequest<'_> {
MetricLineageRequest {
client: self,
ticker: ticker.into(),
metric_key: metric_key.into(),
metric_value_id: None,
limit: None,
as_of: None,
}
}
pub fn metric_revisions(
&self,
ticker: impl Into<String>,
metric_key: impl Into<String>,
) -> MetricRevisionsRequest<'_> {
MetricRevisionsRequest {
client: self,
ticker: ticker.into(),
metric_key: metric_key.into(),
metric_value_id: None,
fiscal_year: None,
fiscal_period: None,
limit: None,
}
}
pub fn raw_concepts(&self, ticker: impl Into<String>) -> RawConceptsRequest<'_> {
RawConceptsRequest {
client: self,
ticker: ticker.into(),
limit: None,
}
}
pub fn filings(&self, ticker: impl Into<String>) -> FilingsRequest<'_> {
FilingsRequest {
client: self,
ticker: ticker.into(),
forms: Vec::new(),
items: Vec::new(),
limit: None,
}
}
pub fn filings_day(&self) -> FilingsDayRequest<'_> {
FilingsDayRequest {
client: self,
date: None,
}
}
pub fn filing(&self, accession: impl Into<String>) -> FilingRequest<'_> {
FilingRequest {
client: self,
accession: accession.into(),
}
}
pub fn insider_activity(&self) -> InsiderActivityRequest<'_> {
InsiderActivityRequest {
client: self,
ticker: None,
tickers: Vec::new(),
since: None,
kind: None,
limit: None,
offset: None,
}
}
pub fn search_holders(&self) -> SearchHoldersRequest<'_> {
SearchHoldersRequest {
client: self,
query: None,
limit: None,
}
}
pub fn holder(&self, cik: i64) -> HolderRequest<'_> {
HolderRequest {
client: self,
cik,
limit: None,
offset: None,
}
}
pub fn holders(&self, ticker: impl Into<String>) -> HoldersRequest<'_> {
HoldersRequest {
client: self,
ticker: ticker.into(),
limit: None,
offset: None,
}
}
pub fn segments(&self, ticker: impl Into<String>) -> SegmentsRequest<'_> {
SegmentsRequest {
client: self,
ticker: ticker.into(),
period: None,
}
}
pub fn prices(&self, ticker: impl Into<String>) -> PricesRequest<'_> {
PricesRequest {
client: self,
ticker: ticker.into(),
range: None,
from: None,
to: None,
}
}
pub fn screen(&self) -> ScreenRequest<'_> {
ScreenRequest {
client: self,
clauses: Vec::new(),
sort: None,
dir: None,
limit: None,
offset: None,
columns: Vec::new(),
}
}
pub fn release(&self) -> ReleaseRequest<'_> {
ReleaseRequest { client: self }
}
}
fn strings<I, S>(values: I) -> Vec<String>
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
values
.into_iter()
.map(|s| s.into().trim().to_string())
.collect()
}
#[must_use = "a request does nothing until sent"]
pub struct SearchSecuritiesRequest<'c> {
client: &'c Client,
query: String,
limit: Option<u32>,
}
impl SearchSecuritiesRequest<'_> {
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub async fn send(self) -> Result<Response<Vec<SecuritySearchHit>>, Error> {
let call = Call::new("searchSecurities", &["securities"])
.push("query", Some(self.query))
.push("limit", self.limit);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct ProfileRequest<'c> {
client: &'c Client,
ticker: String,
}
impl ProfileRequest<'_> {
pub async fn send(self) -> Result<Response<SecurityProfile>, Error> {
let call = Call::new(
"getSecurityProfile",
&["securities", &ticker(&self.ticker)?, "profile"],
);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct MetricsRequest<'c> {
client: &'c Client,
ticker: String,
period: Option<MetricPeriod>,
keys: Vec<String>,
collapse: Option<bool>,
limit: Option<u32>,
as_of: Option<NaiveDate>,
}
impl MetricsRequest<'_> {
pub fn period(mut self, period: MetricPeriod) -> Self {
self.period = Some(period);
self
}
pub fn keys<I, S>(mut self, keys: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.keys = strings(keys);
self
}
pub fn collapse(mut self, collapse: bool) -> Self {
self.collapse = Some(collapse);
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn as_of(mut self, day: NaiveDate) -> Self {
self.as_of = Some(day);
self
}
pub async fn send(self) -> Result<Response<Vec<MetricValue>>, Error> {
let call = Call::new(
"getMetrics",
&["securities", &ticker(&self.ticker)?, "metrics"],
)
.push("period", self.period)
.push_list("keys", &self.keys)
.push("collapse", self.collapse)
.push("limit", self.limit)
.push_day("as_of", self.as_of);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct MetricCatalogRequest<'c> {
client: &'c Client,
}
impl MetricCatalogRequest<'_> {
pub async fn send(self) -> Result<Response<Vec<MetricCatalogEntry>>, Error> {
self.client
.send(Call::new("listMetrics", &["metrics"]))
.await
}
}
#[must_use = "a request does nothing until sent"]
pub struct MetricLineageRequest<'c> {
client: &'c Client,
ticker: String,
metric_key: String,
metric_value_id: Option<String>,
limit: Option<u32>,
as_of: Option<NaiveDate>,
}
impl MetricLineageRequest<'_> {
pub fn metric_value_id(mut self, id: impl Into<String>) -> Self {
self.metric_value_id = Some(id.into());
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn as_of(mut self, day: NaiveDate) -> Self {
self.as_of = Some(day);
self
}
pub async fn send(self) -> Result<Response<Vec<MetricLineage>>, Error> {
let call = Call::new(
"getMetricLineage",
&[
"securities",
&ticker(&self.ticker)?,
"metrics",
&segment(&self.metric_key, "metric key")?,
"lineage",
],
)
.push("metric_value_id", self.metric_value_id)
.push("limit", self.limit)
.push_day("as_of", self.as_of);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct MetricRevisionsRequest<'c> {
client: &'c Client,
ticker: String,
metric_key: String,
metric_value_id: Option<String>,
fiscal_year: Option<i32>,
fiscal_period: Option<String>,
limit: Option<u32>,
}
impl MetricRevisionsRequest<'_> {
pub fn metric_value_id(mut self, id: impl Into<String>) -> Self {
self.metric_value_id = Some(id.into());
self
}
pub fn fiscal_year(mut self, year: i32) -> Self {
self.fiscal_year = Some(year);
self
}
pub fn fiscal_period(mut self, period: impl Into<String>) -> Self {
self.fiscal_period = Some(period.into());
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub async fn send(self) -> Result<Response<Vec<MetricRevision>>, Error> {
let call = Call::new(
"getMetricRevisions",
&[
"securities",
&ticker(&self.ticker)?,
"metrics",
&segment(&self.metric_key, "metric key")?,
"revisions",
],
)
.push("metric_value_id", self.metric_value_id)
.push("fiscal_year", self.fiscal_year)
.push("fiscal_period", self.fiscal_period)
.push("limit", self.limit);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct RawConceptsRequest<'c> {
client: &'c Client,
ticker: String,
limit: Option<u32>,
}
impl RawConceptsRequest<'_> {
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub async fn send(self) -> Result<Response<Vec<RawConcept>>, Error> {
let call = Call::new(
"getRawConcepts",
&["securities", &ticker(&self.ticker)?, "raw-concepts"],
)
.push("limit", self.limit);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct FilingsRequest<'c> {
client: &'c Client,
ticker: String,
forms: Vec<String>,
items: Vec<String>,
limit: Option<u32>,
}
impl FilingsRequest<'_> {
pub fn forms<I, S>(mut self, forms: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.forms = strings(forms);
self
}
pub fn items<I, S>(mut self, items: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.items = strings(items);
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub async fn send(self) -> Result<Response<Vec<Filing>>, Error> {
let call = Call::new(
"listFilings",
&["securities", &ticker(&self.ticker)?, "filings"],
)
.push_list("forms", &self.forms)
.push_list("items", &self.items)
.push("limit", self.limit);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct FilingsDayRequest<'c> {
client: &'c Client,
date: Option<NaiveDate>,
}
impl FilingsDayRequest<'_> {
pub fn date(mut self, day: NaiveDate) -> Self {
self.date = Some(day);
self
}
pub async fn send(self) -> Result<Response<FilingsDay>, Error> {
let call = Call::new("getFilingsDay", &["filings", "day"]).push_day("date", self.date);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct FilingRequest<'c> {
client: &'c Client,
accession: String,
}
impl FilingRequest<'_> {
pub async fn send(self) -> Result<Response<FilingSource>, Error> {
let call = Call::new(
"getFiling",
&["filings", &segment(&self.accession, "accession number")?],
);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct InsiderActivityRequest<'c> {
client: &'c Client,
ticker: Option<String>,
tickers: Vec<String>,
since: Option<NaiveDate>,
kind: Option<InsiderKind>,
limit: Option<u32>,
offset: Option<u32>,
}
impl InsiderActivityRequest<'_> {
pub fn ticker(mut self, ticker: impl Into<String>) -> Self {
self.ticker = Some(ticker.into());
self.tickers.clear();
self
}
pub fn tickers<I, S>(mut self, tickers: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tickers = strings(tickers)
.into_iter()
.map(|t| t.to_ascii_uppercase())
.collect();
self.ticker = None;
self
}
pub fn since(mut self, day: NaiveDate) -> Self {
self.since = Some(day);
self
}
pub fn kind(mut self, kind: InsiderKind) -> Self {
self.kind = Some(kind);
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
fn call(&self) -> Result<Call, Error> {
let call = match &self.ticker {
Some(symbol) => Call::new(
"getInsiderActivity",
&["securities", &ticker(symbol)?, "insider-activity"],
),
None => Call::new("listInsiderActivity", &["insider-activity"])
.push_list("tickers", &self.tickers),
};
Ok(call
.push_day("since", self.since)
.push("kind", self.kind)
.push("limit", self.limit)
.push("offset", self.offset))
}
pub async fn send(self) -> Result<Response<InsiderActivityPage>, Error> {
let call = self.call()?;
self.client.send(call).await
}
pub async fn all(mut self, max_filings: usize) -> Result<Vec<InsiderFiling>, Error> {
let page_size = self.limit.unwrap_or(100);
let mut offset = self.offset.unwrap_or(0);
let mut out = Vec::new();
loop {
self.limit = Some(page_size);
self.offset = Some(offset);
let page: Response<InsiderActivityPage> = self.client.send(self.call()?).await?;
let count = page.data.filings.len();
for filing in page.data.filings {
if out.len() >= max_filings {
return Ok(out);
}
out.push(filing);
}
offset += count as u32;
if count < page_size as usize || out.len() >= max_filings {
return Ok(out);
}
}
}
}
#[must_use = "a request does nothing until sent"]
pub struct SearchHoldersRequest<'c> {
client: &'c Client,
query: Option<String>,
limit: Option<u32>,
}
impl SearchHoldersRequest<'_> {
pub fn query(mut self, query: impl Into<String>) -> Self {
self.query = Some(query.into());
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub async fn send(self) -> Result<Response<Vec<HolderHit>>, Error> {
let call = Call::new("searchHolders", &["holders"])
.push("query", self.query)
.push("limit", self.limit);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct HolderRequest<'c> {
client: &'c Client,
cik: i64,
limit: Option<u32>,
offset: Option<u32>,
}
impl HolderRequest<'_> {
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
fn call(&self) -> Call {
Call::new("getHolder", &["holders", &self.cik.to_string()])
.push("limit", self.limit)
.push("offset", self.offset)
}
pub async fn send(self) -> Result<Response<Holder>, Error> {
self.client.send(self.call()).await
}
pub async fn all(mut self) -> Result<Vec<HolderPosition>, Error> {
let page_size = self.limit.unwrap_or(500);
let mut offset = self.offset.unwrap_or(0);
let mut out = Vec::new();
loop {
self.limit = Some(page_size);
self.offset = Some(offset);
let page: Response<Holder> = self.client.send(self.call()).await?;
let count = page.data.rows.len();
let total = page.data.rows_total;
out.extend(page.data.rows);
offset += count as u32;
if count < page_size as usize || i64::from(offset) >= total {
return Ok(out);
}
}
}
}
#[must_use = "a request does nothing until sent"]
pub struct HoldersRequest<'c> {
client: &'c Client,
ticker: String,
limit: Option<u32>,
offset: Option<u32>,
}
impl HoldersRequest<'_> {
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
fn call(&self) -> Result<Call, Error> {
Ok(Call::new(
"getHolders",
&["securities", &ticker(&self.ticker)?, "holders"],
)
.push("limit", self.limit)
.push("offset", self.offset))
}
pub async fn send(self) -> Result<Response<SecurityHolders>, Error> {
let call = self.call()?;
self.client.send(call).await
}
pub async fn all(mut self) -> Result<Vec<SecurityHolder>, Error> {
let page_size = self.limit.unwrap_or(200);
let mut offset = self.offset.unwrap_or(0);
let mut out = Vec::new();
loop {
self.limit = Some(page_size);
self.offset = Some(offset);
let page: Response<SecurityHolders> = self.client.send(self.call()?).await?;
let count = page.data.rows.len();
let total = page.data.rows_total;
out.extend(page.data.rows);
offset += count as u32;
if count < page_size as usize || i64::from(offset) >= total {
return Ok(out);
}
}
}
}
#[must_use = "a request does nothing until sent"]
pub struct SegmentsRequest<'c> {
client: &'c Client,
ticker: String,
period: Option<SegmentsPeriod>,
}
impl SegmentsRequest<'_> {
pub fn period(mut self, period: SegmentsPeriod) -> Self {
self.period = Some(period);
self
}
pub async fn send(self) -> Result<Response<Segments>, Error> {
let call = Call::new(
"getSegments",
&["securities", &ticker(&self.ticker)?, "segments"],
)
.push("period", self.period);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct PricesRequest<'c> {
client: &'c Client,
ticker: String,
range: Option<PriceRange>,
from: Option<NaiveDate>,
to: Option<NaiveDate>,
}
impl PricesRequest<'_> {
pub fn range(mut self, range: PriceRange) -> Self {
self.range = Some(range);
self
}
pub fn from(mut self, day: NaiveDate) -> Self {
self.from = Some(day);
self
}
pub fn to(mut self, day: NaiveDate) -> Self {
self.to = Some(day);
self
}
pub async fn send(self) -> Result<Response<Prices>, Error> {
let call = Call::new(
"getPrices",
&["securities", &ticker(&self.ticker)?, "prices"],
)
.push("range", self.range)
.push_day("from", self.from)
.push_day("to", self.to);
self.client.send(call).await
}
}
#[must_use = "a request does nothing until sent"]
pub struct ScreenRequest<'c> {
client: &'c Client,
clauses: Vec<String>,
sort: Option<String>,
dir: Option<SortDirection>,
limit: Option<u32>,
offset: Option<u32>,
columns: Vec<ScreenColumn>,
}
impl ScreenRequest<'_> {
pub fn filter(mut self, clause: Clause) -> Self {
self.clauses.push(clause.to_string());
self
}
pub fn where_(mut self, clause: impl Into<String>) -> Self {
self.clauses.push(clause.into());
self
}
pub fn sort(mut self, column: ScreenColumn) -> Self {
self.sort = Some(column.as_str().to_string());
self
}
pub fn sort_by_ticker(mut self) -> Self {
self.sort = Some("ticker".to_string());
self
}
pub fn dir(mut self, dir: SortDirection) -> Self {
self.dir = Some(dir);
self
}
pub fn limit(mut self, limit: u32) -> Self {
self.limit = Some(limit);
self
}
pub fn offset(mut self, offset: u32) -> Self {
self.offset = Some(offset);
self
}
pub fn columns<I>(mut self, columns: I) -> Self
where
I: IntoIterator<Item = ScreenColumn>,
{
self.columns = columns.into_iter().collect();
self
}
fn call(&self) -> Result<Call, Error> {
for clause in &self.clauses {
if let Some(why) = crate::filters::refused(clause) {
return Err(Error::Config(why));
}
}
let columns: Vec<String> = self
.columns
.iter()
.map(|c| c.as_str().to_string())
.collect();
Ok(Call::new("screen", &["screen"])
.push_each("where", &self.clauses)
.push("sort", self.sort.clone())
.push("dir", self.dir)
.push("limit", self.limit)
.push("offset", self.offset)
.push_list("columns", &columns))
}
pub async fn send(self) -> Result<Response<Vec<ScreenRow>>, Error> {
self.client.send(self.call()?).await
}
pub async fn all(mut self, max_rows: usize) -> Result<Vec<ScreenRow>, Error> {
let page_size = self.limit.unwrap_or(500);
let mut offset = self.offset.unwrap_or(0);
let mut out = Vec::new();
loop {
self.limit = Some(page_size);
self.offset = Some(offset);
let page: Response<Vec<ScreenRow>> = self.client.send(self.call()?).await?;
let count = page.data.len();
for row in page.data {
if out.len() >= max_rows {
return Ok(out);
}
out.push(row);
}
offset += count as u32;
let done = page
.meta
.total
.is_some_and(|total| i64::from(offset) >= total);
if count < page_size as usize || done || out.len() >= max_rows {
return Ok(out);
}
}
}
}
#[must_use = "a request does nothing until sent"]
pub struct ReleaseRequest<'c> {
client: &'c Client,
}
impl ReleaseRequest<'_> {
pub async fn send(self) -> Result<Response<Release>, Error> {
self.client
.send(Call::new("getRelease", &["release"]))
.await
}
}