ccxt-exchanges 0.1.5

Exchange implementations for CCXT Rust
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! Signed request builder for Bitget API.
//!
//! This module provides a builder pattern for creating authenticated Bitget API requests,
//! encapsulating the common signing workflow used across all authenticated endpoints.
//!
//! # Overview
//!
//! The `BitgetSignedRequestBuilder` eliminates code duplication by centralizing:
//! - Credential validation
//! - Millisecond timestamp generation
//! - Parameter signing with HMAC-SHA256
//! - Authentication header injection
//! - HTTP request execution
//!
//! # Example
//!
//! ```no_run
//! # use ccxt_exchanges::bitget::Bitget;
//! # use ccxt_exchanges::bitget::signed_request::HttpMethod;
//! # use ccxt_core::ExchangeConfig;
//! # async fn example() -> ccxt_core::Result<()> {
//! let bitget = Bitget::new(ExchangeConfig::default())?;
//!
//! // Simple GET request
//! let data = bitget.signed_request("/api/v2/spot/account/assets")
//!     .execute()
//!     .await?;
//!
//! // POST request with parameters
//! let data = bitget.signed_request("/api/v2/spot/trade/place-order")
//!     .method(HttpMethod::Post)
//!     .param("symbol", "BTCUSDT")
//!     .param("side", "buy")
//!     .execute()
//!     .await?;
//! # Ok(())
//! # }
//! ```

use super::Bitget;
use ccxt_core::{Error, ParseError, Result};
use reqwest::header::HeaderMap;
use serde_json::Value;
use std::collections::BTreeMap;

/// HTTP request methods supported by the signed request builder.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HttpMethod {
    /// GET request - parameters in query string
    #[default]
    Get,
    /// POST request - parameters in JSON body
    Post,
    /// DELETE request - parameters in JSON body
    Delete,
}

/// Builder for creating authenticated Bitget API requests.
///
/// This builder encapsulates the common signing workflow:
/// 1. Credential validation
/// 2. Millisecond timestamp generation
/// 3. Parameter signing with HMAC-SHA256
/// 4. Authentication header injection
/// 5. HTTP request execution
///
/// # Example
///
/// ```no_run
/// # use ccxt_exchanges::bitget::Bitget;
/// # use ccxt_exchanges::bitget::signed_request::HttpMethod;
/// # use ccxt_core::ExchangeConfig;
/// # async fn example() -> ccxt_core::Result<()> {
/// let bitget = Bitget::new(ExchangeConfig::default())?;
///
/// let data = bitget.signed_request("/api/v2/spot/account/assets")
///     .param("symbol", "BTCUSDT")
///     .optional_param("limit", Some(100))
///     .execute()
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct BitgetSignedRequestBuilder<'a> {
    /// Reference to the Bitget exchange instance
    bitget: &'a Bitget,
    /// Request parameters to be signed
    params: BTreeMap<String, String>,
    /// Request body for POST/DELETE requests
    body: Option<Value>,
    /// API endpoint path
    endpoint: String,
    /// HTTP method for the request
    method: HttpMethod,
}

impl<'a> BitgetSignedRequestBuilder<'a> {
    /// Creates a new signed request builder.
    ///
    /// # Arguments
    ///
    /// * `bitget` - Reference to the Bitget exchange instance
    /// * `endpoint` - API endpoint path (e.g., "/api/v2/spot/account/assets")
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_exchanges::bitget::signed_request::BitgetSignedRequestBuilder;
    /// # use ccxt_core::ExchangeConfig;
    /// let bitget = Bitget::new(ExchangeConfig::default()).unwrap();
    /// let builder = BitgetSignedRequestBuilder::new(&bitget, "/api/v2/spot/account/assets");
    /// ```
    pub fn new(bitget: &'a Bitget, endpoint: impl Into<String>) -> Self {
        Self {
            bitget,
            params: BTreeMap::new(),
            body: None,
            endpoint: endpoint.into(),
            method: HttpMethod::default(),
        }
    }

    /// Sets the HTTP method for the request.
    ///
    /// Default is GET.
    ///
    /// # Arguments
    ///
    /// * `method` - The HTTP method to use
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_exchanges::bitget::signed_request::HttpMethod;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let data = bitget.signed_request("/api/v2/spot/trade/place-order")
    ///     .method(HttpMethod::Post)
    ///     .param("symbol", "BTCUSDT")
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn method(mut self, method: HttpMethod) -> Self {
        self.method = method;
        self
    }

    /// Adds a required parameter.
    ///
    /// # Arguments
    ///
    /// * `key` - Parameter name
    /// * `value` - Parameter value (will be converted to string)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let data = bitget.signed_request("/api/v2/spot/trade/orders-history")
    ///     .param("symbol", "BTCUSDT")
    ///     .param("limit", 100)
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn param(mut self, key: impl Into<String>, value: impl ToString) -> Self {
        self.params.insert(key.into(), value.to_string());
        self
    }

    /// Adds an optional parameter (only if value is Some).
    ///
    /// # Arguments
    ///
    /// * `key` - Parameter name
    /// * `value` - Optional parameter value
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let since: Option<i64> = Some(1234567890000);
    /// let limit: Option<u32> = None;
    ///
    /// let data = bitget.signed_request("/api/v2/spot/trade/orders-history")
    ///     .param("symbol", "BTCUSDT")
    ///     .optional_param("after", since)
    ///     .optional_param("limit", limit)  // Won't be added since it's None
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn optional_param<T: ToString>(mut self, key: impl Into<String>, value: Option<T>) -> Self {
        if let Some(v) = value {
            self.params.insert(key.into(), v.to_string());
        }
        self
    }

    /// Adds multiple parameters from a BTreeMap.
    ///
    /// # Arguments
    ///
    /// * `params` - Map of parameter key-value pairs
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_core::ExchangeConfig;
    /// # use std::collections::BTreeMap;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let mut params = BTreeMap::new();
    /// params.insert("symbol".to_string(), "BTCUSDT".to_string());
    /// params.insert("side".to_string(), "buy".to_string());
    ///
    /// let data = bitget.signed_request("/api/v2/spot/trade/place-order")
    ///     .params(params)
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn params(mut self, params: BTreeMap<String, String>) -> Self {
        self.params.extend(params);
        self
    }

    /// Sets the request body for POST/DELETE requests.
    ///
    /// # Arguments
    ///
    /// * `body` - JSON value to use as request body
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_core::ExchangeConfig;
    /// # use serde_json::json;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let body = json!({
    ///     "symbol": "BTCUSDT",
    ///     "side": "buy",
    ///     "orderType": "limit"
    /// });
    ///
    /// let data = bitget.signed_request("/api/v2/spot/trade/place-order")
    ///     .method(ccxt_exchanges::bitget::signed_request::HttpMethod::Post)
    ///     .body(body)
    ///     .execute()
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn body(mut self, body: Value) -> Self {
        self.body = Some(body);
        self
    }

    /// Executes the signed request and returns the response.
    ///
    /// This method:
    /// 1. Validates that credentials are configured
    /// 2. Gets the current millisecond timestamp
    /// 3. Signs the request with HMAC-SHA256
    /// 4. Adds authentication headers
    /// 5. Executes the HTTP request
    ///
    /// # Returns
    ///
    /// Returns the raw `serde_json::Value` response for further parsing.
    ///
    /// # Errors
    ///
    /// - Returns authentication error if credentials are missing
    /// - Returns network error if the request fails
    /// - Returns parse error if response parsing fails
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use ccxt_exchanges::bitget::Bitget;
    /// # use ccxt_core::ExchangeConfig;
    /// # async fn example() -> ccxt_core::Result<()> {
    /// let bitget = Bitget::new(ExchangeConfig::default())?;
    /// let data = bitget.signed_request("/api/v2/spot/account/assets")
    ///     .execute()
    ///     .await?;
    /// println!("Response: {:?}", data);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn execute(self) -> Result<Value> {
        // Step 1: Validate credentials
        self.bitget.check_required_credentials()?;

        // Step 2: Get current millisecond timestamp
        let timestamp = (chrono::Utc::now().timestamp_millis()).to_string();

        // Step 3: Get auth and sign request
        let auth = self.bitget.get_auth()?;

        // Build the body string for signing
        let body_str = if let Some(ref body) = self.body {
            body.to_string()
        } else if self.method == HttpMethod::Get {
            String::new()
        } else {
            // For POST/DELETE without explicit body, use empty string
            String::new()
        };

        // Build the path with query string for GET requests
        let path = if self.method == HttpMethod::Get && !self.params.is_empty() {
            format!("{}?{}", self.endpoint, build_query_string(&self.params))
        } else {
            self.endpoint.clone()
        };

        // Sign the request
        let signature = auth.sign(&timestamp, &method_to_string(self.method), &path, &body_str);

        // Step 4: Add authentication headers
        let mut headers = HeaderMap::new();
        auth.add_auth_headers(&mut headers, &timestamp, &signature);

        // Step 5: Execute HTTP request based on method
        let urls = self.bitget.urls();
        let full_url = format!("{}{}", urls.rest, self.endpoint);

        match self.method {
            HttpMethod::Get => {
                // Build query string for GET requests
                let query_string = build_query_string(&self.params);
                let url = if query_string.is_empty() {
                    full_url
                } else {
                    format!("{}?{}", full_url, query_string)
                };
                self.bitget
                    .base()
                    .http_client
                    .get(&url, Some(headers))
                    .await
            }
            HttpMethod::Post => {
                // Use explicit body if provided, otherwise use params as JSON
                let body = if let Some(b) = self.body {
                    b
                } else {
                    serde_json::to_value(&self.params).map_err(|e| {
                        Error::from(ParseError::invalid_format(
                            "data",
                            format!("Failed to serialize request body: {}", e),
                        ))
                    })?
                };
                self.bitget
                    .base()
                    .http_client
                    .post(&full_url, Some(headers), Some(body))
                    .await
            }
            HttpMethod::Delete => {
                // Use explicit body if provided, otherwise use params as JSON
                let body = if let Some(b) = self.body {
                    b
                } else {
                    serde_json::to_value(&self.params).map_err(|e| {
                        Error::from(ParseError::invalid_format(
                            "data",
                            format!("Failed to serialize request body: {}", e),
                        ))
                    })?
                };
                self.bitget
                    .base()
                    .http_client
                    .delete(&full_url, Some(headers), Some(body))
                    .await
            }
        }
    }
}

/// Converts HttpMethod to string representation.
fn method_to_string(method: HttpMethod) -> String {
    match method {
        HttpMethod::Get => "GET".to_string(),
        HttpMethod::Post => "POST".to_string(),
        HttpMethod::Delete => "DELETE".to_string(),
    }
}

/// Builds a URL-encoded query string from parameters.
///
/// Parameters are sorted alphabetically by key (due to BTreeMap ordering).
fn build_query_string(params: &BTreeMap<String, String>) -> String {
    params
        .iter()
        .map(|(k, v)| format!("{}={}", k, v))
        .collect::<Vec<_>>()
        .join("&")
}

#[cfg(test)]
mod tests {
    #![allow(clippy::disallowed_methods)]
    use super::*;
    use ccxt_core::ExchangeConfig;

    #[test]
    fn test_http_method_default() {
        assert_eq!(HttpMethod::default(), HttpMethod::Get);
    }

    #[test]
    fn test_builder_construction() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/api/v2/spot/account/assets");

        assert_eq!(builder.endpoint, "/api/v2/spot/account/assets");
        assert_eq!(builder.method, HttpMethod::Get);
        assert!(builder.params.is_empty());
        assert!(builder.body.is_none());
    }

    #[test]
    fn test_builder_method_chaining() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/api/v2/spot/trade/place-order")
            .method(HttpMethod::Post)
            .param("symbol", "BTCUSDT")
            .param("side", "buy");

        assert_eq!(builder.method, HttpMethod::Post);
        assert_eq!(builder.params.get("symbol"), Some(&"BTCUSDT".to_string()));
        assert_eq!(builder.params.get("side"), Some(&"buy".to_string()));
    }

    #[test]
    fn test_builder_param() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/test")
            .param("string_param", "value")
            .param("int_param", 123)
            .param("float_param", 45.67);

        assert_eq!(
            builder.params.get("string_param"),
            Some(&"value".to_string())
        );
        assert_eq!(builder.params.get("int_param"), Some(&"123".to_string()));
        assert_eq!(
            builder.params.get("float_param"),
            Some(&"45.67".to_string())
        );
    }

    #[test]
    fn test_builder_optional_param_some() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/test")
            .optional_param("limit", Some(100u32))
            .optional_param("after", Some(1234567890i64));

        assert_eq!(builder.params.get("limit"), Some(&"100".to_string()));
        assert_eq!(builder.params.get("after"), Some(&"1234567890".to_string()));
    }

    #[test]
    fn test_builder_optional_param_none() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let none_value: Option<u32> = None;
        let builder =
            BitgetSignedRequestBuilder::new(&bitget, "/test").optional_param("limit", none_value);

        assert!(builder.params.get("limit").is_none());
    }

    #[test]
    fn test_builder_params_bulk() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let mut params = BTreeMap::new();
        params.insert("symbol".to_string(), "BTCUSDT".to_string());
        params.insert("side".to_string(), "buy".to_string());

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/test").params(params);

        assert_eq!(builder.params.get("symbol"), Some(&"BTCUSDT".to_string()));
        assert_eq!(builder.params.get("side"), Some(&"buy".to_string()));
    }

    #[test]
    fn test_builder_body() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        let body = serde_json::json!({
            "symbol": "BTCUSDT",
            "side": "buy"
        });

        let builder = BitgetSignedRequestBuilder::new(&bitget, "/test").body(body.clone());

        assert_eq!(builder.body, Some(body));
    }

    #[test]
    fn test_builder_all_http_methods() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        // Test all HTTP methods can be set
        let get_builder = BitgetSignedRequestBuilder::new(&bitget, "/test").method(HttpMethod::Get);
        assert_eq!(get_builder.method, HttpMethod::Get);

        let post_builder =
            BitgetSignedRequestBuilder::new(&bitget, "/test").method(HttpMethod::Post);
        assert_eq!(post_builder.method, HttpMethod::Post);

        let delete_builder =
            BitgetSignedRequestBuilder::new(&bitget, "/test").method(HttpMethod::Delete);
        assert_eq!(delete_builder.method, HttpMethod::Delete);
    }

    #[test]
    fn test_builder_parameter_ordering() {
        let config = ExchangeConfig::default();
        let bitget = Bitget::new(config).unwrap();

        // Add parameters in non-alphabetical order
        let builder = BitgetSignedRequestBuilder::new(&bitget, "/test")
            .param("zebra", "z")
            .param("apple", "a")
            .param("mango", "m");

        // BTreeMap should maintain alphabetical order
        let keys: Vec<_> = builder.params.keys().collect();
        assert_eq!(keys, vec!["apple", "mango", "zebra"]);
    }

    #[test]
    fn test_method_to_string() {
        assert_eq!(method_to_string(HttpMethod::Get), "GET");
        assert_eq!(method_to_string(HttpMethod::Post), "POST");
        assert_eq!(method_to_string(HttpMethod::Delete), "DELETE");
    }

    #[test]
    fn test_build_query_string() {
        let mut params = BTreeMap::new();
        params.insert("symbol".to_string(), "BTCUSDT".to_string());
        params.insert("side".to_string(), "buy".to_string());
        params.insert("amount".to_string(), "1.5".to_string());

        let query = build_query_string(&params);

        // BTreeMap maintains alphabetical order
        assert_eq!(query, "amount=1.5&side=buy&symbol=BTCUSDT");
    }

    #[test]
    fn test_build_query_string_empty() {
        let params = BTreeMap::new();
        let query = build_query_string(&params);
        assert!(query.is_empty());
    }
}

#[cfg(test)]
mod property_tests {
    use super::*;
    use ccxt_core::ExchangeConfig;
    use proptest::prelude::*;

    // Strategy to generate valid parameter keys (alphanumeric, non-empty)
    fn param_key_strategy() -> impl Strategy<Value = String> {
        "[a-zA-Z][a-zA-Z0-9]{0,19}".prop_map(|s| s)
    }

    // Strategy to generate valid parameter values
    fn param_value_strategy() -> impl Strategy<Value = String> {
        "[a-zA-Z0-9._-]{1,50}".prop_map(|s| s)
    }

    // Strategy to generate a BTreeMap of parameters
    fn params_strategy() -> impl Strategy<Value = BTreeMap<String, String>> {
        proptest::collection::btree_map(param_key_strategy(), param_value_strategy(), 0..10)
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// **Feature: exchange-signed-request-refactor, Property 1: Fluent API Method Chaining**
        ///
        /// *For any* sequence of builder method calls (param, optional_param, params, method),
        /// each method SHALL return Self allowing further method chaining, and the final execute()
        /// call SHALL consume the builder.
        ///
        /// **Validates: Requirements 2.1**
        #[test]
        fn prop_fluent_api_method_chaining(
            params in params_strategy(),
            other_key in param_key_strategy(),
            other_value in param_value_strategy()
        ) {
            let config = ExchangeConfig::default();
            let bitget = Bitget::new(config).unwrap();

            // Build with method chaining
            let builder = BitgetSignedRequestBuilder::new(&bitget, "/test")
                .method(HttpMethod::Post)
                .params(params.clone())
                .param(&other_key, &other_value)
                .optional_param("optional", Some("value"));

            // Verify all parameters are present
            for (key, value) in &params {
                prop_assert_eq!(builder.params.get(key), Some(value));
            }
            prop_assert_eq!(builder.params.get(&other_key), Some(&other_value));
            prop_assert_eq!(builder.params.get("optional"), Some(&"value".to_string()));
            prop_assert_eq!(builder.method, HttpMethod::Post);
        }

        /// **Feature: exchange-signed-request-refactor, Property 5: Parameter Methods Correctly Populate Params**
        ///
        /// *For any* combination of param(), optional_param(), and params() calls:
        /// - param(key, value) SHALL always add the key-value pair
        /// - optional_param(key, Some(value)) SHALL add the key-value pair
        /// - optional_param(key, None) SHALL NOT add any key-value pair
        /// - params(map) SHALL add all key-value pairs from the map
        ///
        /// **Validates: Requirements 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7**
        #[test]
        fn prop_optional_param_conditional_addition(
            key in param_key_strategy(),
            value in proptest::option::of(param_value_strategy()),
            other_key in param_key_strategy(),
            other_value in param_value_strategy()
        ) {
            let config = ExchangeConfig::default();
            let bitget = Bitget::new(config).unwrap();

            // Build with optional parameter
            let builder = BitgetSignedRequestBuilder::new(&bitget, "/test")
                .param(&other_key, &other_value)
                .optional_param(&key, value.clone());

            // Property: If value is Some, parameter should be present with correct value
            // If value is None, parameter should NOT be present
            match value {
                Some(v) => {
                    prop_assert!(
                        builder.params.contains_key(&key),
                        "Parameter {} should be present when value is Some",
                        key
                    );
                    prop_assert_eq!(
                        builder.params.get(&key).unwrap(),
                        &v,
                        "Parameter {} should have correct value",
                        key
                    );
                }
                None => {
                    // Only check if key is different from other_key
                    if key != other_key {
                        prop_assert!(
                            !builder.params.contains_key(&key),
                            "Parameter {} should NOT be present when value is None",
                            key
                        );
                    }
                }
            }

            // Property: Other parameters should always be present
            prop_assert!(
                builder.params.contains_key(&other_key),
                "Other parameter {} should always be present",
                other_key
            );
            prop_assert_eq!(
                builder.params.get(&other_key).unwrap(),
                &other_value,
                "Other parameter {} should have correct value",
                other_key
            );
        }
    }
}