ig_client/application/services/
account_service.rs

1use crate::application::services::AccountService;
2use crate::{
3    application::models::account::{
4        AccountActivity, AccountInfo, Positions, TransactionHistory, WorkingOrders,
5    },
6    config::Config,
7    error::AppError,
8    session::interface::IgSession,
9    transport::http_client::IgHttpClient,
10};
11use async_trait::async_trait;
12use reqwest::Method;
13use std::sync::Arc;
14use tracing::{debug, info};
15
16/// Implementation of the account service
17pub struct AccountServiceImpl<T: IgHttpClient> {
18    config: Arc<Config>,
19    client: Arc<T>,
20}
21
22impl<T: IgHttpClient> AccountServiceImpl<T> {
23    /// Creates a new instance of the account service
24    pub fn new(config: Arc<Config>, client: Arc<T>) -> Self {
25        Self { config, client }
26    }
27
28    /// Gets the current configuration
29    ///
30    /// # Returns
31    /// * The current configuration as an `Arc<Config>`
32    pub fn get_config(&self) -> Arc<Config> {
33        self.config.clone()
34    }
35
36    /// Sets a new configuration
37    ///
38    /// # Arguments
39    /// * `config` - The new configuration to use
40    pub fn set_config(&mut self, config: Arc<Config>) {
41        self.config = config;
42    }
43}
44
45#[async_trait]
46impl<T: IgHttpClient + 'static> AccountService for AccountServiceImpl<T> {
47    async fn get_accounts(&self, session: &IgSession) -> Result<AccountInfo, AppError> {
48        info!("Getting account information");
49
50        let result = self
51            .client
52            .request::<(), AccountInfo>(Method::GET, "accounts", session, None, "1")
53            .await?;
54
55        debug!(
56            "Account information obtained: {} accounts",
57            result.accounts.len()
58        );
59        Ok(result)
60    }
61
62    async fn get_positions(&self, session: &IgSession) -> Result<Positions, AppError> {
63        debug!("Getting open positions");
64
65        let result = self
66            .client
67            .request::<(), Positions>(Method::GET, "positions", session, None, "2")
68            .await?;
69
70        debug!("Positions obtained: {} positions", result.positions.len());
71        Ok(result)
72    }
73
74    async fn get_working_orders(&self, session: &IgSession) -> Result<WorkingOrders, AppError> {
75        info!("Getting working orders");
76
77        let result = self
78            .client
79            .request::<(), WorkingOrders>(Method::GET, "workingorders", session, None, "2")
80            .await?;
81
82        debug!(
83            "Working orders obtained: {} orders",
84            result.working_orders.len()
85        );
86        Ok(result)
87    }
88
89    async fn get_activity(
90        &self,
91        session: &IgSession,
92        from: &str,
93        to: &str,
94    ) -> Result<AccountActivity, AppError> {
95        let path = format!("history/activity?from={from}&to={to}&pageSize=500");
96        info!("Getting account activity");
97
98        let result = self
99            .client
100            .request::<(), AccountActivity>(Method::GET, &path, session, None, "3")
101            .await?;
102
103        debug!(
104            "Account activity obtained: {} activities",
105            result.activities.len()
106        );
107        Ok(result)
108    }
109
110    async fn get_activity_with_details(
111        &self,
112        session: &IgSession,
113        from: &str,
114        to: &str,
115    ) -> Result<AccountActivity, AppError> {
116        let path = format!("history/activity?from={from}&to={to}&detailed=true&pageSize=500");
117        info!("Getting detailed account activity");
118
119        let result = self
120            .client
121            .request::<(), AccountActivity>(Method::GET, &path, session, None, "3")
122            .await?;
123
124        debug!(
125            "Detailed account activity obtained: {} activities",
126            result.activities.len()
127        );
128        Ok(result)
129    }
130
131    async fn get_transactions(
132        &self,
133        session: &IgSession,
134        from: &str,
135        to: &str,
136        page_size: u32,
137        page_number: u32,
138    ) -> Result<TransactionHistory, AppError> {
139        let path = format!(
140            "history/transactions?from={from}&to={to}&pageSize={page_size}&pageNumber={page_number}"
141        );
142        info!("Getting transaction history");
143
144        let result = self
145            .client
146            .request::<(), TransactionHistory>(Method::GET, &path, session, None, "2")
147            .await?;
148
149        debug!(
150            "Transaction history obtained: {} transactions",
151            result.transactions.len()
152        );
153        Ok(result)
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160    use crate::config::Config;
161    use crate::transport::http_client::IgHttpClientImpl;
162    use crate::utils::rate_limiter::RateLimitType;
163    use std::sync::Arc;
164
165    #[test]
166    fn test_get_and_set_config() {
167        let config = Arc::new(Config::with_rate_limit_type(
168            RateLimitType::TradingAccount,
169            0.7,
170        ));
171        let client = Arc::new(IgHttpClientImpl::new(config.clone()));
172        let mut service = AccountServiceImpl::new(config.clone(), client.clone());
173
174        let cfg1 = service.get_config();
175        assert!(Arc::ptr_eq(&cfg1, &config));
176
177        let new_cfg = Arc::new(Config::default());
178        service.set_config(new_cfg.clone());
179        assert!(Arc::ptr_eq(&service.get_config(), &new_cfg));
180    }
181}