Skip to main content

pine_lang/
lib.rs

1// Re-export all public types from sub-crates
2pub use pine_ast as ast;
3pub use pine_broker as broker;
4pub use pine_builtins as builtins;
5use pine_builtins::DefaultPineOutput;
6pub use pine_core as core;
7pub use pine_data as data;
8pub use pine_diagnostics as diagnostics;
9pub use pine_format as format;
10pub use pine_interpreter as interpreter;
11pub use pine_lexer as lexer;
12pub use pine_lint as lint;
13pub use pine_parser as parser;
14pub use pine_sema as sema;
15
16mod backtest;
17mod run;
18
19pub use backtest::{Backtest, Metrics};
20pub use pine_core::{DataProvider, DirLoader, FileResolver, LibraryLoader};
21pub use run::{Run, RunResult};
22
23use pine_ast::Program;
24use pine_core::{
25    AlertConditionOutput, BoxOutput, DrawingOutput, FillOutput, GlobalOutput, InputOutput,
26    LabelOutput, LineOutput, LogOutput, MetadataOutput, PineOutput, PlotOutput, TableOutput,
27};
28use pine_core::{Bar, Data, PineVersion, Timeframe, VersionError};
29use pine_diagnostics::Diagnostic;
30use pine_interpreter::{Interpreter, RuntimeError, Value};
31use pine_lexer::{Lexer, LexerError};
32use pine_parser::{Parser, ParserError};
33use std::collections::HashMap;
34use std::rc::Rc;
35
36/// Error type for Pine operations
37#[derive(Debug)]
38pub enum Error {
39    Lexer(LexerError),
40    Parser(ParserError),
41    Runtime(RuntimeError),
42    /// Semantic analysis failed; the program is invalid. Carries every
43    /// diagnostic found.
44    Sema(Vec<Diagnostic>),
45    /// The script's `//@version=N` annotation names a version this toolchain
46    /// cannot compile.
47    Version(VersionError),
48    /// No bars to run over: neither data nor a provider was given, or the
49    /// provider could not produce the requested feed.
50    Data(pine_core::ProviderError),
51}
52
53impl std::fmt::Display for Error {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        match self {
56            Error::Lexer(e) => write!(f, "Lexer error: {}", e),
57            Error::Parser(e) => write!(f, "Parser error: {}", e),
58            Error::Runtime(e) => write!(f, "Runtime error: {}", e),
59            Error::Version(e) => write!(f, "Version error: {}", e),
60            Error::Data(e) => write!(f, "Data error: {}", e),
61            // One diagnostic per line, so multiple errors are simply appended.
62            Error::Sema(diags) => {
63                for (i, d) in diags.iter().enumerate() {
64                    if i > 0 {
65                        writeln!(f)?;
66                    }
67                    write!(f, "{}", d)?;
68                }
69                Ok(())
70            }
71        }
72    }
73}
74
75impl std::error::Error for Error {}
76
77impl From<RuntimeError> for Error {
78    fn from(e: RuntimeError) -> Self {
79        Error::Runtime(e)
80    }
81}
82
83impl From<LexerError> for Error {
84    fn from(e: LexerError) -> Self {
85        Error::Lexer(e)
86    }
87}
88
89impl From<ParserError> for Error {
90    fn from(e: ParserError) -> Self {
91        Error::Parser(e)
92    }
93}
94
95impl From<VersionError> for Error {
96    fn from(e: VersionError) -> Self {
97        Error::Version(e)
98    }
99}
100
101/// Parse and semantically analyze `source` without bars or execution, returning
102/// every diagnostic.
103pub fn check(source: &str, loader: Option<&dyn LibraryLoader>) -> Result<Vec<Diagnostic>, Error> {
104    let version = PineVersion::detect(source)?.unwrap_or(PineVersion::LATEST);
105    let tokens = Lexer::with_version(source, version).tokenize()?;
106    let program = Parser::new(tokens).parse_program()?;
107
108    let (mut env, _): (HashMap<String, Value<DefaultPineOutput>>, _) =
109        pine_builtins::register_namespace_objects(version, None, None);
110    for (name, value) in pine_builtins::per_bar_variables(&Bar::default(), None) {
111        env.insert(name, value);
112    }
113
114    let mut diagnostics = pine_sema::analyze(&program, &env, loader);
115    diagnostics.extend(pine_lint::lint(&program));
116    diagnostics.sort_by_key(|d| d.pos.unwrap_or((u32::MAX, u32::MAX)));
117    Ok(diagnostics)
118}
119
120/// Decode `input.*` overrides from a JSON object — `{"Length": 20, "Smooth":
121/// true, "Source": "close"}` — keyed by input title, for
122/// [`ScriptBuilder::with_inputs`].
123pub fn inputs_from_json(
124    json: &str,
125) -> Result<HashMap<String, pine_core::InputValue>, serde_json::Error> {
126    serde_json::from_str(json)
127}
128
129pub struct ScriptBuilder<O: PineOutput> {
130    source: String,
131    custom_variables: HashMap<String, Value<O>>,
132    inputs: HashMap<String, pine_core::InputValue>,
133    library_loader: Option<Box<dyn LibraryLoader>>,
134    request_provider: Option<Box<dyn DataProvider>>,
135    ticker: Option<String>,
136    timeframe: Timeframe,
137    data: Option<Data>,
138    bar_count: Option<usize>,
139    broker_factory: Option<Box<dyn pine_broker::BrokerFactory>>,
140}
141
142impl<O: PineOutput> ScriptBuilder<O> {
143    pub fn with_code(source: &str) -> ScriptBuilder<O> {
144        Self {
145            source: source.to_string(),
146            custom_variables: HashMap::new(),
147            inputs: HashMap::new(),
148            library_loader: None,
149            request_provider: None,
150            ticker: None,
151            timeframe: Timeframe::default(),
152            data: None,
153            bar_count: None,
154            broker_factory: None,
155        }
156    }
157
158    /// Host overrides for the script's `input.*` calls, keyed by input title.
159    /// Each `input.*` returns (and validates) the override for its title if one
160    /// is present, else its declared default. See [`inputs_from_json`].
161    pub fn with_inputs(mut self, inputs: HashMap<String, pine_core::InputValue>) -> Self {
162        self.inputs = inputs;
163        self
164    }
165
166    /// Host-supplied variables the script can reference, registered as consts
167    /// alongside the builtin namespaces.
168    pub fn with_custom_variables(mut self, variables: HashMap<String, Value<O>>) -> Self {
169        self.custom_variables = variables;
170        self
171    }
172
173    /// Resolves `import` statements. Without one, importing a library fails.
174    pub fn with_library_loader(mut self, loader: Box<dyn LibraryLoader>) -> Self {
175        self.library_loader = Some(loader);
176        self
177    }
178
179    /// Supplies bars for `request.security`. Without one, `request.security`
180    /// returns na.
181    pub fn with_request_provider(mut self, provider: Box<dyn DataProvider>) -> Self {
182        self.request_provider = Some(provider);
183        self
184    }
185
186    /// Swaps the broker a `strategy` trades against. Without one, the built-in
187    /// [`DefaultBrokerFactory`](pine_broker::DefaultBrokerFactory) is used.
188    pub fn with_broker(mut self, factory: Box<dyn pine_broker::BrokerFactory>) -> Self {
189        self.broker_factory = Some(factory);
190        self
191    }
192
193    pub fn with_ticker(mut self, ticker: String) -> Self {
194        self.ticker = Some(ticker);
195        self
196    }
197
198    /// The chart timeframe exposed to the script as `timeframe.*`. Without one,
199    /// the namespace is populated with defaults.
200    pub fn with_timeframe(mut self, timeframe: Timeframe) -> Self {
201        self.timeframe = timeframe;
202        self
203    }
204
205    /// Run over only the last `bar_count` bars of the feed. Without one, the
206    /// whole feed is used.
207    pub fn with_bar_count(mut self, bar_count: usize) -> Self {
208        self.bar_count = Some(bar_count);
209        self
210    }
211
212    /// The market to run over: the bars, and the symbol and timeframe they
213    /// belong to.
214    ///
215    /// The data describes itself, so it fills in `syminfo.*` and `timeframe.*`
216    /// too. An explicit [`ScriptBuilder::with_syminfo`] or
217    /// [`ScriptBuilder::with_timeframe`] still wins, whichever order they are
218    /// called in.
219    pub fn with_data(mut self, data: Data) -> Self {
220        self.data = Some(data);
221        self
222    }
223
224    /// Compile PineScript source code into a Script with default output
225    pub fn compile(self) -> Result<Script<O>, Error>
226    where
227        O: LogOutput
228            + PlotOutput
229            + LabelOutput
230            + BoxOutput
231            + InputOutput
232            + LineOutput
233            + TableOutput
234            + MetadataOutput
235            + GlobalOutput
236            + AlertConditionOutput
237            + FillOutput
238            + DrawingOutput,
239    {
240        let data = match self.data {
241            Some(data) => data,
242            None => {
243                let provider = self
244                    .request_provider
245                    .as_ref()
246                    .ok_or_else(|| Error::Data("no data or request provider set".into()))?;
247
248                let ticker = self.ticker.clone().unwrap_or_default();
249                provider
250                    .request(&ticker, self.timeframe.clone())
251                    .map_err(Error::Data)?
252            }
253        };
254
255        let syminfo = data.syminfo;
256        let timeframe = self.timeframe;
257
258        // Keep only the last `bar_count` bars when the caller limited the run.
259        let mut bars = data.bars;
260        if let Some(n) = self.bar_count {
261            let len = bars.len();
262            bars = bars.split_off(len.saturating_sub(n.max(1)));
263        }
264
265        // The chart's bar spacing, so `request.security_lower_tf` can reject a
266        // request that is not actually lower than the chart timeframe.
267        let chart_period = bars
268            .windows(2)
269            .next()
270            .map(|pair| pair[1].time - pair[0].time);
271
272        let source = self.source.as_str();
273        let version = PineVersion::detect(source)?.unwrap_or(PineVersion::LATEST);
274
275        let mut lexer = Lexer::with_version(source, version);
276        let tokens = lexer.tokenize()?;
277
278        let mut parser = Parser::new(tokens);
279        let statements = parser.parse()?;
280        let program = Program::new(statements);
281
282        // The interpreter's const environment: the registered namespaces plus any
283        // host-supplied globals. Built once and handed over as-is.
284        let (mut consts, advances) = pine_builtins::register_namespace_objects(
285            version,
286            Some(syminfo),
287            Some(timeframe.clone()),
288        );
289        for (name, value) in self.custom_variables {
290            consts.insert(name, value);
291        }
292
293        let mut builtins = consts.clone();
294        for (name, value) in pine_builtins::per_bar_variables(&Bar::default(), None) {
295            builtins.insert(name, value);
296        }
297
298        // Semantic pre-check: reject if sema produces errors.
299        let errors: Vec<_> =
300            pine_sema::analyze(&program, &builtins, self.library_loader.as_deref())
301                .into_iter()
302                .filter(|diagnostic| diagnostic.severity == pine_diagnostics::Severity::Error)
303                .collect();
304        if !errors.is_empty() {
305            return Err(Error::Sema(errors));
306        }
307
308        // Create interpreter and load builtin namespace objects
309        let mut interpreter = Interpreter::new();
310        interpreter.library_loader = self.library_loader;
311        interpreter.request_provider = self.request_provider.map(Rc::from);
312        interpreter.chart_period = chart_period;
313        if let Some(broker_factory) = self.broker_factory {
314            interpreter.broker_factory = Some(broker_factory);
315        }
316        interpreter.set_const_variables(consts);
317        interpreter.per_bar_advances = advances;
318        interpreter.inputs = self.inputs;
319
320        Ok(Script {
321            program,
322            interpreter,
323            timeframe,
324            bars,
325            equity_curve: Vec::new(),
326            last_close: 0.0,
327            equity_peak: f64::NEG_INFINITY,
328            equity_trough: f64::INFINITY,
329            max_drawdown: 0.0,
330            max_runup: 0.0,
331            max_drawdown_percent: 0.0,
332            max_runup_percent: 0.0,
333            max_contracts_all: 0.0,
334            max_contracts_long: 0.0,
335            max_contracts_short: 0.0,
336        })
337    }
338}
339
340/// A compiled PineScript program, and the bars it will run over.
341///
342/// State accumulates across bars — series history, `var` locals, and every
343/// stateful builtin's window — exactly as it does in TradingView. That makes a
344/// `Script` single-use: [`Script::run`] takes it by value so a second run
345/// cannot inherit the first one's state.
346pub struct Script<O: PineOutput> {
347    program: Program,
348    interpreter: Interpreter<O>,
349    /// The chart timeframe, carried onto the `Backtest` so its metrics can
350    /// annualise per-bar figures.
351    timeframe: Timeframe,
352    /// Bars from the builder's source; empty when none was given.
353    bars: Vec<Bar>,
354    /// Account value at each bar's close, accumulated while a `strategy` runs.
355    equity_curve: Vec<f64>,
356    /// The last bar's close, used to mark open trades at the run's end.
357    last_close: f64,
358    /// Running equity extremes for `strategy.max_drawdown`/`max_runup`.
359    equity_peak: f64,
360    equity_trough: f64,
361    max_drawdown: f64,
362    max_runup: f64,
363    /// Drawdown/run-up as a fraction of the peak/trough, tracked separately
364    /// because the percentage extreme need not coincide with the cash extreme.
365    max_drawdown_percent: f64,
366    max_runup_percent: f64,
367    /// Largest position (in contracts) ever held, overall and per side.
368    max_contracts_all: f64,
369    max_contracts_long: f64,
370    max_contracts_short: f64,
371}
372
373impl<O: PineOutput> Script<O> {
374    /// Run one bar. Private: bars must be replayed in order from the first, so
375    /// [`Script::run`] is the only way in.
376    pub fn execute(&mut self, bar: &Bar, last_bar: Option<&Bar>) -> Result<O, Error> {
377        use interpreter::Value;
378
379        self.interpreter.current_time = Some(bar.time);
380
381        for (name, value) in pine_builtins::per_bar_variables(bar, last_bar) {
382            if matches!(value, Value::Series(_)) {
383                self.interpreter.advance_series(&name, value);
384            } else {
385                self.interpreter.set_variable(&name, value);
386            }
387        }
388
389        // Fill orders left pending by the previous bar before the body runs, so
390        // it reads the position and equity they produced. A no-op unless the
391        // script declared a `strategy`.
392        self.advance_broker(bar);
393
394        let output = self.interpreter.execute(&self.program)?;
395
396        // Read after the body so the bar a `strategy` is declared on is counted.
397        if let Some(broker) = self.interpreter.broker.as_ref() {
398            self.equity_curve.push(broker.equity(bar.close));
399            self.last_close = bar.close;
400        }
401
402        Ok(output)
403    }
404
405    /// Advance the simulated broker one bar and refresh the read-only
406    /// `strategy.*` values from it. The interpreter only holds the broker
407    /// handle; the backtest accounting that maps it onto script variables lives
408    /// here, in the host.
409    fn advance_broker(&mut self, bar: &Bar) {
410        use interpreter::Value;
411
412        let close = bar.close;
413
414        // Read from the broker, then drop the borrow to update `self`'s state.
415        let Some(broker) = self.interpreter.broker.as_mut() else {
416            return;
417        };
418        broker.advance(bar);
419
420        let position = broker.position();
421        let equity = broker.equity(close);
422        let initial = broker.initial_capital();
423        // Equity is monotonic in price, so its intrabar extremes are the marks
424        // at the bar's high and low — lower is adverse, higher favourable.
425        let equity_hi = broker.equity(bar.high);
426        let equity_lo = broker.equity(bar.low);
427        let intrabar_low = equity_hi.min(equity_lo);
428        let intrabar_high = equity_hi.max(equity_lo);
429        let open_profit: f64 = broker.open_trades().iter().map(|t| t.profit(close)).sum();
430        let closed_trades = broker.closed_trades().len() as i64;
431
432        let (mut gross_profit, mut gross_loss) = (0.0, 0.0);
433        let (mut wins, mut losses, mut evens) = (0i64, 0i64, 0i64);
434        for trade in broker.closed_trades() {
435            let profit = trade.profit(close); // closed, so the price is ignored
436            if profit > 0.0 {
437                gross_profit += profit;
438                wins += 1;
439            } else if profit < 0.0 {
440                gross_loss -= profit; // positive magnitude, as Pine reports it
441                losses += 1;
442            } else {
443                evens += 1;
444            }
445        }
446
447        // Read the rest off the broker while its borrow is live: each closed
448        // trade's percent return (for the average-trade-percent figures) and the
449        // open position's entry name.
450        let (mut trade_pcts, mut win_pcts, mut loss_pcts) = (Vec::new(), Vec::new(), Vec::new());
451        for trade in broker.closed_trades() {
452            let profit = trade.profit(close);
453            let basis = trade.entry_price * trade.size.abs();
454            let ret = if basis != 0.0 {
455                profit / basis * 100.0
456            } else {
457                0.0
458            };
459            trade_pcts.push(ret);
460            if profit > 0.0 {
461                win_pcts.push(ret);
462            } else if profit < 0.0 {
463                loss_pcts.push(ret);
464            }
465        }
466        let position_entry_name = broker
467            .open_trades()
468            .last()
469            .map_or(Value::Na, |t| Value::String(t.entry_id.clone()));
470
471        // Drawdown/run-up measure the intrabar extreme against a peak/trough
472        // that tracks close equity — an intrabar swing does not move the mark.
473        // Seed with the starting capital (the declaration bar's equity).
474        if self.equity_peak == f64::NEG_INFINITY {
475            self.equity_peak = initial;
476            self.equity_trough = initial;
477        }
478        self.equity_peak = self.equity_peak.max(equity);
479        self.equity_trough = self.equity_trough.min(equity);
480        self.max_drawdown = self.max_drawdown.max(self.equity_peak - intrabar_low);
481        self.max_runup = self.max_runup.max(intrabar_high - self.equity_trough);
482        if self.equity_peak > 0.0 {
483            let dd = (self.equity_peak - intrabar_low) / self.equity_peak * 100.0;
484            self.max_drawdown_percent = self.max_drawdown_percent.max(dd);
485        }
486        if self.equity_trough > 0.0 {
487            let ru = (intrabar_high - self.equity_trough) / self.equity_trough * 100.0;
488            self.max_runup_percent = self.max_runup_percent.max(ru);
489        }
490        // Largest position held, overall and per side.
491        self.max_contracts_all = self.max_contracts_all.max(position.size.abs());
492        if position.size > 0.0 {
493            self.max_contracts_long = self.max_contracts_long.max(position.size);
494        } else if position.size < 0.0 {
495            self.max_contracts_short = self.max_contracts_short.max(-position.size);
496        }
497
498        // Pine's identity equity = initial + netprofit + openprofit; derive
499        // netprofit from it so commission can't make the two drift.
500        let net_profit = equity - initial - open_profit;
501        // na, not 0, when flat — matching Pine.
502        let avg_price = if position.size == 0.0 {
503            Value::Na
504        } else {
505            Value::Number(position.avg_price)
506        };
507
508        let refreshed = [
509            ("position_size", Value::Number(position.size)),
510            ("position_avg_price", avg_price),
511            ("equity", Value::Number(equity)),
512            ("netprofit", Value::Number(net_profit)),
513            ("openprofit", Value::Number(open_profit)),
514            ("grossprofit", Value::Number(gross_profit)),
515            ("grossloss", Value::Number(gross_loss)),
516            ("max_drawdown", Value::Number(self.max_drawdown)),
517            ("max_runup", Value::Number(self.max_runup)),
518            // `opentrades` / `closedtrades` are value-objects that read their
519            // count straight from the broker, so they are not refreshed here.
520            ("wintrades", Value::Int(wins)),
521            ("losstrades", Value::Int(losses)),
522            ("eventrades", Value::Int(evens)),
523        ];
524        for (name, value) in refreshed {
525            self.interpreter.set_object_field("strategy", name, value);
526        }
527
528        // Derived statistics: percentages of the starting capital, and per-trade
529        // averages. `na` when there are no trades to average, matching Pine.
530        let pct = |x: f64| {
531            if initial != 0.0 {
532                x / initial * 100.0
533            } else {
534                0.0
535            }
536        };
537        let per_trade = |total: f64, count: i64| {
538            if count > 0 {
539                Value::Number(total / count as f64)
540            } else {
541                Value::Na
542            }
543        };
544        let mean = |v: &[f64]| {
545            if v.is_empty() {
546                Value::Na
547            } else {
548                Value::Number(v.iter().sum::<f64>() / v.len() as f64)
549            }
550        };
551        let derived = [
552            ("netprofit_percent", Value::Number(pct(net_profit))),
553            ("openprofit_percent", Value::Number(pct(open_profit))),
554            ("grossprofit_percent", Value::Number(pct(gross_profit))),
555            ("grossloss_percent", Value::Number(pct(gross_loss))),
556            (
557                "max_drawdown_percent",
558                Value::Number(self.max_drawdown_percent),
559            ),
560            ("max_runup_percent", Value::Number(self.max_runup_percent)),
561            (
562                "max_contracts_held_all",
563                Value::Number(self.max_contracts_all),
564            ),
565            (
566                "max_contracts_held_long",
567                Value::Number(self.max_contracts_long),
568            ),
569            (
570                "max_contracts_held_short",
571                Value::Number(self.max_contracts_short),
572            ),
573            ("avg_trade", per_trade(net_profit, closed_trades)),
574            ("avg_winning_trade", per_trade(gross_profit, wins)),
575            // Losing trades are reported as a negative average, so negate the
576            // positive gross-loss magnitude.
577            ("avg_losing_trade", per_trade(-gross_loss, losses)),
578            ("avg_trade_percent", mean(&trade_pcts)),
579            ("avg_winning_trade_percent", mean(&win_pcts)),
580            ("avg_losing_trade_percent", mean(&loss_pcts)),
581            ("position_entry_name", position_entry_name),
582        ];
583        for (name, value) in derived {
584            self.interpreter.set_object_field("strategy", name, value);
585        }
586    }
587
588    /// Replay the script over every bar from its source, returning what each
589    /// one produced.
590    pub fn run(mut self) -> Result<Run<O>, Error> {
591        let bars = std::mem::take(&mut self.bars);
592        let last_bar = bars.last().cloned();
593        let outputs = bars
594            .iter()
595            .map(|bar| self.execute(bar, last_bar.as_ref()))
596            .collect::<Result<Vec<O>, Error>>()?;
597        let backtest = self.take_backtest();
598        Ok(Run { outputs, backtest })
599    }
600
601    fn take_backtest(&mut self) -> Option<Backtest> {
602        let broker = self.interpreter.broker.as_ref()?;
603        let close = self.last_close;
604
605        // Closed trades first, then those still open.
606        let mut trades: Vec<_> = broker.closed_trades().to_vec();
607        trades.extend(broker.open_trades().into_iter().cloned());
608
609        let open_profit: f64 = broker.open_trades().iter().map(|t| t.profit(close)).sum();
610        let initial_capital = broker.initial_capital();
611        let position_size = broker.position().size;
612
613        let (mut gross_profit, mut gross_loss) = (0.0, 0.0);
614        let (mut win_trades, mut loss_trades, mut even_trades) = (0, 0, 0);
615        for trade in broker.closed_trades() {
616            let profit = trade.profit(close);
617            if profit > 0.0 {
618                gross_profit += profit;
619                win_trades += 1;
620            } else if profit < 0.0 {
621                gross_loss -= profit;
622                loss_trades += 1;
623            } else {
624                even_trades += 1;
625            }
626        }
627
628        let equity = std::mem::take(&mut self.equity_curve);
629        let final_equity = equity.last().copied().unwrap_or(initial_capital);
630
631        Some(Backtest {
632            initial_capital,
633            net_profit: final_equity - initial_capital - open_profit,
634            open_profit,
635            gross_profit,
636            gross_loss,
637            max_drawdown: self.max_drawdown,
638            max_runup: self.max_runup,
639            win_trades,
640            loss_trades,
641            even_trades,
642            position_size,
643            mark_price: close,
644            equity,
645            trades,
646            halted: broker.halted_bar(),
647            timeframe: self.timeframe.clone(),
648        })
649    }
650}
651
652pub fn execute(source: &str, data: Data) -> Result<(), Error> {
653    ScriptBuilder::<DefaultPineOutput>::with_code(source)
654        .with_data(data)
655        .compile()?
656        .run()
657        .map(|_| ())
658}
659
660#[cfg(test)]
661mod tests {
662    use super::inputs_from_json;
663    use pine_core::InputValue;
664
665    #[test]
666    fn decodes_input_overrides_from_json() {
667        let map = inputs_from_json(r#"{"Length": 20, "Ratio": 1.5, "On": true, "Mode": "fast"}"#)
668            .unwrap();
669        assert_eq!(map["Length"], InputValue::Int(20));
670        assert_eq!(map["Ratio"], InputValue::Float(1.5));
671        assert_eq!(map["On"], InputValue::Bool(true));
672        assert_eq!(map["Mode"], InputValue::Str("fast".to_string()));
673    }
674}