Skip to main content

openapi_rs/
lib.rs

1//! openapi-rs: protobuf/gRPC trading SDK primitives.
2//!
3//! This crate provides:
4//! - symbol-aware lot-size validation and volume quoting
5//! - auth/session/account service logic
6//! - candle history + candle streaming APIs
7//! - tonic server adapter (`OpenApiGrpcServer`)
8//! - typed async SDK client (`OpenApiSdkClient`)
9
10use std::collections::HashMap;
11use std::pin::Pin;
12use std::sync::Arc;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use chrono::{DateTime, Duration, SecondsFormat, Utc};
16use futures_core::Stream;
17use rust_decimal::Decimal;
18use thiserror::Error;
19use tokio::sync::Mutex as TokioMutex;
20#[cfg(feature = "live")]
21use tokio_stream::StreamExt as _;
22use tonic::{Request, Response, Status};
23
24#[cfg(feature = "demo")]
25mod spotware;
26#[cfg(feature = "demo")]
27pub use spotware::{SpotwareAdapterConfig, SpotwareGrpcAdapterServer};
28
29pub mod pb {
30    tonic::include_proto!("openapi");
31}
32
33pub const DEFAULT_CANDLE_LIMIT: u32 = 100;
34pub const MAX_CANDLE_LIMIT: u32 = 2_000;
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct SymbolSpec {
38    pub contract_size: Decimal,
39    pub min_lot: Decimal,
40    pub max_lot: Decimal,
41    pub lot_step: Decimal,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct VolumeQuote {
46    pub symbol: String,
47    pub lot_size: Decimal,
48    pub volume: Decimal,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Timeframe {
53    M1,
54    M5,
55    M15,
56    H1,
57    H4,
58    D1,
59}
60
61impl Timeframe {
62    fn seconds(self) -> i64 {
63        match self {
64            Self::M1 => 60,
65            Self::M5 => 300,
66            Self::M15 => 900,
67            Self::H1 => 3600,
68            Self::H4 => 14_400,
69            Self::D1 => 86_400,
70        }
71    }
72}
73
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub struct Candle {
76    pub symbol: String,
77    pub timeframe: Timeframe,
78    pub open_time: DateTime<Utc>,
79    pub close_time: DateTime<Utc>,
80    pub open: Decimal,
81    pub high: Decimal,
82    pub low: Decimal,
83    pub close: Decimal,
84    pub volume: Decimal,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub enum OrderSide {
89    Buy,
90    Sell,
91}
92
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct OrderRequest {
95    pub symbol: String,
96    pub lot_size: Decimal,
97    pub side: OrderSide,
98}
99
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct OrderExecution {
102    pub order_id: u64,
103    pub account_id: String,
104    pub symbol: String,
105    pub lot_size: Decimal,
106    pub volume: Decimal,
107    pub side: OrderSide,
108    pub margin_used: Decimal,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct OpenPosition {
113    pub position_id: u64,
114    pub account_id: String,
115    pub symbol: String,
116    pub lot_size: Decimal,
117    pub volume: Decimal,
118    pub side: OrderSide,
119}
120
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct AccountBalance {
123    pub account_id: String,
124    pub balance: Decimal,
125    pub used_margin: Decimal,
126    pub free_margin: Decimal,
127}
128
129#[derive(Debug, Clone, PartialEq, Eq)]
130struct Account {
131    account_id: String,
132    balance: Decimal,
133    used_margin: Decimal,
134}
135
136impl Account {
137    fn free_margin(&self) -> Decimal {
138        self.balance - self.used_margin
139    }
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
143struct UserRecord {
144    password: String,
145    account_id: String,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
149struct SessionRecord {
150    username: String,
151}
152
153#[derive(Debug, Clone)]
154struct CandleQuery {
155    symbol: String,
156    timeframe: Timeframe,
157    from_time: DateTime<Utc>,
158    to_time: DateTime<Utc>,
159    limit: u32,
160}
161
162#[derive(Debug, Error, PartialEq, Eq)]
163pub enum OpenApiError {
164    #[error("symbol '{0}' not found")]
165    SymbolNotFound(String),
166    #[error("lot size must be greater than zero")]
167    NonPositiveLotSize,
168    #[error("lot size {lot_size} is outside allowed range [{min_lot}, {max_lot}]")]
169    LotOutOfRange {
170        lot_size: Decimal,
171        min_lot: Decimal,
172        max_lot: Decimal,
173    },
174    #[error("lot size {lot_size} does not match lot step {lot_step} from min lot {min_lot}")]
175    InvalidLotStep {
176        lot_size: Decimal,
177        lot_step: Decimal,
178        min_lot: Decimal,
179    },
180    #[error("invalid credentials")]
181    InvalidCredentials,
182    #[error("session token not found")]
183    SessionNotFound,
184    #[error("user '{0}' already exists")]
185    UserAlreadyExists(String),
186    #[error("account '{0}' already exists")]
187    AccountAlreadyExists(String),
188    #[error("account '{0}' not found")]
189    AccountNotFound(String),
190    #[error("insufficient margin: required {required}, available {available}")]
191    InsufficientMargin { required: Decimal, available: Decimal },
192    #[error("invalid decimal for field '{field}': '{value}'")]
193    InvalidDecimalField { field: &'static str, value: String },
194    #[error("unsupported order side: {0}")]
195    UnsupportedOrderSide(i32),
196    #[error("unsupported timeframe: {0}")]
197    UnsupportedTimeframe(i32),
198    #[error("limit {limit} exceeds maximum allowed {max}")]
199    CandleLimitTooLarge { limit: u32, max: u32 },
200    #[error("invalid UTC timestamp for field '{field}': '{value}'")]
201    InvalidUtcTimestamp { field: &'static str, value: String },
202    #[error("invalid time range: from_time {from_time} must be before to_time {to_time}")]
203    InvalidTimeRange { from_time: String, to_time: String },
204    #[error("grpc status: {0}")]
205    GrpcStatus(String),
206}
207
208#[derive(Debug, Default)]
209pub struct OpenApiEngine {
210    symbols: HashMap<String, SymbolSpec>,
211}
212
213impl OpenApiEngine {
214    pub fn new() -> Self {
215        Self::default()
216    }
217
218    pub fn with_symbols(symbols: impl IntoIterator<Item = (impl Into<String>, SymbolSpec)>) -> Self {
219        let mut engine = Self::new();
220        for (symbol, spec) in symbols {
221            engine.register_symbol(symbol, spec);
222        }
223        engine
224    }
225
226    pub fn register_symbol(&mut self, symbol: impl Into<String>, spec: SymbolSpec) {
227        self.symbols.insert(normalize_symbol(symbol), spec);
228    }
229
230    pub fn has_symbol(&self, symbol: impl AsRef<str>) -> bool {
231        self.symbols.contains_key(&normalize_symbol(symbol.as_ref()))
232    }
233
234    pub fn volume_from_lot_size(
235        &self,
236        symbol: impl AsRef<str>,
237        lot_size: Decimal,
238    ) -> Result<VolumeQuote, OpenApiError> {
239        if lot_size <= Decimal::ZERO {
240            return Err(OpenApiError::NonPositiveLotSize);
241        }
242
243        let normalized_symbol = normalize_symbol(symbol.as_ref());
244        let spec = self
245            .symbols
246            .get(&normalized_symbol)
247            .ok_or_else(|| OpenApiError::SymbolNotFound(symbol.as_ref().to_string()))?;
248
249        if lot_size < spec.min_lot || lot_size > spec.max_lot {
250            return Err(OpenApiError::LotOutOfRange {
251                lot_size,
252                min_lot: spec.min_lot,
253                max_lot: spec.max_lot,
254            });
255        }
256
257        let offset = lot_size - spec.min_lot;
258        let remainder = offset % spec.lot_step;
259        if !remainder.is_zero() {
260            return Err(OpenApiError::InvalidLotStep {
261                lot_size,
262                lot_step: spec.lot_step,
263                min_lot: spec.min_lot,
264            });
265        }
266
267        Ok(VolumeQuote {
268            symbol: normalized_symbol,
269            lot_size,
270            volume: lot_size * spec.contract_size,
271        })
272    }
273
274    pub fn quote_volume_proto(
275        &self,
276        request: pb::QuoteVolumeRequest,
277    ) -> Result<pb::QuoteVolumeResponse, OpenApiError> {
278        let lot_size = parse_decimal_field("lot_size", &request.lot_size)?;
279        let quote = self.volume_from_lot_size(request.symbol, lot_size)?;
280
281        Ok(pb::QuoteVolumeResponse {
282            quote: Some(pb::VolumeQuote {
283                symbol: quote.symbol,
284                lot_size: quote.lot_size.to_string(),
285                volume: quote.volume.to_string(),
286            }),
287        })
288    }
289}
290
291#[derive(Debug)]
292pub struct OpenApiService {
293    engine: OpenApiEngine,
294    users: HashMap<String, UserRecord>,
295    sessions: HashMap<String, SessionRecord>,
296    accounts: HashMap<String, Account>,
297    open_positions: HashMap<String, Vec<OpenPosition>>,
298    next_session_id: AtomicU64,
299    next_order_id: AtomicU64,
300    next_position_id: AtomicU64,
301    leverage: Decimal,
302}
303
304impl OpenApiService {
305    pub fn new(engine: OpenApiEngine) -> Self {
306        Self {
307            engine,
308            users: HashMap::new(),
309            sessions: HashMap::new(),
310            accounts: HashMap::new(),
311            open_positions: HashMap::new(),
312            next_session_id: AtomicU64::new(1),
313            next_order_id: AtomicU64::new(1),
314            next_position_id: AtomicU64::new(1),
315            leverage: Decimal::new(100, 0),
316        }
317    }
318
319    pub fn register_user(
320        &mut self,
321        username: impl AsRef<str>,
322        password: impl Into<String>,
323        account_id: impl Into<String>,
324        initial_balance: Decimal,
325    ) -> Result<(), OpenApiError> {
326        let normalized_username = normalize_username(username.as_ref());
327        if self.users.contains_key(&normalized_username) {
328            return Err(OpenApiError::UserAlreadyExists(username.as_ref().to_string()));
329        }
330
331        let account_id = account_id.into();
332        if self.accounts.contains_key(&account_id) {
333            return Err(OpenApiError::AccountAlreadyExists(account_id));
334        }
335
336        self.accounts.insert(
337            account_id.clone(),
338            Account {
339                account_id: account_id.clone(),
340                balance: initial_balance,
341                used_margin: Decimal::ZERO,
342            },
343        );
344        self.open_positions.insert(account_id.clone(), Vec::new());
345
346        self.users.insert(
347            normalized_username,
348            UserRecord {
349                password: password.into(),
350                account_id,
351            },
352        );
353
354        Ok(())
355    }
356
357    pub fn login(
358        &mut self,
359        username: impl AsRef<str>,
360        password: impl AsRef<str>,
361    ) -> Result<String, OpenApiError> {
362        let normalized_username = normalize_username(username.as_ref());
363        let user = self
364            .users
365            .get(&normalized_username)
366            .ok_or(OpenApiError::InvalidCredentials)?;
367
368        if user.password != password.as_ref() {
369            return Err(OpenApiError::InvalidCredentials);
370        }
371
372        let session_id = self.next_session_id.fetch_add(1, Ordering::Relaxed);
373        let token = format!("sess-{session_id}");
374
375        self.sessions.insert(
376            token.clone(),
377            SessionRecord {
378                username: normalized_username,
379            },
380        );
381
382        Ok(token)
383    }
384
385    pub fn logout(&mut self, token: impl AsRef<str>) -> Result<(), OpenApiError> {
386        if self.sessions.remove(token.as_ref()).is_none() {
387            return Err(OpenApiError::SessionNotFound);
388        }
389
390        Ok(())
391    }
392
393    pub fn fetch_balance(&self, token: impl AsRef<str>) -> Result<AccountBalance, OpenApiError> {
394        let account = self.account_for_token(token.as_ref())?;
395
396        Ok(AccountBalance {
397            account_id: account.account_id.clone(),
398            balance: account.balance,
399            used_margin: account.used_margin,
400            free_margin: account.free_margin(),
401        })
402    }
403
404    pub fn fetch_open_positions(
405        &self,
406        token: impl AsRef<str>,
407    ) -> Result<Vec<OpenPosition>, OpenApiError> {
408        let account_id = self.account_id_for_token(token.as_ref())?;
409        let positions = self
410            .open_positions
411            .get(&account_id)
412            .ok_or_else(|| OpenApiError::AccountNotFound(account_id.clone()))?;
413
414        Ok(positions.clone())
415    }
416
417    pub fn place_market_order(
418        &mut self,
419        token: impl AsRef<str>,
420        request: OrderRequest,
421    ) -> Result<OrderExecution, OpenApiError> {
422        let volume_quote = self
423            .engine
424            .volume_from_lot_size(&request.symbol, request.lot_size)?;
425
426        let account_id = self.account_id_for_token(token.as_ref())?;
427        let account = self
428            .accounts
429            .get_mut(&account_id)
430            .ok_or_else(|| OpenApiError::AccountNotFound(account_id.clone()))?;
431
432        let margin_required = volume_quote.volume / self.leverage;
433        let free_margin = account.free_margin();
434        if free_margin < margin_required {
435            return Err(OpenApiError::InsufficientMargin {
436                required: margin_required,
437                available: free_margin,
438            });
439        }
440
441        account.used_margin += margin_required;
442
443        let order_id = self.next_order_id.fetch_add(1, Ordering::Relaxed);
444        let position_id = self.next_position_id.fetch_add(1, Ordering::Relaxed);
445
446        self.open_positions
447            .entry(account_id.clone())
448            .or_default()
449            .push(OpenPosition {
450                position_id,
451                account_id: account_id.clone(),
452                symbol: volume_quote.symbol.clone(),
453                lot_size: volume_quote.lot_size,
454                volume: volume_quote.volume,
455                side: request.side.clone(),
456            });
457
458        Ok(OrderExecution {
459            order_id,
460            account_id,
461            symbol: volume_quote.symbol,
462            lot_size: volume_quote.lot_size,
463            volume: volume_quote.volume,
464            side: request.side,
465            margin_used: margin_required,
466        })
467    }
468
469    pub fn register_user_proto(
470        &mut self,
471        request: pb::RegisterUserRequest,
472    ) -> Result<pb::RegisterUserResponse, OpenApiError> {
473        let initial_balance = parse_decimal_field("initial_balance", &request.initial_balance)?;
474
475        self.register_user(
476            request.username,
477            request.password,
478            request.account_id,
479            initial_balance,
480        )?;
481
482        Ok(pb::RegisterUserResponse { success: true })
483    }
484
485    pub fn login_proto(
486        &mut self,
487        request: pb::LoginRequest,
488    ) -> Result<pb::LoginResponse, OpenApiError> {
489        let session_token = self.login(request.username, request.password)?;
490        Ok(pb::LoginResponse { session_token })
491    }
492
493    pub fn logout_proto(
494        &mut self,
495        request: pb::LogoutRequest,
496    ) -> Result<pb::LogoutResponse, OpenApiError> {
497        self.logout(request.session_token)?;
498        Ok(pb::LogoutResponse { success: true })
499    }
500
501    pub fn fetch_balance_proto(
502        &self,
503        request: pb::FetchBalanceRequest,
504    ) -> Result<pb::FetchBalanceResponse, OpenApiError> {
505        let balance = self.fetch_balance(request.session_token)?;
506
507        Ok(pb::FetchBalanceResponse {
508            balance: Some(pb::AccountBalance {
509                account_id: balance.account_id,
510                balance: balance.balance.to_string(),
511                used_margin: balance.used_margin.to_string(),
512                free_margin: balance.free_margin.to_string(),
513            }),
514        })
515    }
516
517    pub fn fetch_open_positions_proto(
518        &self,
519        request: pb::FetchOpenPositionsRequest,
520    ) -> Result<pb::FetchOpenPositionsResponse, OpenApiError> {
521        let positions = self.fetch_open_positions(request.session_token)?;
522
523        Ok(pb::FetchOpenPositionsResponse {
524            positions: positions
525                .into_iter()
526                .map(|position| pb::OpenPosition {
527                    position_id: position.position_id,
528                    account_id: position.account_id,
529                    symbol: position.symbol,
530                    lot_size: position.lot_size.to_string(),
531                    volume: position.volume.to_string(),
532                    side: domain_side_to_proto(position.side) as i32,
533                })
534                .collect(),
535        })
536    }
537
538    pub fn place_market_order_proto(
539        &mut self,
540        request: pb::PlaceMarketOrderRequest,
541    ) -> Result<pb::PlaceMarketOrderResponse, OpenApiError> {
542        let lot_size = parse_decimal_field("lot_size", &request.lot_size)?;
543        let side = proto_side_to_domain(request.side)?;
544
545        let execution = self.place_market_order(
546            request.session_token,
547            OrderRequest {
548                symbol: request.symbol,
549                lot_size,
550                side,
551            },
552        )?;
553
554        Ok(pb::PlaceMarketOrderResponse {
555            execution: Some(pb::OrderExecution {
556                order_id: execution.order_id,
557                account_id: execution.account_id,
558                symbol: execution.symbol,
559                lot_size: execution.lot_size.to_string(),
560                volume: execution.volume.to_string(),
561                side: domain_side_to_proto(execution.side) as i32,
562                margin_used: execution.margin_used.to_string(),
563            }),
564        })
565    }
566
567    pub fn get_candles_proto(
568        &self,
569        request: pb::GetCandlesRequest,
570    ) -> Result<pb::GetCandlesResponse, OpenApiError> {
571        let candles = self.build_candles(CandleQuery {
572            symbol: request.symbol,
573            timeframe: proto_timeframe_to_domain(request.timeframe)?,
574            from_time: Utc::now(),
575            to_time: Utc::now(),
576            limit: request.limit,
577        }, request.from_time, request.to_time)?;
578
579        Ok(pb::GetCandlesResponse { candles })
580    }
581
582    pub fn stream_candles_proto(
583        &self,
584        request: pb::StreamCandlesRequest,
585    ) -> Result<Vec<pb::Candle>, OpenApiError> {
586        self.build_candles(CandleQuery {
587            symbol: request.symbol,
588            timeframe: proto_timeframe_to_domain(request.timeframe)?,
589            from_time: Utc::now(),
590            to_time: Utc::now(),
591            limit: request.limit,
592        }, request.from_time, request.to_time)
593    }
594
595    pub fn get_server_time_proto(
596        &self,
597        _request: pb::GetServerTimeRequest,
598    ) -> Result<pb::GetServerTimeResponse, OpenApiError> {
599        Ok(pb::GetServerTimeResponse {
600            server_time: format_utc(Utc::now()),
601        })
602    }
603
604    fn build_candles(
605        &self,
606        mut query: CandleQuery,
607        from_time_str: String,
608        to_time_str: String,
609    ) -> Result<Vec<pb::Candle>, OpenApiError> {
610        query.symbol = normalize_symbol(query.symbol);
611        if !self.engine.has_symbol(&query.symbol) {
612            return Err(OpenApiError::SymbolNotFound(query.symbol));
613        }
614
615        let limit = if query.limit == 0 {
616            DEFAULT_CANDLE_LIMIT
617        } else {
618            query.limit
619        };
620        if limit > MAX_CANDLE_LIMIT {
621            return Err(OpenApiError::CandleLimitTooLarge {
622                limit,
623                max: MAX_CANDLE_LIMIT,
624            });
625        }
626
627        let (from_time, to_time) = resolve_time_window(
628            &from_time_str,
629            &to_time_str,
630            query.timeframe,
631            limit,
632        )?;
633
634        query.from_time = from_time;
635        query.to_time = to_time;
636        query.limit = limit;
637
638        let mut candles = Vec::with_capacity(limit as usize);
639        let step_seconds = query.timeframe.seconds();
640        let seed = query
641            .symbol
642            .bytes()
643            .fold(0_u64, |acc, b| acc.wrapping_add(b as u64)) as i64;
644
645        for i in 0..limit {
646            let open_time = query.from_time + Duration::seconds(step_seconds * i as i64);
647            let close_time = open_time + Duration::seconds(step_seconds);
648            if close_time > query.to_time {
649                break;
650            }
651
652            let open = Decimal::new(10_000 + (seed % 2_000) + i as i64 * 2, 2);
653            let high = open + Decimal::new(15, 2);
654            let low = open - Decimal::new(12, 2);
655            let close = open + Decimal::new(3, 2);
656            let volume = Decimal::new(1_000 + i as i64 * 10, 2);
657
658            candles.push(pb::Candle {
659                symbol: query.symbol.clone(),
660                timeframe: domain_timeframe_to_proto(query.timeframe) as i32,
661                open_time: format_utc(open_time),
662                close_time: format_utc(close_time),
663                open: open.to_string(),
664                high: high.to_string(),
665                low: low.to_string(),
666                close: close.to_string(),
667                volume: volume.to_string(),
668            });
669        }
670
671        Ok(candles)
672    }
673
674    fn account_for_token(&self, token: &str) -> Result<&Account, OpenApiError> {
675        let account_id = self.account_id_for_token(token)?;
676        self.accounts
677            .get(&account_id)
678            .ok_or(OpenApiError::AccountNotFound(account_id))
679    }
680
681    fn account_id_for_token(&self, token: &str) -> Result<String, OpenApiError> {
682        let session = self
683            .sessions
684            .get(token)
685            .ok_or(OpenApiError::SessionNotFound)?;
686
687        let user = self
688            .users
689            .get(&session.username)
690            .ok_or(OpenApiError::InvalidCredentials)?;
691
692        Ok(user.account_id.clone())
693    }
694}
695
696#[derive(Clone, Debug)]
697pub struct OpenApiGrpcServer {
698    inner: Arc<TokioMutex<OpenApiService>>,
699}
700
701impl OpenApiGrpcServer {
702    pub fn new(service: OpenApiService) -> Self {
703        Self {
704            inner: Arc::new(TokioMutex::new(service)),
705        }
706    }
707
708    pub fn into_tonic_service(self) -> pb::open_api_service_server::OpenApiServiceServer<Self> {
709        pb::open_api_service_server::OpenApiServiceServer::new(self)
710    }
711}
712
713#[cfg(feature = "live")]
714#[derive(Clone, Debug)]
715pub struct BrokerGrpcAdapterServer {
716    upstream: Arc<
717        TokioMutex<pb::open_api_service_client::OpenApiServiceClient<tonic::transport::Channel>>,
718    >,
719}
720
721#[cfg(feature = "live")]
722impl BrokerGrpcAdapterServer {
723    pub async fn connect(upstream_url: impl Into<String>) -> Result<Self, tonic::transport::Error> {
724        let client = pb::open_api_service_client::OpenApiServiceClient::connect(upstream_url.into())
725            .await?;
726        Ok(Self {
727            upstream: Arc::new(TokioMutex::new(client)),
728        })
729    }
730
731    pub fn into_tonic_service(self) -> pb::open_api_service_server::OpenApiServiceServer<Self> {
732        pb::open_api_service_server::OpenApiServiceServer::new(self)
733    }
734}
735
736#[tonic::async_trait]
737impl pb::open_api_service_server::OpenApiService for OpenApiGrpcServer {
738    type StreamCandlesStream = Pin<Box<dyn Stream<Item = Result<pb::StreamCandlesResponse, Status>> + Send + 'static>>;
739
740    async fn register_user(
741        &self,
742        request: Request<pb::RegisterUserRequest>,
743    ) -> Result<Response<pb::RegisterUserResponse>, Status> {
744        let mut service = self.inner.lock().await;
745        let response = service
746            .register_user_proto(request.into_inner())
747            .map_err(open_api_error_to_status)?;
748        Ok(Response::new(response))
749    }
750
751    async fn login(
752        &self,
753        request: Request<pb::LoginRequest>,
754    ) -> Result<Response<pb::LoginResponse>, Status> {
755        let mut service = self.inner.lock().await;
756        let response = service
757            .login_proto(request.into_inner())
758            .map_err(open_api_error_to_status)?;
759        Ok(Response::new(response))
760    }
761
762    async fn logout(
763        &self,
764        request: Request<pb::LogoutRequest>,
765    ) -> Result<Response<pb::LogoutResponse>, Status> {
766        let mut service = self.inner.lock().await;
767        let response = service
768            .logout_proto(request.into_inner())
769            .map_err(open_api_error_to_status)?;
770        Ok(Response::new(response))
771    }
772
773    async fn fetch_balance(
774        &self,
775        request: Request<pb::FetchBalanceRequest>,
776    ) -> Result<Response<pb::FetchBalanceResponse>, Status> {
777        let service = self.inner.lock().await;
778        let response = service
779            .fetch_balance_proto(request.into_inner())
780            .map_err(open_api_error_to_status)?;
781        Ok(Response::new(response))
782    }
783
784    async fn fetch_open_positions(
785        &self,
786        request: Request<pb::FetchOpenPositionsRequest>,
787    ) -> Result<Response<pb::FetchOpenPositionsResponse>, Status> {
788        let service = self.inner.lock().await;
789        let response = service
790            .fetch_open_positions_proto(request.into_inner())
791            .map_err(open_api_error_to_status)?;
792        Ok(Response::new(response))
793    }
794
795    async fn place_market_order(
796        &self,
797        request: Request<pb::PlaceMarketOrderRequest>,
798    ) -> Result<Response<pb::PlaceMarketOrderResponse>, Status> {
799        let mut service = self.inner.lock().await;
800        let response = service
801            .place_market_order_proto(request.into_inner())
802            .map_err(open_api_error_to_status)?;
803        Ok(Response::new(response))
804    }
805
806    async fn quote_volume(
807        &self,
808        request: Request<pb::QuoteVolumeRequest>,
809    ) -> Result<Response<pb::QuoteVolumeResponse>, Status> {
810        let service = self.inner.lock().await;
811        let response = service
812            .engine
813            .quote_volume_proto(request.into_inner())
814            .map_err(open_api_error_to_status)?;
815        Ok(Response::new(response))
816    }
817
818    async fn get_candles(
819        &self,
820        request: Request<pb::GetCandlesRequest>,
821    ) -> Result<Response<pb::GetCandlesResponse>, Status> {
822        let service = self.inner.lock().await;
823        let response = service
824            .get_candles_proto(request.into_inner())
825            .map_err(open_api_error_to_status)?;
826        Ok(Response::new(response))
827    }
828
829    async fn stream_candles(
830        &self,
831        request: Request<pb::StreamCandlesRequest>,
832    ) -> Result<Response<Self::StreamCandlesStream>, Status> {
833        let service = self.inner.lock().await;
834        let candles = service
835            .stream_candles_proto(request.into_inner())
836            .map_err(open_api_error_to_status)?;
837
838        let stream = tokio_stream::iter(candles.into_iter().map(|candle| {
839            Ok(pb::StreamCandlesResponse {
840                candle: Some(candle),
841            })
842        }));
843
844        Ok(Response::new(Box::pin(stream) as Self::StreamCandlesStream))
845    }
846
847    async fn get_server_time(
848        &self,
849        request: Request<pb::GetServerTimeRequest>,
850    ) -> Result<Response<pb::GetServerTimeResponse>, Status> {
851        let service = self.inner.lock().await;
852        let response = service
853            .get_server_time_proto(request.into_inner())
854            .map_err(open_api_error_to_status)?;
855        Ok(Response::new(response))
856    }
857}
858
859#[cfg(feature = "live")]
860#[tonic::async_trait]
861impl pb::open_api_service_server::OpenApiService for BrokerGrpcAdapterServer {
862    type StreamCandlesStream =
863        Pin<Box<dyn Stream<Item = Result<pb::StreamCandlesResponse, Status>> + Send + 'static>>;
864
865    async fn register_user(
866        &self,
867        request: Request<pb::RegisterUserRequest>,
868    ) -> Result<Response<pb::RegisterUserResponse>, Status> {
869        let mut client = self.upstream.lock().await;
870        client.register_user(request.into_inner()).await
871    }
872
873    async fn login(
874        &self,
875        request: Request<pb::LoginRequest>,
876    ) -> Result<Response<pb::LoginResponse>, Status> {
877        let mut client = self.upstream.lock().await;
878        client.login(request.into_inner()).await
879    }
880
881    async fn logout(
882        &self,
883        request: Request<pb::LogoutRequest>,
884    ) -> Result<Response<pb::LogoutResponse>, Status> {
885        let mut client = self.upstream.lock().await;
886        client.logout(request.into_inner()).await
887    }
888
889    async fn fetch_balance(
890        &self,
891        request: Request<pb::FetchBalanceRequest>,
892    ) -> Result<Response<pb::FetchBalanceResponse>, Status> {
893        let mut client = self.upstream.lock().await;
894        client.fetch_balance(request.into_inner()).await
895    }
896
897    async fn fetch_open_positions(
898        &self,
899        request: Request<pb::FetchOpenPositionsRequest>,
900    ) -> Result<Response<pb::FetchOpenPositionsResponse>, Status> {
901        let mut client = self.upstream.lock().await;
902        client.fetch_open_positions(request.into_inner()).await
903    }
904
905    async fn place_market_order(
906        &self,
907        request: Request<pb::PlaceMarketOrderRequest>,
908    ) -> Result<Response<pb::PlaceMarketOrderResponse>, Status> {
909        let mut client = self.upstream.lock().await;
910        client.place_market_order(request.into_inner()).await
911    }
912
913    async fn quote_volume(
914        &self,
915        request: Request<pb::QuoteVolumeRequest>,
916    ) -> Result<Response<pb::QuoteVolumeResponse>, Status> {
917        let mut client = self.upstream.lock().await;
918        client.quote_volume(request.into_inner()).await
919    }
920
921    async fn get_candles(
922        &self,
923        request: Request<pb::GetCandlesRequest>,
924    ) -> Result<Response<pb::GetCandlesResponse>, Status> {
925        let mut client = self.upstream.lock().await;
926        client.get_candles(request.into_inner()).await
927    }
928
929    async fn stream_candles(
930        &self,
931        request: Request<pb::StreamCandlesRequest>,
932    ) -> Result<Response<Self::StreamCandlesStream>, Status> {
933        let mut client = self.upstream.lock().await;
934        let upstream_stream = client.stream_candles(request.into_inner()).await?.into_inner();
935        let mapped = upstream_stream.map(|item| item.map_err(|status| status));
936        Ok(Response::new(Box::pin(mapped) as Self::StreamCandlesStream))
937    }
938
939    async fn get_server_time(
940        &self,
941        request: Request<pb::GetServerTimeRequest>,
942    ) -> Result<Response<pb::GetServerTimeResponse>, Status> {
943        let mut client = self.upstream.lock().await;
944        client.get_server_time(request.into_inner()).await
945    }
946}
947
948#[derive(Clone, Debug)]
949pub struct OpenApiSdkClient {
950    inner: pb::open_api_service_client::OpenApiServiceClient<tonic::transport::Channel>,
951}
952
953impl OpenApiSdkClient {
954    pub async fn connect(dst: impl Into<String>) -> Result<Self, tonic::transport::Error> {
955        let inner = pb::open_api_service_client::OpenApiServiceClient::connect(dst.into()).await?;
956        Ok(Self { inner })
957    }
958
959    pub async fn register_user(
960        &mut self,
961        username: impl Into<String>,
962        password: impl Into<String>,
963        account_id: impl Into<String>,
964        initial_balance: Decimal,
965    ) -> Result<(), OpenApiError> {
966        self.inner
967            .register_user(pb::RegisterUserRequest {
968                username: username.into(),
969                password: password.into(),
970                account_id: account_id.into(),
971                initial_balance: initial_balance.to_string(),
972            })
973            .await
974            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?;
975        Ok(())
976    }
977
978    pub async fn login(
979        &mut self,
980        username: impl Into<String>,
981        password: impl Into<String>,
982    ) -> Result<String, OpenApiError> {
983        let response = self
984            .inner
985            .login(pb::LoginRequest {
986                username: username.into(),
987                password: password.into(),
988            })
989            .await
990            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
991            .into_inner();
992
993        Ok(response.session_token)
994    }
995
996    pub async fn logout(&mut self, session_token: impl Into<String>) -> Result<(), OpenApiError> {
997        self.inner
998            .logout(pb::LogoutRequest {
999                session_token: session_token.into(),
1000            })
1001            .await
1002            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?;
1003        Ok(())
1004    }
1005
1006    pub async fn fetch_balance(
1007        &mut self,
1008        session_token: impl Into<String>,
1009    ) -> Result<AccountBalance, OpenApiError> {
1010        let response = self
1011            .inner
1012            .fetch_balance(pb::FetchBalanceRequest {
1013                session_token: session_token.into(),
1014            })
1015            .await
1016            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1017            .into_inner();
1018
1019        let balance = response
1020            .balance
1021            .ok_or_else(|| OpenApiError::GrpcStatus("missing balance payload".to_string()))?;
1022
1023        Ok(AccountBalance {
1024            account_id: balance.account_id,
1025            balance: parse_decimal_field("balance", &balance.balance)?,
1026            used_margin: parse_decimal_field("used_margin", &balance.used_margin)?,
1027            free_margin: parse_decimal_field("free_margin", &balance.free_margin)?,
1028        })
1029    }
1030
1031    pub async fn fetch_open_positions(
1032        &mut self,
1033        session_token: impl Into<String>,
1034    ) -> Result<Vec<OpenPosition>, OpenApiError> {
1035        let response = self
1036            .inner
1037            .fetch_open_positions(pb::FetchOpenPositionsRequest {
1038                session_token: session_token.into(),
1039            })
1040            .await
1041            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1042            .into_inner();
1043
1044        response
1045            .positions
1046            .into_iter()
1047            .map(|position| {
1048                Ok(OpenPosition {
1049                    position_id: position.position_id,
1050                    account_id: position.account_id,
1051                    symbol: position.symbol,
1052                    lot_size: parse_decimal_field("lot_size", &position.lot_size)?,
1053                    volume: parse_decimal_field("volume", &position.volume)?,
1054                    side: proto_side_to_domain(position.side)?,
1055                })
1056            })
1057            .collect()
1058    }
1059
1060    pub async fn quote_volume(
1061        &mut self,
1062        symbol: impl Into<String>,
1063        lot_size: Decimal,
1064    ) -> Result<VolumeQuote, OpenApiError> {
1065        let response = self
1066            .inner
1067            .quote_volume(pb::QuoteVolumeRequest {
1068                symbol: symbol.into(),
1069                lot_size: lot_size.to_string(),
1070            })
1071            .await
1072            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1073            .into_inner();
1074
1075        let quote = response
1076            .quote
1077            .ok_or_else(|| OpenApiError::GrpcStatus("missing quote payload".to_string()))?;
1078
1079        Ok(VolumeQuote {
1080            symbol: quote.symbol,
1081            lot_size: parse_decimal_field("lot_size", &quote.lot_size)?,
1082            volume: parse_decimal_field("volume", &quote.volume)?,
1083        })
1084    }
1085
1086    pub async fn place_market_order(
1087        &mut self,
1088        session_token: impl Into<String>,
1089        symbol: impl Into<String>,
1090        lot_size: Decimal,
1091        side: OrderSide,
1092    ) -> Result<OrderExecution, OpenApiError> {
1093        let response = self
1094            .inner
1095            .place_market_order(pb::PlaceMarketOrderRequest {
1096                session_token: session_token.into(),
1097                symbol: symbol.into(),
1098                lot_size: lot_size.to_string(),
1099                side: domain_side_to_proto(side).into(),
1100            })
1101            .await
1102            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1103            .into_inner();
1104
1105        let execution = response
1106            .execution
1107            .ok_or_else(|| OpenApiError::GrpcStatus("missing execution payload".to_string()))?;
1108
1109        Ok(OrderExecution {
1110            order_id: execution.order_id,
1111            account_id: execution.account_id,
1112            symbol: execution.symbol,
1113            lot_size: parse_decimal_field("lot_size", &execution.lot_size)?,
1114            volume: parse_decimal_field("volume", &execution.volume)?,
1115            side: proto_side_to_domain(execution.side)?,
1116            margin_used: parse_decimal_field("margin_used", &execution.margin_used)?,
1117        })
1118    }
1119
1120    pub async fn get_candles(
1121        &mut self,
1122        symbol: impl Into<String>,
1123        timeframe: Timeframe,
1124        from_time: Option<DateTime<Utc>>,
1125        to_time: Option<DateTime<Utc>>,
1126        limit: u32,
1127    ) -> Result<Vec<Candle>, OpenApiError> {
1128        let response = self
1129            .inner
1130            .get_candles(pb::GetCandlesRequest {
1131                symbol: symbol.into(),
1132                timeframe: domain_timeframe_to_proto(timeframe) as i32,
1133                from_time: from_time.map(format_utc).unwrap_or_default(),
1134                to_time: to_time.map(format_utc).unwrap_or_default(),
1135                limit,
1136            })
1137            .await
1138            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1139            .into_inner();
1140
1141        response
1142            .candles
1143            .into_iter()
1144            .map(candle_from_proto)
1145            .collect()
1146    }
1147
1148    pub async fn stream_candles(
1149        &mut self,
1150        symbol: impl Into<String>,
1151        timeframe: Timeframe,
1152        from_time: Option<DateTime<Utc>>,
1153        to_time: Option<DateTime<Utc>>,
1154        limit: u32,
1155    ) -> Result<tonic::Streaming<pb::StreamCandlesResponse>, OpenApiError> {
1156        let stream = self
1157            .inner
1158            .stream_candles(pb::StreamCandlesRequest {
1159                symbol: symbol.into(),
1160                timeframe: domain_timeframe_to_proto(timeframe) as i32,
1161                from_time: from_time.map(format_utc).unwrap_or_default(),
1162                to_time: to_time.map(format_utc).unwrap_or_default(),
1163                limit,
1164            })
1165            .await
1166            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1167            .into_inner();
1168
1169        Ok(stream)
1170    }
1171
1172    pub async fn get_server_time(&mut self) -> Result<DateTime<Utc>, OpenApiError> {
1173        let response = self
1174            .inner
1175            .get_server_time(pb::GetServerTimeRequest {})
1176            .await
1177            .map_err(|e| OpenApiError::GrpcStatus(e.to_string()))?
1178            .into_inner();
1179
1180        parse_utc_timestamp_field("server_time", &response.server_time)
1181    }
1182}
1183
1184fn resolve_time_window(
1185    from_time: &str,
1186    to_time: &str,
1187    timeframe: Timeframe,
1188    limit: u32,
1189) -> Result<(DateTime<Utc>, DateTime<Utc>), OpenApiError> {
1190    let from_empty = from_time.trim().is_empty();
1191    let to_empty = to_time.trim().is_empty();
1192
1193    let (from, to) = match (from_empty, to_empty) {
1194        (true, true) => {
1195            let to = Utc::now();
1196            let from = to - Duration::seconds(timeframe.seconds() * limit as i64);
1197            (from, to)
1198        }
1199        (false, false) => (
1200            parse_utc_timestamp_field("from_time", from_time)?,
1201            parse_utc_timestamp_field("to_time", to_time)?,
1202        ),
1203        _ => {
1204            return Err(OpenApiError::InvalidUtcTimestamp {
1205                field: if from_empty { "from_time" } else { "to_time" },
1206                value: if from_empty {
1207                    from_time.to_string()
1208                } else {
1209                    to_time.to_string()
1210                },
1211            });
1212        }
1213    };
1214
1215    if from >= to {
1216        return Err(OpenApiError::InvalidTimeRange {
1217            from_time: format_utc(from),
1218            to_time: format_utc(to),
1219        });
1220    }
1221
1222    Ok((from, to))
1223}
1224
1225fn parse_utc_timestamp_field(field: &'static str, value: &str) -> Result<DateTime<Utc>, OpenApiError> {
1226    let parsed = DateTime::parse_from_rfc3339(value).map_err(|_| OpenApiError::InvalidUtcTimestamp {
1227        field,
1228        value: value.to_string(),
1229    })?;
1230
1231    if parsed.offset().local_minus_utc() != 0 {
1232        return Err(OpenApiError::InvalidUtcTimestamp {
1233            field,
1234            value: value.to_string(),
1235        });
1236    }
1237
1238    Ok(parsed.with_timezone(&Utc))
1239}
1240
1241fn format_utc(time: DateTime<Utc>) -> String {
1242    time.to_rfc3339_opts(SecondsFormat::Secs, true)
1243}
1244
1245fn candle_from_proto(candle: pb::Candle) -> Result<Candle, OpenApiError> {
1246    Ok(Candle {
1247        symbol: candle.symbol,
1248        timeframe: proto_timeframe_to_domain(candle.timeframe)?,
1249        open_time: parse_utc_timestamp_field("open_time", &candle.open_time)?,
1250        close_time: parse_utc_timestamp_field("close_time", &candle.close_time)?,
1251        open: parse_decimal_field("open", &candle.open)?,
1252        high: parse_decimal_field("high", &candle.high)?,
1253        low: parse_decimal_field("low", &candle.low)?,
1254        close: parse_decimal_field("close", &candle.close)?,
1255        volume: parse_decimal_field("volume", &candle.volume)?,
1256    })
1257}
1258
1259fn open_api_error_to_status(error: OpenApiError) -> Status {
1260    match error {
1261        OpenApiError::SymbolNotFound(_) => Status::not_found(error.to_string()),
1262        OpenApiError::SessionNotFound => Status::unauthenticated(error.to_string()),
1263        OpenApiError::InvalidCredentials => Status::unauthenticated(error.to_string()),
1264        OpenApiError::UserAlreadyExists(_) | OpenApiError::AccountAlreadyExists(_) => {
1265            Status::already_exists(error.to_string())
1266        }
1267        OpenApiError::InsufficientMargin { .. } => Status::failed_precondition(error.to_string()),
1268        OpenApiError::GrpcStatus(_) => Status::internal(error.to_string()),
1269        _ => Status::invalid_argument(error.to_string()),
1270    }
1271}
1272
1273fn normalize_symbol(symbol: impl Into<String>) -> String {
1274    symbol.into().trim().to_ascii_uppercase()
1275}
1276
1277fn normalize_username(username: impl Into<String>) -> String {
1278    username.into().trim().to_ascii_lowercase()
1279}
1280
1281fn parse_decimal_field(field: &'static str, value: &str) -> Result<Decimal, OpenApiError> {
1282    value
1283        .parse::<Decimal>()
1284        .map_err(|_| OpenApiError::InvalidDecimalField {
1285            field,
1286            value: value.to_string(),
1287        })
1288}
1289
1290fn proto_side_to_domain(side: i32) -> Result<OrderSide, OpenApiError> {
1291    match pb::OrderSide::try_from(side) {
1292        Ok(pb::OrderSide::Buy) => Ok(OrderSide::Buy),
1293        Ok(pb::OrderSide::Sell) => Ok(OrderSide::Sell),
1294        _ => Err(OpenApiError::UnsupportedOrderSide(side)),
1295    }
1296}
1297
1298fn domain_side_to_proto(side: OrderSide) -> pb::OrderSide {
1299    match side {
1300        OrderSide::Buy => pb::OrderSide::Buy,
1301        OrderSide::Sell => pb::OrderSide::Sell,
1302    }
1303}
1304
1305fn proto_timeframe_to_domain(timeframe: i32) -> Result<Timeframe, OpenApiError> {
1306    match pb::Timeframe::try_from(timeframe) {
1307        Ok(pb::Timeframe::M1) => Ok(Timeframe::M1),
1308        Ok(pb::Timeframe::M5) => Ok(Timeframe::M5),
1309        Ok(pb::Timeframe::M15) => Ok(Timeframe::M15),
1310        Ok(pb::Timeframe::H1) => Ok(Timeframe::H1),
1311        Ok(pb::Timeframe::H4) => Ok(Timeframe::H4),
1312        Ok(pb::Timeframe::D1) => Ok(Timeframe::D1),
1313        _ => Err(OpenApiError::UnsupportedTimeframe(timeframe)),
1314    }
1315}
1316
1317fn domain_timeframe_to_proto(timeframe: Timeframe) -> pb::Timeframe {
1318    match timeframe {
1319        Timeframe::M1 => pb::Timeframe::M1,
1320        Timeframe::M5 => pb::Timeframe::M5,
1321        Timeframe::M15 => pb::Timeframe::M15,
1322        Timeframe::H1 => pb::Timeframe::H1,
1323        Timeframe::H4 => pb::Timeframe::H4,
1324        Timeframe::D1 => pb::Timeframe::D1,
1325    }
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330    use super::*;
1331    use tokio::net::TcpListener;
1332    use tokio_stream::StreamExt;
1333    use tokio_stream::wrappers::TcpListenerStream;
1334    use tonic::transport::Server;
1335
1336    fn d(value: i64, scale: u32) -> Decimal {
1337        Decimal::new(value, scale)
1338    }
1339
1340    fn sample_engine() -> OpenApiEngine {
1341        OpenApiEngine::with_symbols([
1342            (
1343                "EURUSD",
1344                SymbolSpec {
1345                    contract_size: d(100_000, 0),
1346                    min_lot: d(1, 2),
1347                    max_lot: d(1000, 0),
1348                    lot_step: d(1, 2),
1349                },
1350            ),
1351            (
1352                "XAUUSD",
1353                SymbolSpec {
1354                    contract_size: d(100, 0),
1355                    min_lot: d(1, 1),
1356                    max_lot: d(500, 0),
1357                    lot_step: d(1, 1),
1358                },
1359            ),
1360        ])
1361    }
1362
1363    fn sample_service() -> OpenApiService {
1364        let mut service = OpenApiService::new(sample_engine());
1365        service
1366            .register_user("alice", "secret", "ACC-001", d(100_000, 0))
1367            .expect("user must be registered");
1368        service
1369    }
1370
1371    #[test]
1372    fn computes_volume_from_lot_size_for_known_symbol() {
1373        let engine = sample_engine();
1374
1375        let quote = engine
1376            .volume_from_lot_size("eurusd", d(50, 2))
1377            .expect("expected valid quote");
1378
1379        assert_eq!(quote.symbol, "EURUSD");
1380        assert_eq!(quote.volume, d(50_000, 0));
1381    }
1382
1383    #[test]
1384    fn rejects_unknown_symbol() {
1385        let engine = sample_engine();
1386
1387        let err = engine
1388            .volume_from_lot_size("UNKNOWN", d(10, 2))
1389            .expect_err("expected symbol error");
1390
1391        assert_eq!(err, OpenApiError::SymbolNotFound("UNKNOWN".to_string()));
1392    }
1393
1394    #[test]
1395    fn rejects_lot_size_out_of_range() {
1396        let engine = sample_engine();
1397
1398        let err = engine
1399            .volume_from_lot_size("XAUUSD", d(5, 2))
1400            .expect_err("expected range error");
1401
1402        assert_eq!(
1403            err,
1404            OpenApiError::LotOutOfRange {
1405                lot_size: d(5, 2),
1406                min_lot: d(1, 1),
1407                max_lot: d(500, 0),
1408            }
1409        );
1410    }
1411
1412    #[test]
1413    fn rejects_lot_size_not_matching_step() {
1414        let engine = sample_engine();
1415
1416        let err = engine
1417            .volume_from_lot_size("XAUUSD", d(15, 2))
1418            .expect_err("expected step error");
1419
1420        assert_eq!(
1421            err,
1422            OpenApiError::InvalidLotStep {
1423                lot_size: d(15, 2),
1424                lot_step: d(1, 1),
1425                min_lot: d(1, 1),
1426            }
1427        );
1428    }
1429
1430    #[test]
1431    fn candle_limit_guard_rejects_large_limit() {
1432        let service = sample_service();
1433
1434        let err = service
1435            .get_candles_proto(pb::GetCandlesRequest {
1436                symbol: "EURUSD".to_string(),
1437                timeframe: pb::Timeframe::M1 as i32,
1438                from_time: String::new(),
1439                to_time: String::new(),
1440                limit: MAX_CANDLE_LIMIT + 1,
1441            })
1442            .expect_err("limit should be rejected");
1443
1444        assert_eq!(
1445            err,
1446            OpenApiError::CandleLimitTooLarge {
1447                limit: MAX_CANDLE_LIMIT + 1,
1448                max: MAX_CANDLE_LIMIT,
1449            }
1450        );
1451    }
1452
1453    #[test]
1454    fn timeframe_validation_rejects_unspecified() {
1455        let service = sample_service();
1456
1457        let err = service
1458            .get_candles_proto(pb::GetCandlesRequest {
1459                symbol: "EURUSD".to_string(),
1460                timeframe: pb::Timeframe::Unspecified as i32,
1461                from_time: String::new(),
1462                to_time: String::new(),
1463                limit: 10,
1464            })
1465            .expect_err("timeframe should be rejected");
1466
1467        assert_eq!(err, OpenApiError::UnsupportedTimeframe(0));
1468    }
1469
1470    #[test]
1471    fn timestamp_validation_requires_utc() {
1472        let service = sample_service();
1473
1474        let err = service
1475            .get_candles_proto(pb::GetCandlesRequest {
1476                symbol: "EURUSD".to_string(),
1477                timeframe: pb::Timeframe::M1 as i32,
1478                from_time: "2026-05-26T12:00:00+03:00".to_string(),
1479                to_time: "2026-05-26T13:00:00Z".to_string(),
1480                limit: 10,
1481            })
1482            .expect_err("non-utc timestamp should fail");
1483
1484        assert_eq!(
1485            err,
1486            OpenApiError::InvalidUtcTimestamp {
1487                field: "from_time",
1488                value: "2026-05-26T12:00:00+03:00".to_string(),
1489            }
1490        );
1491    }
1492
1493    #[test]
1494    fn range_validation_requires_from_before_to() {
1495        let service = sample_service();
1496
1497        let err = service
1498            .get_candles_proto(pb::GetCandlesRequest {
1499                symbol: "EURUSD".to_string(),
1500                timeframe: pb::Timeframe::M1 as i32,
1501                from_time: "2026-05-26T13:00:00Z".to_string(),
1502                to_time: "2026-05-26T12:00:00Z".to_string(),
1503                limit: 10,
1504            })
1505            .expect_err("invalid range should fail");
1506
1507        assert_eq!(
1508            err,
1509            OpenApiError::InvalidTimeRange {
1510                from_time: "2026-05-26T13:00:00Z".to_string(),
1511                to_time: "2026-05-26T12:00:00Z".to_string(),
1512            }
1513        );
1514    }
1515
1516    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1517    async fn grpc_sdk_client_roundtrip_works() {
1518        let mut service = sample_service();
1519        service
1520            .register_user("bob", "pw", "ACC-002", d(250_000, 0))
1521            .expect("bob should be registered");
1522
1523        let server = OpenApiGrpcServer::new(service);
1524
1525        let listener = TcpListener::bind("127.0.0.1:0")
1526            .await
1527            .expect("listener should bind");
1528        let addr = listener.local_addr().expect("local addr should resolve");
1529        let incoming = TcpListenerStream::new(listener);
1530
1531        let server_task = tokio::spawn(async move {
1532            Server::builder()
1533                .add_service(server.into_tonic_service())
1534                .serve_with_incoming(incoming)
1535                .await
1536        });
1537
1538        let mut client = OpenApiSdkClient::connect(format!("http://{addr}"))
1539            .await
1540            .expect("client should connect");
1541
1542        let token = client
1543            .login("bob", "pw")
1544            .await
1545            .expect("login should succeed");
1546
1547        let quote = client
1548            .quote_volume("EURUSD", d(25, 2))
1549            .await
1550            .expect("quote should succeed");
1551        assert_eq!(quote.volume, d(25_000, 0));
1552
1553        let execution = client
1554            .place_market_order(token.clone(), "EURUSD", d(25, 2), OrderSide::Buy)
1555            .await
1556            .expect("order should execute");
1557        assert_eq!(execution.margin_used, d(250, 0));
1558
1559        let positions = client
1560            .fetch_open_positions(token.clone())
1561            .await
1562            .expect("positions should load");
1563        assert_eq!(positions.len(), 1);
1564        assert_eq!(positions[0].symbol, "EURUSD");
1565
1566        let candles = client
1567            .get_candles("EURUSD", Timeframe::M1, None, None, 5)
1568            .await
1569            .expect("candles should load");
1570        assert_eq!(candles.len(), 5);
1571
1572        let mut stream = client
1573            .stream_candles("EURUSD", Timeframe::M1, None, None, 3)
1574            .await
1575            .expect("stream should open");
1576        let mut received = 0;
1577        while let Some(item) = stream.next().await {
1578            let msg = item.expect("stream item should be valid");
1579            assert!(msg.candle.is_some());
1580            received += 1;
1581        }
1582        assert_eq!(received, 3);
1583
1584        let _server_time = client
1585            .get_server_time()
1586            .await
1587            .expect("server time should load");
1588
1589        let balance = client
1590            .fetch_balance(token.clone())
1591            .await
1592            .expect("balance should load");
1593        assert!(balance.free_margin < d(250_000, 0));
1594
1595        client.logout(token).await.expect("logout should succeed");
1596
1597        server_task.abort();
1598    }
1599}