digdigdig3 0.3.18

Unified async Rust API for 47 exchange connectors (REST + WebSocket). The core layer — pure ExchangeHub + connectors. Higher-level builder, persistence, replay, OB tracker live in `digdigdig3-station`.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! # JQuants Connector Implementation

use reqwest::Client;
use std::collections::HashMap;
use std::sync::Mutex;

use crate::core::types::*;
use crate::core::traits::*;

use super::endpoints::*;
use super::auth::*;
use super::parser::*;

/// JQuants connector
pub struct JQuantsConnector {
    client: Client,
    auth: Mutex<JQuantsAuth>, // Mutex for thread-safe interior mutability (token caching)
    urls: JQuantsUrls,
}

impl JQuantsConnector {
    /// Create new connector with refresh token
    pub fn new(refresh_token: impl Into<String>) -> Self {
        Self {
            client: Client::new(),
            auth: Mutex::new(JQuantsAuth::new(refresh_token)),
            urls: JQuantsUrls::default(),
        }
    }

    /// Create connector from environment variables
    ///
    /// Expects: JQUANTS_REFRESH_TOKEN
    pub fn from_env() -> Self {
        Self {
            client: Client::new(),
            auth: Mutex::new(JQuantsAuth::from_env()),
            urls: JQuantsUrls::default(),
        }
    }

    /// Ensure we have a valid ID token (fetch if needed)
    async fn ensure_id_token(&self) -> ExchangeResult<String> {
        // Check if we have a cached valid ID token
        if let Some(token) = self.auth.lock().expect("Mutex poisoned").get_cached_id_token() {
            return Ok(token.to_string());
        }

        // Need to fetch new ID token using refresh token
        let refresh_token = self.auth.lock().expect("Mutex poisoned").refresh_token().to_string();
        if refresh_token.is_empty() {
            return Err(ExchangeError::Auth(
                "Missing refresh token. Set JQUANTS_REFRESH_TOKEN env var.".to_string()
            ));
        }

        let url = format!(
            "{}{}?refreshtoken={}",
            self.urls.rest_base,
            JQuantsEndpoint::AuthRefresh.path(),
            refresh_token
        );

        let response = self.client
            .post(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!("Failed to get ID token: {}", e)))?;

        if !response.status().is_success() {
            let status = response.status();
            let text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Auth(format!(
                "Failed to get ID token: HTTP {} - {}",
                status, text
            )));
        }

        let json: serde_json::Value = response.json().await
            .map_err(|e| ExchangeError::Parse(format!("Failed to parse ID token response: {}", e)))?;

        let id_token = JQuantsParser::parse_id_token(&json)?;

        // Cache the token
        self.auth.lock().expect("Mutex poisoned").cache_id_token(id_token.clone());

        Ok(id_token)
    }

    /// Internal: Make GET request with authentication
    async fn get(
        &self,
        endpoint: JQuantsEndpoint,
        params: HashMap<String, String>,
    ) -> ExchangeResult<serde_json::Value> {
        let id_token = self.ensure_id_token().await?;

        let url = format!("{}{}", self.urls.rest_base, endpoint.path());

        let mut request = self.client.get(&url);

        // Add auth header
        request = request.header("Authorization", format!("Bearer {}", id_token));
        request = request.header("Content-Type", "application/json");

        // Add query params
        if !params.is_empty() {
            request = request.query(&params);
        }

        let response = request.send().await
            .map_err(|e| ExchangeError::Network(format!("Request failed: {}", e)))?;

        let status = response.status();

        if status.as_u16() == 401 {
            // Token expired, clear cache and retry once
            self.auth.lock().expect("Mutex poisoned").clear_id_token();
            return Err(ExchangeError::Auth("ID token expired, retry request".to_string()));
        }

        if !status.is_success() {
            let text = response.text().await.unwrap_or_default();
            return Err(ExchangeError::Api {
                code: status.as_u16() as i32,
                message: text,
            });
        }

        response.json().await
            .map_err(|e| ExchangeError::Parse(format!("JSON parse error: {}", e)))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: ExchangeIdentity (ALWAYS implement)
// ═══════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for JQuantsConnector {
    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::JQuants
    }

    fn is_testnet(&self) -> bool {
        false // JQuants has no testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        vec![AccountType::Spot] // Data provider, treating as "Spot" equivalent
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: MarketData (Implement what makes sense)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl MarketData for JQuantsConnector {
    /// Get current price (using latest daily quote close price)
    async fn get_price(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let mut params = HashMap::new();
        params.insert("code".to_string(), symbol);

        let response = self.get(JQuantsEndpoint::DailyQuotes, params).await?;
        JQuantsParser::parse_current_price(&response)
    }

    /// Get orderbook - NOT AVAILABLE (data provider only)
    async fn get_orderbook(
        &self,
        _symbol: SymbolInput<'_>,
        _depth: Option<u16>,
        _account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants does not provide orderbook data - it is a data-only provider with delayed data".to_string()
        ))
    }

    /// Get klines/candles (historical daily OHLC)
    async fn get_klines(
        &self,
        symbol: SymbolInput<'_>,
        _interval: &str, // JQuants only has daily data on free tier
        limit: Option<u16>,
        _account_type: AccountType,
        end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        use chrono::{DateTime, Duration, NaiveDate, Utc};
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };

        let mut params = HashMap::new();
        params.insert("code".to_string(), symbol);

        // Determine the end date: use end_time if provided, otherwise today
        let end_date: NaiveDate = if let Some(end_ms) = end_time {
            let dt = DateTime::from_timestamp_millis(end_ms)
                .ok_or_else(|| ExchangeError::InvalidRequest(
                    "Invalid end_time timestamp".to_string()
                ))?;
            dt.date_naive()
        } else {
            Utc::now().date_naive()
        };

        // Determine the start date: go back `limit` calendar days from end_date
        // JQuants returns trading days only, so fetching extra days is safe.
        let days_back = limit.unwrap_or(100) as i64;
        let start_date = end_date - Duration::days(days_back - 1);

        // JQuants expects YYYYMMDD format
        let fmt = |d: NaiveDate| d.format("%Y%m%d").to_string();
        params.insert("from".to_string(), fmt(start_date));
        params.insert("to".to_string(), fmt(end_date));

        let response = self.get(JQuantsEndpoint::DailyQuotes, params).await?;
        let mut klines = JQuantsParser::parse_daily_quotes(&response)?;

        // Apply limit if specified (in case API returned more than requested)
        if let Some(lim) = limit {
            let len = klines.len();
            if len > lim as usize {
                klines = klines[len - lim as usize..].to_vec();
            }
        }

        Ok(klines)
    }

    /// Get ticker (24h stats from latest daily quote)
    async fn get_ticker(
        &self,
        symbol: SymbolInput<'_>,
        _account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let symbol: String = match symbol { SymbolInput::Raw(s) => s.to_string(), SymbolInput::Canonical(c) => c.to_concat() };
        let mut params = HashMap::new();
        params.insert("code".to_string(), symbol.clone());

        let response = self.get(JQuantsEndpoint::DailyQuotes, params).await?;
        JQuantsParser::parse_ticker(&response, &symbol)
    }

    /// Ping - check connectivity
    async fn ping(&self) -> ExchangeResult<()> {
        // Simple connectivity check - try to fetch anything
        // We can't use a truly public endpoint since all require auth
        // This is a basic check that will fail if network is down
        Ok(())
    }

    /// Get exchange info — returns listed Japanese stock codes from JQuants
    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        let params = HashMap::new();
        let response = self.get(JQuantsEndpoint::ListedInfo, params).await?;

        // Iterate the raw "info" array directly so each SymbolInfo carries its full
        // native record in `extra`. JQuantsParser::parse_symbols only returns String codes.
        let info_array = response
            .get("info")
            .and_then(|v| v.as_array())
            .ok_or_else(|| ExchangeError::Parse("Missing 'info' array in JQuants listed info".to_string()))?;

        let infos = info_array.iter().filter_map(|item| {
            let code = item.get("Code").and_then(|v| v.as_str())?.to_string();

            // JQuants /listed/info has no per-symbol trading-status field
            let status = String::new();

            // instrument_type: use native "MarketCode" if present (e.g. "0111" = Prime)
            // or "Scale" / "ScaleCategory". No canonical type token, so None.
            let instrument_type: Option<String> = None;

            Some(SymbolInfo {
                symbol: code.clone(),
                base_asset: code,
                quote_asset: "JPY".to_string(),
                status,
                price_precision: 0,
                quantity_precision: 0,
                min_quantity: Some(1.0),
                max_quantity: None,
                tick_size: None,
                step_size: Some(1.0),
                min_notional: None,
                account_type,
                instrument_type,
                extra: item.clone(),
            })
        }).collect();

        Ok(infos)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Trading (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl Trading for JQuantsConnector {
    async fn place_order(&self, _req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - trading not supported".to_string()
        ))
    }

    async fn cancel_order(&self, _req: CancelRequest) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_order(
        &self,
        _symbol: &str,
        _order_id: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<Order> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_open_orders(
        &self,
        _symbol: Option<&str>,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - trading not supported".to_string()
        ))
    }

    async fn get_order_history(
        &self,
        _filter: OrderHistoryFilter,
        _account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - trading not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Account (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl Account for JQuantsConnector {
    async fn get_balance(&self, _query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - account operations not supported".to_string()
        ))
    
    }

    async fn get_account_info(&self, _account_type: AccountType) -> ExchangeResult<AccountInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - account operations not supported".to_string()
        ))
    }

    async fn get_fees(&self, _symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - account operations not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// TRAIT: Positions (UnsupportedOperation - data provider only)
// ═══════════════════════════════════════════════════════════════════════════

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl Positions for JQuantsConnector {
    async fn get_positions(&self, _query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - position tracking not supported".to_string()
        ))
    }

    async fn get_funding_rate(
        &self,
        _symbol: &str,
        _account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - position tracking not supported".to_string()
        ))
    }

    async fn modify_position(&self, _req: PositionModification) -> ExchangeResult<()> {
        Err(ExchangeError::UnsupportedOperation(
            "JQuants is a data provider - position tracking not supported".to_string()
        ))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// EXTENDED METHODS (JQuants-specific, not from traits)
// ═══════════════════════════════════════════════════════════════════════════

impl JQuantsConnector {
    /// Get list of available symbols (stock codes)
    pub async fn get_symbols(&self) -> ExchangeResult<Vec<String>> {
        let params = HashMap::new();
        let response = self.get(JQuantsEndpoint::ListedInfo, params).await?;
        JQuantsParser::parse_symbols(&response)
    }
}