pine-builtins 0.2.1

Built-in functions and namespaces for the Pine Script interpreter.
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
//! The `strategy` namespace: the declaration plus the order commands a
//! backtest trades with.
//!
//! `strategy` is both callable and a namespace — `strategy("My Strat", ...)`
//! declares the script and sets up the simulated [`Broker`], while
//! `strategy.entry`/`strategy.close`/… submit orders to it. The read-only
//! values (`strategy.position_size`, `strategy.equity`, …) are seeded here and
//! refreshed each bar by the host after the broker advances; the interpreter
//! itself holds only the broker handle and carries no backtest logic.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use pine_broker::{
    BrokerConfig, Commission, Direction, EntryFilter, Exit, OcaType, Order, OrderKind, RiskRule,
    RiskType, Sizing,
};
use pine_builtin_macro::BuiltinFunction;
use pine_core::{PineOutput, PineVersion};
use pine_interpreter::{BuiltinFn, Interpreter, RuntimeError, Value};

/// TradingView's default starting capital.
const DEFAULT_INITIAL_CAPITAL: f64 = 1_000_000.0;

/// strategy(title, shorttitle, overlay, ..., default_qty_type, default_qty_value,
/// initial_capital, ..., slippage, commission_type, commission_value, ...)
///
/// Only the parameters that shape the simulated broker are honoured; display
/// and reporting-only parameters are accepted and ignored. Runs every bar, but
/// only builds the broker on the first, so state persists across the backtest.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy")]
struct StrategyFn {
    #[allow(dead_code)]
    title: String,
    #[arg(default = "")]
    shorttitle: String,
    #[arg(default = false)]
    overlay: bool,
    #[arg(default = "")]
    format: String,
    #[arg(default = None)]
    precision: Option<f64>,
    #[arg(default = "")]
    scale: String,
    #[arg(default = None)]
    pyramiding: Option<f64>,
    #[arg(default = "fixed")]
    default_qty_type: String,
    #[arg(default = 1.0)]
    default_qty_value: f64,
    #[arg(default = None)]
    initial_capital: Option<f64>,
    #[arg(default = "")]
    currency: String,
    #[arg(default = 0.0)]
    slippage: f64,
    #[arg(default = "percent")]
    commission_type: String,
    #[arg(default = 0.0)]
    commission_value: f64,
}

impl StrategyFn {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = (
            &self.shorttitle,
            self.overlay,
            &self.format,
            self.precision,
            &self.scale,
            &self.currency,
        );

        // Runs every bar; build the broker only once so trades accumulate.
        if ctx.broker.is_none() {
            let initial_capital = self.initial_capital.unwrap_or(DEFAULT_INITIAL_CAPITAL);
            let commission =
                (self.commission_value != 0.0).then_some(match self.commission_type.as_str() {
                    "cash_per_contract" => Commission::CashPerContract(self.commission_value),
                    "cash_per_order" => Commission::CashPerOrder(self.commission_value),
                    // "percent" and anything unrecognised.
                    _ => Commission::Percent(self.commission_value),
                });
            let config = BrokerConfig {
                initial_capital,
                mintick: mintick_of(ctx),
                sizing: self.sizing(),
                pyramiding: self.pyramiding.unwrap_or(0.0) as usize,
                commission,
                slippage: self.slippage,
            };

            let factory = ctx.broker_factory.as_ref().ok_or_else(|| {
                RuntimeError::TypeError("strategy() has no broker configured".to_string())
            })?;
            ctx.broker = Some(factory.build(&config));
            ctx.set_object_field(
                "strategy",
                "initial_capital",
                Value::Number(initial_capital),
            );
            ctx.set_object_field("strategy", "equity", Value::Number(initial_capital));
        }

        Ok(Value::Na)
    }

    /// How an order's absent `qty` is sized, from `default_qty_type`.
    fn sizing(&self) -> Sizing {
        match self.default_qty_type.as_str() {
            "cash" => Sizing::Cash(self.default_qty_value),
            "percent_of_equity" => Sizing::PercentOfEquity(self.default_qty_value),
            // "fixed" and anything unrecognised: a contract count.
            _ => Sizing::Contracts(self.default_qty_value),
        }
    }
}

/// The symbol's tick size from `syminfo.mintick`, or 0 (which disables tick-based
/// slippage and exit distances) when it is unknown.
fn mintick_of<O: PineOutput>(ctx: &Interpreter<O>) -> f64 {
    if let Some(Value::Object { fields, .. }) = ctx.get_variable("syminfo") {
        if let Some(Value::Number(mintick)) = fields.borrow().get("mintick") {
            return *mintick;
        }
    }
    0.0
}

/// The current bar's `close`, used to size a default-qty order the way Pine
/// does — from the close of the bar the order command runs on.
fn close_of<O: PineOutput>(ctx: &Interpreter<O>) -> f64 {
    match ctx.get_variable("close") {
        Some(Value::Series(series)) => match series.current.as_ref() {
            Value::Number(n) => *n,
            _ => f64::NAN,
        },
        Some(Value::Number(n)) => *n,
        _ => f64::NAN,
    }
}

/// A string argument as an option, mapping the empty default to `None` — used
/// for an OCA group name and an exit's `from_entry`.
fn non_empty(name: &str) -> Option<String> {
    if name.is_empty() {
        None
    } else {
        Some(name.to_string())
    }
}

/// The order condition from an entry/order call's `limit` and `stop`: both set
/// makes a stop-limit, either alone a limit or stop, neither a market order.
fn order_kind(limit: Option<f64>, stop: Option<f64>) -> OrderKind {
    match (limit, stop) {
        (Some(limit), Some(stop)) => OrderKind::StopLimit { stop, limit },
        (Some(limit), None) => OrderKind::Limit(limit),
        (None, Some(stop)) => OrderKind::Stop(stop),
        (None, None) => OrderKind::Market,
    }
}

/// strategy.entry(id, direction, qty, limit, stop, ...)
///
/// Enters or reverses a position: a fill on the opposite side closes the
/// current position and opens the requested one.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.entry")]
struct StrategyEntry {
    id: String,
    direction: String,
    #[arg(default = None)]
    qty: Option<f64>,
    #[arg(default = None)]
    limit: Option<f64>,
    #[arg(default = None)]
    stop: Option<f64>,
    #[arg(default = "")]
    oca_name: String,
    #[arg(default = "")]
    oca_type: String,
    #[arg(default = "")]
    comment: String,
}

impl StrategyEntry {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let sizing_price = close_of(ctx);
        if let Some(broker) = ctx.broker.as_mut() {
            broker.submit(Order {
                id: self.id.clone(),
                direction: Direction::from(self.direction.as_str()),
                qty: self.qty,
                qty_percent: None,
                sizing_price: Some(sizing_price),
                kind: order_kind(self.limit, self.stop),
                reduce_only: false,
                reverses: true,
                close_target: None,
                oca_name: non_empty(&self.oca_name),
                oca_type: OcaType::from(self.oca_type.as_str()),
                comment: self.comment.clone(),
            });
        }
        Ok(Value::Na)
    }
}

/// strategy.order(id, direction, qty, limit, stop, ...)
///
/// Like [`StrategyEntry`] but a plain order: it neither reverses an opposite
/// position nor obeys pyramiding — it simply adds contracts in `direction`.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.order")]
struct StrategyOrder {
    id: String,
    direction: String,
    #[arg(default = None)]
    qty: Option<f64>,
    #[arg(default = None)]
    limit: Option<f64>,
    #[arg(default = None)]
    stop: Option<f64>,
    #[arg(default = "")]
    oca_name: String,
    #[arg(default = "")]
    oca_type: String,
    #[arg(default = "")]
    comment: String,
}

impl StrategyOrder {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let sizing_price = close_of(ctx);
        if let Some(broker) = ctx.broker.as_mut() {
            broker.submit(Order {
                id: self.id.clone(),
                direction: Direction::from(self.direction.as_str()),
                qty: self.qty,
                qty_percent: None,
                sizing_price: Some(sizing_price),
                kind: order_kind(self.limit, self.stop),
                reduce_only: false,
                reverses: false,
                close_target: None,
                oca_name: non_empty(&self.oca_name),
                oca_type: OcaType::from(self.oca_type.as_str()),
                comment: self.comment.clone(),
            });
        }
        Ok(Value::Na)
    }
}

/// strategy.close(id, comment, qty, qty_percent, ...)
///
/// Exits the position opened by entry `id` with a market order, closing that
/// entry's lots oldest-first. With no `qty` it closes all of them.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.close")]
struct StrategyClose {
    id: String,
    #[arg(default = "")]
    comment: String,
    #[arg(default = None)]
    qty: Option<f64>,
    #[arg(default = None)]
    qty_percent: Option<f64>,
}

impl StrategyClose {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        if let Some(broker) = ctx.broker.as_mut() {
            // Direction is ignored for a reduce-only order — the broker closes
            // against whatever side is open — so Long is just a placeholder. The
            // order's id names the entry whose lots it closes.
            broker.submit(Order {
                id: self.id.clone(),
                direction: Direction::Long,
                qty: self.qty,
                qty_percent: self.qty_percent,
                sizing_price: None,
                kind: OrderKind::Market,
                reduce_only: true,
                reverses: false,
                close_target: Some(self.id.clone()),
                oca_name: None,
                oca_type: OcaType::None,
                comment: self.comment.clone(),
            });
        }
        Ok(Value::Na)
    }
}

/// strategy.close_all(comment, alert_message)
///
/// Flattens the position with a market order.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.close_all")]
struct StrategyCloseAll {
    #[arg(default = "")]
    comment: String,
}

impl StrategyCloseAll {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        if let Some(broker) = ctx.broker.as_mut() {
            broker.submit(Order {
                id: "Close all".to_string(),
                direction: Direction::Long,
                qty: None,
                qty_percent: None,
                sizing_price: None,
                kind: OrderKind::Market,
                reduce_only: true,
                reverses: false,
                close_target: None,
                oca_name: None,
                oca_type: OcaType::None,
                comment: self.comment.clone(),
            });
        }
        Ok(Value::Na)
    }
}

/// strategy.cancel(id) — remove a pending order by id.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.cancel")]
struct StrategyCancel {
    id: String,
}

impl StrategyCancel {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        if let Some(broker) = ctx.broker.as_mut() {
            broker.cancel(&self.id);
        }
        Ok(Value::Na)
    }
}

/// strategy.cancel_all() — remove every pending order.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.cancel_all")]
struct StrategyCancelAll {}

impl StrategyCancelAll {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        if let Some(broker) = ctx.broker.as_mut() {
            broker.cancel_all();
        }
        Ok(Value::Na)
    }
}

/// A `strategy.risk.*` threshold's measure, from a `strategy.cash` /
/// `strategy.percent_of_equity` argument (percent for anything else).
fn risk_type(value: f64, kind: &str) -> RiskType {
    match kind {
        "cash" => RiskType::Cash(value),
        _ => RiskType::Percent(value),
    }
}

/// strategy.risk.allow_entry_in(value) — restrict entries to one direction.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.allow_entry_in")]
struct RiskAllowEntryIn {
    value: String,
}

impl RiskAllowEntryIn {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let filter = match self.value.as_str() {
            "long" => EntryFilter::LongOnly,
            "short" => EntryFilter::ShortOnly,
            _ => EntryFilter::All,
        };
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::AllowEntryIn(filter));
        }
        Ok(Value::Na)
    }
}

/// strategy.risk.max_position_size(contracts) — cap the absolute position size.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.max_position_size")]
struct RiskMaxPositionSize {
    contracts: f64,
}

impl RiskMaxPositionSize {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::MaxPositionSize(self.contracts));
        }
        Ok(Value::Na)
    }
}

/// strategy.risk.max_drawdown(value, type) — halt the strategy on this drawdown.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.max_drawdown")]
struct RiskMaxDrawdown {
    value: f64,
    #[arg(default = "percent_of_equity")]
    r#type: String,
    #[arg(default = "")]
    alert_message: String,
}

impl RiskMaxDrawdown {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = &self.alert_message;
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::MaxDrawdown(risk_type(self.value, &self.r#type)));
        }
        Ok(Value::Na)
    }
}

/// strategy.risk.max_intraday_loss(value, type) — halt for the day on this loss.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.max_intraday_loss")]
struct RiskMaxIntradayLoss {
    value: f64,
    #[arg(default = "percent_of_equity")]
    r#type: String,
    #[arg(default = "")]
    alert_message: String,
}

impl RiskMaxIntradayLoss {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = &self.alert_message;
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::MaxIntradayLoss(risk_type(
                self.value,
                &self.r#type,
            )));
        }
        Ok(Value::Na)
    }
}

/// strategy.risk.max_cons_loss_days(count) — halt after N consecutive losing days.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.max_cons_loss_days")]
struct RiskMaxConsLossDays {
    count: f64,
    #[arg(default = "")]
    alert_message: String,
}

impl RiskMaxConsLossDays {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = &self.alert_message;
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::MaxConsLossDays(self.count.max(0.0) as u32));
        }
        Ok(Value::Na)
    }
}

/// strategy.risk.max_intraday_filled_orders(count) — block new orders past a
/// daily fill count.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.risk.max_intraday_filled_orders")]
struct RiskMaxIntradayFilledOrders {
    count: f64,
    #[arg(default = "")]
    alert_message: String,
}

impl RiskMaxIntradayFilledOrders {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = &self.alert_message;
        if let Some(broker) = ctx.broker.as_mut() {
            broker.set_risk(RiskRule::MaxIntradayFilledOrders(self.count.max(0.0) as u32));
        }
        Ok(Value::Na)
    }
}

/// strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, ...)
///
/// Attaches a stop-loss / take-profit bracket to a position. Take-profit is a
/// `limit` price or a `profit` distance in ticks; stop-loss a `stop` price or a
/// `loss` in ticks. The broker fills whichever the bar reaches first (the stop
/// when both do) and cancels the other. Trailing stops are not yet modelled.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.exit")]
struct StrategyExit {
    id: String,
    #[arg(default = "")]
    from_entry: String,
    #[arg(default = None)]
    qty: Option<f64>,
    #[arg(default = None)]
    qty_percent: Option<f64>,
    #[arg(default = None)]
    profit: Option<f64>,
    #[arg(default = None)]
    limit: Option<f64>,
    #[arg(default = None)]
    loss: Option<f64>,
    #[arg(default = None)]
    stop: Option<f64>,
    #[arg(default = None)]
    trail_price: Option<f64>,
    #[arg(default = None)]
    trail_points: Option<f64>,
    #[arg(default = None)]
    trail_offset: Option<f64>,
    #[arg(default = "")]
    comment: String,
}

impl StrategyExit {
    fn execute<O: PineOutput>(&self, ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = &self.comment;
        if let Some(broker) = ctx.broker.as_mut() {
            broker.submit_exit(Exit {
                limit: self.limit,
                profit_ticks: self.profit,
                stop: self.stop,
                loss_ticks: self.loss,
                trail_price: self.trail_price,
                trail_points: self.trail_points,
                trail_offset: self.trail_offset,
                ..Exit::resting(
                    self.id.clone(),
                    non_empty(&self.from_entry),
                    self.qty,
                    self.qty_percent,
                )
            });
        }
        Ok(Value::Na)
    }
}

/// Build the `strategy` namespace object: the callable declaration, the order
/// commands, the direction and sizing constants, and the read-only values the
/// host refreshes each bar (seeded to a flat, zero-profit account).
pub fn register<O: PineOutput>(_version: PineVersion) -> Value<O> {
    let mut fields: HashMap<String, Value<O>> = HashMap::new();

    // Order commands.
    fields.insert("entry".to_string(), StrategyEntry::builtin_value::<O>());
    fields.insert("order".to_string(), StrategyOrder::builtin_value::<O>());
    fields.insert("close".to_string(), StrategyClose::builtin_value::<O>());
    fields.insert(
        "close_all".to_string(),
        StrategyCloseAll::builtin_value::<O>(),
    );
    fields.insert("exit".to_string(), StrategyExit::builtin_value::<O>());
    fields.insert("cancel".to_string(), StrategyCancel::builtin_value::<O>());
    fields.insert(
        "cancel_all".to_string(),
        StrategyCancelAll::builtin_value::<O>(),
    );

    // Direction constants.
    fields.insert("long".to_string(), Value::String("long".to_string()));
    fields.insert("short".to_string(), Value::String("short".to_string()));

    // Sizing constants for `default_qty_type`.
    fields.insert("fixed".to_string(), Value::String("fixed".to_string()));
    fields.insert("cash".to_string(), Value::String("cash".to_string()));
    fields.insert(
        "percent_of_equity".to_string(),
        Value::String("percent_of_equity".to_string()),
    );

    // Commission-type constants (`strategy.commission.*`).
    let mut commission: HashMap<String, Value<O>> = HashMap::new();
    commission.insert("percent".to_string(), Value::String("percent".to_string()));
    commission.insert(
        "cash_per_contract".to_string(),
        Value::String("cash_per_contract".to_string()),
    );
    commission.insert(
        "cash_per_order".to_string(),
        Value::String("cash_per_order".to_string()),
    );
    fields.insert(
        "commission".to_string(),
        Value::Object {
            type_name: "strategy.commission".to_string(),
            fields: Rc::new(RefCell::new(commission)),
            call: None,
        },
    );

    // Entry-direction constants for `strategy.risk.allow_entry_in`.
    let mut direction: HashMap<String, Value<O>> = HashMap::new();
    direction.insert("long".to_string(), Value::String("long".to_string()));
    direction.insert("short".to_string(), Value::String("short".to_string()));
    direction.insert("all".to_string(), Value::String("all".to_string()));
    fields.insert(
        "direction".to_string(),
        Value::Object {
            type_name: "strategy.direction".to_string(),
            fields: Rc::new(RefCell::new(direction)),
            call: None,
        },
    );

    // Risk-management rules (`strategy.risk.*`).
    let mut risk: HashMap<String, Value<O>> = HashMap::new();
    risk.insert(
        "allow_entry_in".to_string(),
        RiskAllowEntryIn::builtin_value::<O>(),
    );
    risk.insert(
        "max_position_size".to_string(),
        RiskMaxPositionSize::builtin_value::<O>(),
    );
    risk.insert(
        "max_drawdown".to_string(),
        RiskMaxDrawdown::builtin_value::<O>(),
    );
    risk.insert(
        "max_intraday_loss".to_string(),
        RiskMaxIntradayLoss::builtin_value::<O>(),
    );
    risk.insert(
        "max_cons_loss_days".to_string(),
        RiskMaxConsLossDays::builtin_value::<O>(),
    );
    risk.insert(
        "max_intraday_filled_orders".to_string(),
        RiskMaxIntradayFilledOrders::builtin_value::<O>(),
    );
    fields.insert(
        "risk".to_string(),
        Value::Object {
            type_name: "strategy.risk".to_string(),
            fields: Rc::new(RefCell::new(risk)),
            call: None,
        },
    );

    // One-Cancels-All type constants (`strategy.oca.*`).
    let mut oca: HashMap<String, Value<O>> = HashMap::new();
    oca.insert("cancel".to_string(), Value::String("cancel".to_string()));
    oca.insert("reduce".to_string(), Value::String("reduce".to_string()));
    oca.insert("none".to_string(), Value::String("none".to_string()));
    fields.insert(
        "oca".to_string(),
        Value::Object {
            type_name: "strategy.oca".to_string(),
            fields: Rc::new(RefCell::new(oca)),
            call: None,
        },
    );

    // Read-only account values, refreshed each bar by the host after the broker
    // advances. Seeded to a flat, zero-profit account.
    for name in [
        "position_size",
        "equity",
        "initial_capital",
        "netprofit",
        "openprofit",
        "grossprofit",
        "grossloss",
        "max_drawdown",
        "max_runup",
    ] {
        fields.insert(name.to_string(), Value::Number(0.0));
    }
    // na while flat, matching Pine.
    fields.insert("position_avg_price".to_string(), Value::Na);
    for name in [
        "opentrades",
        "closedtrades",
        "wintrades",
        "losstrades",
        "eventrades",
    ] {
        fields.insert(name.to_string(), Value::Int(0));
    }

    Value::Object {
        type_name: "strategy".to_string(),
        fields: Rc::new(RefCell::new(fields)),
        call: Some(Rc::new(StrategyFn::builtin_fn) as BuiltinFn<O>),
    }
}