septoria/
client.rs

1use crate::api::Requests;
2use crate::error::Error;
3use crate::util::build_reqwest_client;
4use reqwest::Url;
5use serde::de::DeserializeOwned;
6use serde::Serialize;
7use std::fmt::Debug;
8
9/// Paper endpoint url
10static PAPER_ENDPOINT: &str = "https://paper-trading.lemon.markets/v1";
11/// Money endpoint url
12static MONEY_ENDPOINT: &str = "https://trading.lemon.markets/v1";
13
14#[derive(Debug)]
15/// The client for the Lemon API.
16pub struct TradingClient {
17    /// The API key.
18    pub api_key: String,
19    /// The base url for the API
20    pub base_url: Url,
21    /// Internal client used for all requests.
22    pub(crate) client: reqwest::blocking::Client,
23}
24
25/// API methods for the Client
26impl Requests for TradingClient {
27    /// Generic get request
28    fn get<T: DeserializeOwned + Debug>(&self, path: &str) -> Result<T, Error> {
29        let url = format!("{}/{}", self.base_url, path);
30        let r = self.client.get(&url).send()?;
31        let json = self.response_handler(r)?;
32        Ok(json)
33    }
34    /// Generic get request with query parameters
35    fn get_with_query<T: DeserializeOwned + Debug, Q: IntoIterator + Serialize>(
36        &self,
37        path: &str,
38        query: Q,
39    ) -> Result<T, Error> {
40        let url = format!("{}/{}", self.base_url, path);
41        let r = self.client.get(&url).query(&query).send()?;
42        let json = self.response_handler(r)?;
43        Ok(json)
44    }
45    /// Generic post request
46    fn post<T: DeserializeOwned, B: Serialize>(&self, path: &str, body: B) -> Result<T, Error> {
47        let url = format!("{}/{}", self.base_url, path);
48        let body_string = serde_json::to_string(&body)?;
49        let r = self.client.post(&url).body(body_string).send()?;
50        let json = self.response_handler(r)?;
51        Ok(json)
52    }
53    /// Generic delete request
54    fn delete<T: DeserializeOwned>(&self, path: &str, path_param: &str) -> Result<T, Error> {
55        let url = format!("{}/{}/{}", self.base_url, path, path_param);
56        let r = self.client.delete(&url).send()?;
57        // .json::<T>()?;
58        let json = self.response_handler::<T>(r)?;
59        Ok(json)
60    }
61}
62
63impl TradingClient {
64    /// Create a new TradingClient
65    pub fn new(api_key: String, _endpoint: &str) -> Self {
66        let base_url = Url::parse(PAPER_ENDPOINT).unwrap();
67        let client = build_reqwest_client(&api_key);
68        Self {
69            api_key,
70            base_url,
71            client,
72        }
73    }
74
75    /// Create a new client for paper trading with the given API key.
76    pub fn paper_client(api_key: &str) -> Self {
77        TradingClient::new(api_key.to_string(), PAPER_ENDPOINT)
78    }
79
80    /// Create a new client for live trading with the given API key.
81    pub fn live_client(api_key: String) -> Self {
82        TradingClient::new(api_key, MONEY_ENDPOINT)
83    }
84}