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    ) -> Result<TransactionHistory, AppError> {
137        const PAGE_SIZE: u32 = 200;
138        let mut all_transactions = Vec::new();
139        let mut current_page = 1;
140        #[allow(unused_assignments)]
141        let mut last_metadata = None;
142
143        loop {
144            let path = format!(
145                "history/transactions?from={from}&to={to}&pageSize={PAGE_SIZE}&pageNumber={current_page}"
146            );
147            info!("Getting transaction history page {}", current_page);
148
149            let result = self
150                .client
151                .request::<(), TransactionHistory>(Method::GET, &path, session, None, "2")
152                .await?;
153
154            let total_pages = result.metadata.page_data.total_pages as u32;
155            last_metadata = Some(result.metadata);
156            all_transactions.extend(result.transactions);
157
158            if current_page >= total_pages {
159                break;
160            }
161            current_page += 1;
162        }
163
164        debug!(
165            "Total transaction history obtained: {} transactions",
166            all_transactions.len()
167        );
168
169        Ok(TransactionHistory {
170            transactions: all_transactions,
171            metadata: last_metadata
172                .ok_or_else(|| AppError::InvalidInput("Could not retrieve metadata".to_string()))?,
173        })
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::config::Config;
181    use crate::transport::http_client::IgHttpClientImpl;
182    use crate::utils::rate_limiter::RateLimitType;
183    use std::sync::Arc;
184
185    #[test]
186    fn test_get_and_set_config() {
187        let config = Arc::new(Config::with_rate_limit_type(
188            RateLimitType::TradingAccount,
189            0.7,
190        ));
191        let client = Arc::new(IgHttpClientImpl::new(config.clone()));
192        let mut service = AccountServiceImpl::new(config.clone(), client.clone());
193
194        let cfg1 = service.get_config();
195        assert!(Arc::ptr_eq(&cfg1, &config));
196
197        let new_cfg = Arc::new(Config::default());
198        service.set_config(new_cfg.clone());
199        assert!(Arc::ptr_eq(&service.get_config(), &new_cfg));
200    }
201}