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
9static PAPER_ENDPOINT: &str = "https://paper-trading.lemon.markets/v1";
11static MONEY_ENDPOINT: &str = "https://trading.lemon.markets/v1";
13
14#[derive(Debug)]
15pub struct TradingClient {
17 pub api_key: String,
19 pub base_url: Url,
21 pub(crate) client: reqwest::blocking::Client,
23}
24
25impl Requests for TradingClient {
27 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 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 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 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 let json = self.response_handler::<T>(r)?;
59 Ok(json)
60 }
61}
62
63impl TradingClient {
64 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 pub fn paper_client(api_key: &str) -> Self {
77 TradingClient::new(api_key.to_string(), PAPER_ENDPOINT)
78 }
79
80 pub fn live_client(api_key: String) -> Self {
82 TradingClient::new(api_key, MONEY_ENDPOINT)
83 }
84}