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