Skip to main content

ccxt_common/
params.rs

1//! Exchange-specific extra parameters, without exposing [`Value`].
2//!
3//! Every unified method ends with a `params` argument carrying the knobs a
4//! particular venue understands (`timeInForce`, `reduceOnly`, `marginMode`, …).
5//! The typed layer takes a [`Params`] here rather than a raw [`Value`], so a
6//! caller only ever handles Rust primitives:
7//!
8//! ```ignore
9//! // nothing extra
10//! ex.create_order("BTC/USDT", "limit", "buy", 0.01, Some(50_000.0), Params::none()).await?;
11//!
12//! // a couple of venue-specific knobs
13//! ex.create_order("BTC/USDT", "limit", "buy", 0.01, Some(50_000.0),
14//!     Params::new()
15//!         .with_str("timeInForce", "GTC")
16//!         .with_bool("postOnly", true)
17//!         .with_float("stopPrice", 49_000.0),
18//! ).await?;
19//! ```
20//!
21//! Values keep insertion order, matching the JS object ordering the transpiled
22//! code and every signing routine expect.
23use crate::Value;
24use indexmap::IndexMap;
25
26/// Extra exchange-specific parameters for a unified call.
27///
28/// Build with [`Params::new`] and the `with_*` setters, or [`Params::none`]
29/// when a method needs no extras. Cheap to clone and `Default`-constructible.
30#[derive(Clone, Debug, Default, PartialEq)]
31pub struct Params {
32    entries: IndexMap<String, Value>,
33}
34
35impl Params {
36    /// An empty parameter set.
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// An empty parameter set — reads better at a call site than
42    /// `Params::new()` when you are explicitly passing "no extras".
43    pub fn none() -> Self {
44        Self::default()
45    }
46
47    /// `true` when nothing has been set.
48    pub fn is_empty(&self) -> bool {
49        self.entries.is_empty()
50    }
51
52    /// Number of parameters set.
53    pub fn len(&self) -> usize {
54        self.entries.len()
55    }
56
57    /// Set a string parameter.
58    pub fn with_str(mut self, key: &str, value: &str) -> Self {
59        self.entries.insert(key.to_string(), Value::Str(value.to_string().into()));
60        self
61    }
62
63    /// Set an integer parameter.
64    pub fn with_int(mut self, key: &str, value: i64) -> Self {
65        self.entries.insert(key.to_string(), Value::Int(value));
66        self
67    }
68
69    /// Set a floating-point parameter.
70    pub fn with_float(mut self, key: &str, value: f64) -> Self {
71        self.entries.insert(key.to_string(), Value::Float(value));
72        self
73    }
74
75    /// Set a boolean parameter.
76    pub fn with_bool(mut self, key: &str, value: bool) -> Self {
77        self.entries.insert(key.to_string(), Value::Bool(value));
78        self
79    }
80
81    /// Set a list-of-strings parameter (e.g. a batch of client order ids).
82    pub fn with_strs(mut self, key: &str, values: &[&str]) -> Self {
83        let list: Vec<Value> = values.iter().map(|s| Value::Str((*s).to_string().into())).collect();
84        self.entries.insert(key.to_string(), Value::Arr(std::sync::Arc::new(list)));
85        self
86    }
87
88    /// Set a nested parameter from a JSON literal, for the rare venue that
89    /// wants a structured object. Invalid JSON is stored as a plain string.
90    pub fn with_json(mut self, key: &str, json: &str) -> Self {
91        let parsed = crate::runtime::json_parse(&Value::Str(json.to_string().into()));
92        let v = if matches!(parsed, Value::Null) { Value::Str(json.to_string().into()) } else { parsed };
93        self.entries.insert(key.to_string(), v);
94        self
95    }
96
97    /// Set a nested object from another `Params`. Calling this twice with the
98    /// same key MERGES — the second call adds to the object rather than
99    /// replacing it.
100    pub fn with_params(mut self, key: &str, value: Params) -> Self {
101        let mut base = match self.entries.get(key) {
102            Some(Value::Dict(d)) => (**d).clone(),
103            _ => IndexMap::new(),
104        };
105        deep_merge(&mut base, value.into_entries());
106        // `insert` on an existing key keeps its original position.
107        self.entries.insert(key.to_string(), Value::Dict(std::sync::Arc::new(base)));
108        self
109    }
110
111    /// The entries, for callers that need to embed this object somewhere.
112    pub(crate) fn into_entries(self) -> IndexMap<String, Value> {
113        self.entries
114    }
115
116    /// Like [`Params::into_value`] but an empty set stays an empty object
117    /// rather than collapsing to `Value::Null` — used when nesting, where the
118    /// key should still exist.
119    pub fn into_value_object(self) -> Value {
120        Value::Dict(std::sync::Arc::new(self.entries))
121    }
122
123    /// Lower to the dynamic representation the transpiled core consumes.
124    /// An empty set becomes `Value::Null`, which every unified method treats
125    /// as "no extra params".
126    pub fn into_value(self) -> Value {
127        if self.entries.is_empty() {
128            return Value::Null;
129        }
130        Value::Map(self.entries)
131    }
132}
133
134impl From<Params> for Value {
135    fn from(p: Params) -> Value {
136        p.into_value()
137    }
138}
139
140/// Back-compat: existing call sites that already hold a `Value` (including
141/// `Value::Null`) keep working without a conversion at the call site.
142impl From<Value> for Params {
143    fn from(v: Value) -> Params {
144        match v {
145            Value::Dict(entries) => Params {
146                entries: std::sync::Arc::try_unwrap(entries).unwrap_or_else(|a| (*a).clone()),
147            },
148            Value::Null => Params::default(),
149            // Anything else is not a parameter object; treat it as no params
150            // rather than silently corrupting the request.
151            _ => Params::default(),
152        }
153    }
154}
155
156/// `()` reads as "no extra params" at a call site.
157impl From<()> for Params {
158    fn from(_: ()) -> Params {
159        Params::default()
160    }
161}
162
163impl<const N: usize> From<[(&str, &str); N]> for Params {
164    fn from(pairs: [(&str, &str); N]) -> Params {
165        let mut p = Params::new();
166        for (k, v) in pairs {
167            p = p.with_str(k, v);
168        }
169        p
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn empty_lowers_to_null() {
179        assert!(matches!(Params::none().into_value(), Value::Null));
180        assert!(Params::new().is_empty());
181    }
182
183    #[test]
184    fn preserves_insertion_order_and_types() {
185        let v = Params::new()
186            .with_str("timeInForce", "GTC")
187            .with_bool("postOnly", true)
188            .with_float("stopPrice", 49_000.0)
189            .with_int("recvWindow", 5_000)
190            .into_value();
191        let map = match &v { Value::Dict(m) => m, _ => panic!("expected a map") };
192        let keys: Vec<&str> = map.keys().map(|k| k.as_str()).collect();
193        assert_eq!(keys, ["timeInForce", "postOnly", "stopPrice", "recvWindow"]);
194        assert_eq!(map["postOnly"], Value::Bool(true));
195        assert_eq!(map["recvWindow"], Value::Int(5_000));
196    }
197
198    #[test]
199    fn round_trips_through_value() {
200        let p = Params::new().with_str("a", "1").with_int("b", 2);
201        let back: Params = Params::from(p.clone().into_value());
202        assert_eq!(p, back);
203    }
204
205    #[test]
206    fn value_null_and_unit_are_empty() {
207        assert!(Params::from(Value::Null).is_empty());
208        assert!(Params::from(()).is_empty());
209    }
210
211    #[test]
212    fn array_literal_shorthand() {
213        let p: Params = [("timeInForce", "IOC"), ("newClientOrderId", "x1")].into();
214        assert_eq!(p.len(), 2);
215    }
216}
217
218/// Constructor configuration for an exchange, without exposing [`Value`].
219///
220/// ```ignore
221/// let ex = Binance::with_config(
222///     Config::new()
223///         .api_key(&key)
224///         .secret(&secret)
225///         .sandbox(true)
226///         .option_strs("fetchMarkets.types", &["spot"]),
227/// );
228/// ```
229///
230/// `options` nests exactly the way it does in every other ccxt binding. What
231/// the manual writes as
232///
233/// ```text
234/// { "options": { "fetchMarkets": { "types": ["spot"] } } }
235/// ```
236///
237/// is built with [`Config::option`] and a nested [`Params`]:
238///
239/// ```ignore
240/// Config::new().option("fetchMarkets", Params::new().with_strs("types", &["spot"]))
241/// ```
242///
243/// Use [`Config::option_str`] and friends for a flat key
244/// (`options: { defaultType: "swap" }`), or [`Config::options`] to hand over
245/// the whole block at once.
246#[derive(Clone, Debug, Default, PartialEq)]
247pub struct Config {
248    top: IndexMap<String, Value>,
249    options: IndexMap<String, Value>,
250}
251
252impl Config {
253    pub fn new() -> Self {
254        Self::default()
255    }
256
257    /// No configuration — same as `Config::new()`, clearer at a call site.
258    pub fn none() -> Self {
259        Self::default()
260    }
261
262    pub fn api_key(self, v: &str) -> Self { self.set_str("apiKey", v) }
263    pub fn secret(self, v: &str) -> Self { self.set_str("secret", v) }
264    pub fn password(self, v: &str) -> Self { self.set_str("password", v) }
265    pub fn uid(self, v: &str) -> Self { self.set_str("uid", v) }
266    pub fn wallet_address(self, v: &str) -> Self { self.set_str("walletAddress", v) }
267    pub fn private_key(self, v: &str) -> Self { self.set_str("privateKey", v) }
268    pub fn token(self, v: &str) -> Self { self.set_str("token", v) }
269
270    /// Route to the venue's testnet / demo endpoints.
271    pub fn sandbox(self, on: bool) -> Self { self.option_bool("sandbox", on) }
272    /// Client-side rate limiting (on by default in ccxt).
273    pub fn enable_rate_limit(self, on: bool) -> Self { self.set_bool("enableRateLimit", on) }
274    /// Milliseconds per rate-limit token.
275    pub fn rate_limit_ms(self, ms: i64) -> Self { self.set_int("rateLimit", ms) }
276    /// Request timeout in milliseconds.
277    pub fn timeout_ms(self, ms: i64) -> Self { self.set_int("timeout", ms) }
278    /// Log every request and response.
279    pub fn verbose(self, on: bool) -> Self { self.set_bool("verbose", on) }
280
281    /// Set an arbitrary top-level property.
282    pub fn set_str(mut self, key: &str, v: &str) -> Self {
283        self.top.insert(key.to_string(), Value::Str(v.to_string().into()));
284        self
285    }
286    pub fn set_int(mut self, key: &str, v: i64) -> Self {
287        self.top.insert(key.to_string(), Value::Int(v));
288        self
289    }
290    pub fn set_float(mut self, key: &str, v: f64) -> Self {
291        self.top.insert(key.to_string(), Value::Float(v));
292        self
293    }
294    pub fn set_bool(mut self, key: &str, v: bool) -> Self {
295        self.top.insert(key.to_string(), Value::Bool(v));
296        self
297    }
298
299    /// Merge a whole `options` block in — the closest match to passing an
300    /// options dict wholesale in the other language bindings. Deep-merges, so
301    /// it composes with anything already set (`sandbox`, earlier `option`
302    /// calls) instead of discarding it.
303    pub fn options(mut self, options: Params) -> Self {
304        deep_merge(&mut self.options, options.into_entries());
305        self
306    }
307
308    /// Set one nested object under `options`, e.g.
309    /// `option("fetchMarkets", Params::new().with_strs("types", &["spot"]))`
310    /// for `options: { fetchMarkets: { types: ["spot"] } }`.
311    ///
312    /// Calling it twice with the same key MERGES the two objects, so nested
313    /// options can be built up across several calls.
314    pub fn option(mut self, key: &str, value: Params) -> Self {
315        let mut base = match self.options.get(key) {
316            Some(Value::Dict(d)) => (**d).clone(),
317            _ => IndexMap::new(),
318        };
319        deep_merge(&mut base, value.into_entries());
320        self.options.insert(key.to_string(), Value::Dict(std::sync::Arc::new(base)));
321        self
322    }
323
324    /// Set a flat entry under `options`. The key is taken literally.
325    pub fn option_str(self, key: &str, v: &str) -> Self {
326        self.option_value(key, Value::Str(v.to_string().into()))
327    }
328    pub fn option_int(self, key: &str, v: i64) -> Self {
329        self.option_value(key, Value::Int(v))
330    }
331    pub fn option_float(self, key: &str, v: f64) -> Self {
332        self.option_value(key, Value::Float(v))
333    }
334    pub fn option_bool(self, key: &str, v: bool) -> Self {
335        self.option_value(key, Value::Bool(v))
336    }
337    pub fn option_strs(self, key: &str, values: &[&str]) -> Self {
338        let list: Vec<Value> = values.iter().map(|s| Value::Str((*s).to_string().into())).collect();
339        self.option_value(key, Value::Arr(std::sync::Arc::new(list)))
340    }
341
342    fn option_value(mut self, key: &str, v: Value) -> Self {
343        self.options.insert(key.to_string(), v);
344        self
345    }
346
347    /// Lower to the dynamic representation the transpiled core consumes.
348    pub fn into_value(self) -> Value {
349        let mut top = self.top;
350        if !self.options.is_empty() {
351            // Merge into any `options` already set through `set_*`.
352            let merged = match top.shift_remove("options") {
353                Some(Value::Dict(existing)) => {
354                    let mut m = (*existing).clone();
355                    for (k, v) in self.options { m.insert(k, v); }
356                    m
357                }
358                _ => self.options,
359            };
360            top.insert("options".to_string(), Value::Dict(std::sync::Arc::new(merged)));
361        }
362        if top.is_empty() { Value::Null } else { Value::Dict(std::sync::Arc::new(top)) }
363    }
364
365    /// `Some(value)` for the generated `new(Option<Value>)` constructors.
366    pub fn into_option(self) -> Option<Value> {
367        match self.into_value() {
368            Value::Null => None,
369            v => Some(v),
370        }
371    }
372}
373
374/// Recursive merge, mirroring ccxt's `deepExtend`: nested objects combine,
375/// anything else is overwritten by the incoming value.
376fn deep_merge(into: &mut IndexMap<String, Value>, from: IndexMap<String, Value>) {
377    for (k, v) in from {
378        let merged = match (into.get(&k), &v) {
379            (Some(Value::Dict(a)), Value::Dict(b)) => {
380                let mut m = (**a).clone();
381                deep_merge(&mut m, (**b).clone());
382                Value::Dict(std::sync::Arc::new(m))
383            }
384            _ => v,
385        };
386        into.insert(k, merged);
387    }
388}
389
390impl From<Config> for Value {
391    fn from(c: Config) -> Value { c.into_value() }
392}
393
394impl From<Config> for Option<Value> {
395    fn from(c: Config) -> Option<Value> { c.into_option() }
396}
397
398#[cfg(test)]
399mod config_tests {
400    use super::*;
401
402    fn dict(v: &Value) -> IndexMap<String, Value> {
403        match v { Value::Dict(d) => (**d).clone(), other => panic!("expected a dict, got {other:?}") }
404    }
405
406    #[test]
407    fn empty_config_is_none() {
408        assert!(Config::new().into_option().is_none());
409    }
410
411    // The shape every other ccxt binding sends for
412    // `{"options": {"fetchMarkets": {"types": [...]}, "defaultType": "..."}}`.
413    #[test]
414    fn options_nest_like_the_other_bindings() {
415        let v = Config::new()
416            .api_key("k")
417            .option("fetchMarkets", Params::new().with_strs("types", &["spot", "linear"]))
418            .option_str("defaultType", "spot")
419            .sandbox(true)
420            .into_value();
421        let top = dict(&v);
422        assert_eq!(top["apiKey"], Value::Str("k".into()));
423        let options = dict(&top["options"]);
424        assert_eq!(options["defaultType"], Value::Str("spot".into()));
425        assert_eq!(options["sandbox"], Value::Bool(true));
426        // The nested object, exactly as the other bindings send it.
427        let fetch_markets = dict(&options["fetchMarkets"]);
428        let types = match &fetch_markets["types"] { Value::Arr(a) => a.clone(), _ => panic!("types") };
429        assert_eq!(&types[..], &[Value::Str("spot".into()), Value::Str("linear".into())]);
430    }
431
432    #[test]
433    fn options_block_can_be_handed_over_wholesale() {
434        let v = Config::new()
435            .options(Params::new()
436                .with_params("fetchMarkets", Params::new().with_strs("types", &["swap"]))
437                .with_str("defaultType", "swap"))
438            .into_value();
439        let options = dict(&dict(&v)["options"]);
440        assert_eq!(options["defaultType"], Value::Str("swap".into()));
441        let types = match &dict(&options["fetchMarkets"])["types"] { Value::Arr(a) => a.clone(), _ => panic!("types") };
442        assert_eq!(&types[..], &[Value::Str("swap".into())]);
443    }
444
445    // Several entries at the same level: just keep chaining.
446    #[test]
447    fn many_entries_at_one_level() {
448        let v = Config::new()
449            .option("fetchMarkets", Params::new()
450                .with_strs("types", &["spot", "swap"])
451                .with_bool("skipDelisted", true)
452                .with_int("limit", 500))
453            .into_value();
454        let fm = dict(&dict(&dict(&v)["options"])["fetchMarkets"]);
455        assert_eq!(fm.len(), 3);
456        assert_eq!(fm["skipDelisted"], Value::Bool(true));
457        assert_eq!(fm["limit"], Value::Int(500));
458    }
459
460    // Repeated `option` calls for the same key add to it rather than replace.
461    #[test]
462    fn repeated_option_calls_merge() {
463        let v = Config::new()
464            .option("fetchMarkets", Params::new().with_strs("types", &["spot"]))
465            .option("fetchMarkets", Params::new().with_bool("skipDelisted", true))
466            .into_value();
467        let fm = dict(&dict(&dict(&v)["options"])["fetchMarkets"]);
468        assert_eq!(fm.len(), 2, "second call must not clobber the first");
469        assert!(matches!(fm["types"], Value::Arr(_)));
470        assert_eq!(fm["skipDelisted"], Value::Bool(true));
471    }
472
473    // `options()` composes with settings made before AND after it.
474    #[test]
475    fn options_block_merges_with_neighbours() {
476        let v = Config::new()
477            .sandbox(true)
478            .options(Params::new().with_str("defaultType", "swap"))
479            .option_int("recvWindow", 5_000)
480            .into_value();
481        let options = dict(&dict(&v)["options"]);
482        assert_eq!(options["sandbox"], Value::Bool(true), "sandbox must survive options()");
483        assert_eq!(options["defaultType"], Value::Str("swap".into()));
484        assert_eq!(options["recvWindow"], Value::Int(5_000));
485    }
486
487    #[test]
488    fn a_literal_dot_in_a_key_stays_a_literal_dot() {
489        let v = Config::new().option_str("a.b", "x").into_value();
490        assert_eq!(dict(&dict(&v)["options"])["a.b"], Value::Str("x".into()));
491    }
492}