pine-builtins 0.2.2

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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! 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, Trade,
};
use pine_builtin_macro::BuiltinFunction;
use pine_core::{PineOutput, PineVersion};
use pine_interpreter::{Builtin, BuiltinFn, EvaluatedArg, 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)
    }
}

/// strategy.convert_to_account(value) - Convert a value to the account currency.
/// The account and symbol currency are the same here (no FX feed), so this is
/// the identity.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.convert_to_account")]
struct StrategyConvertToAccount {
    value: f64,
}

impl StrategyConvertToAccount {
    fn execute<O: PineOutput>(&self, _ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        Ok(Value::Number(self.value))
    }
}

/// strategy.convert_to_symbol(value) - Convert a value to the symbol currency
/// (identity without an FX feed).
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.convert_to_symbol")]
struct StrategyConvertToSymbol {
    value: f64,
}

impl StrategyConvertToSymbol {
    fn execute<O: PineOutput>(&self, _ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        Ok(Value::Number(self.value))
    }
}

/// strategy.default_entry_qty(fill_price) - The quantity a default-sized entry
/// would use. `na` here, since the default sizing model is not exposed.
#[derive(BuiltinFunction)]
#[builtin(name = "strategy.default_entry_qty")]
struct StrategyDefaultEntryQty {
    fill_price: f64,
}

impl StrategyDefaultEntryQty {
    fn execute<O: PineOutput>(&self, _ctx: &mut Interpreter<O>) -> Result<Value<O>, RuntimeError> {
        let _ = self.fill_price;
        Ok(Value::Na)
    }
}

/// A trade's profit as a percentage of the capital it tied up at entry.
fn profit_percent(trade: &Trade, close: f64) -> f64 {
    let cost = trade.entry_price * trade.size.abs();
    if cost == 0.0 {
        0.0
    } else {
        trade.profit(close) / cost * 100.0
    }
}

/// A `strategy.*trades.<field>(trade_num)` accessor: reads one field off trade
/// `trade_num` of the open or closed log (via the interpreter's broker), or `na`
/// when the index is out of range. `select` also gets the current close, for the
/// open-profit fields.
fn trade_field<O: PineOutput>(open: bool, select: fn(&Trade, f64) -> Value<O>) -> Value<O> {
    Value::BuiltinFunction(Builtin::untyped(Rc::new(
        move |ctx: &mut Interpreter<O>, args| {
            let n = args
                .args
                .first()
                .and_then(|arg| match arg {
                    EvaluatedArg::Positional(v) => v.to_number().ok().flatten(),
                    EvaluatedArg::Named { value, .. } => value.to_number().ok().flatten(),
                })
                .unwrap_or(0.0);
            if n < 0.0 {
                return Ok(Value::Na);
            }
            let close = ctx
                .get_variable("close")
                .and_then(|v| v.to_number().ok().flatten())
                .unwrap_or(f64::NAN);
            let Some(broker) = ctx.broker.as_ref() else {
                return Ok(Value::Na);
            };
            let index = n as usize;
            let selected = if open {
                broker
                    .open_trades()
                    .get(index)
                    .copied()
                    .map(|t| select(t, close))
            } else {
                broker.closed_trades().get(index).map(|t| select(t, close))
            };
            Ok(selected.unwrap_or(Value::Na))
        },
    )))
}

/// The `strategy.closedtrades` object: bare, the number of closed trades; as a
/// namespace, per-trade accessors over the closed log. Time/comment/exit-id and
/// per-trade drawdown/runup are not modelled by the broker, so they are `na`.
fn register_closedtrades<O: PineOutput>() -> Value<O> {
    let mut m: HashMap<String, Value<O>> = HashMap::new();
    m.insert(
        "entry_price".into(),
        trade_field(false, |t, _| Value::Number(t.entry_price)),
    );
    m.insert(
        "entry_bar_index".into(),
        trade_field(false, |t, _| Value::Int(t.entry_bar as i64)),
    );
    m.insert(
        "entry_id".into(),
        trade_field(false, |t, _| Value::String(t.entry_id.clone())),
    );
    m.insert(
        "exit_price".into(),
        trade_field(false, |t, _| {
            t.exit_price.map(Value::Number).unwrap_or(Value::Na)
        }),
    );
    m.insert(
        "exit_bar_index".into(),
        trade_field(false, |t, _| {
            t.exit_bar
                .map(|b| Value::Int(b as i64))
                .unwrap_or(Value::Na)
        }),
    );
    m.insert(
        "size".into(),
        trade_field(false, |t, _| Value::Number(t.size)),
    );
    m.insert(
        "commission".into(),
        trade_field(false, |t, _| Value::Number(t.commission)),
    );
    m.insert(
        "profit".into(),
        trade_field(false, |t, close| Value::Number(t.profit(close))),
    );
    m.insert(
        "profit_percent".into(),
        trade_field(false, |t, close| Value::Number(profit_percent(t, close))),
    );
    for name in [
        "entry_time",
        "entry_comment",
        "exit_time",
        "exit_id",
        "exit_comment",
        "max_drawdown",
        "max_drawdown_percent",
        "max_runup",
        "max_runup_percent",
    ] {
        m.insert(name.into(), trade_field(false, |_, _| Value::Na));
    }
    // The trade number of the first closed trade in the set.
    m.insert("first_index".into(), Value::Int(0));
    Value::Object {
        type_name: "strategy.closedtrades".into(),
        fields: Rc::new(RefCell::new(m)),
        call: None,
        value: Some(Rc::new(|ctx: &mut Interpreter<O>| {
            Ok(Value::Int(
                ctx.broker
                    .as_ref()
                    .map(|b| b.closed_trades().len() as i64)
                    .unwrap_or(0),
            ))
        })),
    }
}

/// The `strategy.opentrades` object: bare, the number of open trades; as a
/// namespace, per-trade accessors over the open log.
fn register_opentrades<O: PineOutput>() -> Value<O> {
    let mut m: HashMap<String, Value<O>> = HashMap::new();
    m.insert(
        "entry_price".into(),
        trade_field(true, |t, _| Value::Number(t.entry_price)),
    );
    m.insert(
        "entry_bar_index".into(),
        trade_field(true, |t, _| Value::Int(t.entry_bar as i64)),
    );
    m.insert(
        "entry_id".into(),
        trade_field(true, |t, _| Value::String(t.entry_id.clone())),
    );
    m.insert(
        "size".into(),
        trade_field(true, |t, _| Value::Number(t.size)),
    );
    m.insert(
        "commission".into(),
        trade_field(true, |t, _| Value::Number(t.commission)),
    );
    m.insert(
        "profit".into(),
        trade_field(true, |t, close| Value::Number(t.profit(close))),
    );
    m.insert(
        "profit_percent".into(),
        trade_field(true, |t, close| Value::Number(profit_percent(t, close))),
    );
    // Capital the open trade ties up: entry price times absolute size.
    m.insert(
        "capital_held".into(),
        trade_field(true, |t, _| Value::Number(t.entry_price * t.size.abs())),
    );
    for name in [
        "entry_time",
        "entry_comment",
        "max_drawdown",
        "max_drawdown_percent",
        "max_runup",
        "max_runup_percent",
    ] {
        m.insert(name.into(), trade_field(true, |_, _| Value::Na));
    }
    Value::Object {
        type_name: "strategy.opentrades".into(),
        fields: Rc::new(RefCell::new(m)),
        call: None,
        value: Some(Rc::new(|ctx: &mut Interpreter<O>| {
            Ok(Value::Int(
                ctx.broker
                    .as_ref()
                    .map(|b| b.open_trades().len() as i64)
                    .unwrap_or(0),
            ))
        })),
    }
}

/// 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,
            value: 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,
            value: 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,
            value: 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,
            value: 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",
        // Percentages and per-trade averages, derived from the broker each bar.
        "netprofit_percent",
        "openprofit_percent",
        "grossprofit_percent",
        "grossloss_percent",
        "max_drawdown_percent",
        "max_runup_percent",
        "max_contracts_held_all",
        "max_contracts_held_long",
        "max_contracts_held_short",
    ] {
        fields.insert(name.to_string(), Value::Number(0.0));
    }
    // na while flat / before any trade, matching Pine.
    fields.insert("position_avg_price".to_string(), Value::Na);
    for name in [
        "avg_trade",
        "avg_trade_percent",
        "avg_winning_trade",
        "avg_winning_trade_percent",
        "avg_losing_trade",
        "avg_losing_trade_percent",
        "margin_liquidation_price",
        "position_entry_name",
    ] {
        fields.insert(name.to_string(), Value::Na);
    }
    fields.insert(
        "account_currency".to_string(),
        Value::String("USD".to_string()),
    );
    fields.insert(
        "convert_to_account".to_string(),
        StrategyConvertToAccount::builtin_value::<O>(),
    );
    fields.insert(
        "convert_to_symbol".to_string(),
        StrategyConvertToSymbol::builtin_value::<O>(),
    );
    fields.insert(
        "default_entry_qty".to_string(),
        StrategyDefaultEntryQty::builtin_value::<O>(),
    );
    for name in ["wintrades", "losstrades", "eventrades"] {
        fields.insert(name.to_string(), Value::Int(0));
    }
    // Both a count (bare) and a namespace of per-trade accessors; the count is
    // read from the broker on use, so the host no longer refreshes it.
    fields.insert("closedtrades".to_string(), register_closedtrades());
    fields.insert("opentrades".to_string(), register_opentrades());

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