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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
//! App state and the event loop. Feed caching with its request-budget
//! guards lives in `feeds`, the settings overlay in `settings`; views under
//! `crate::ui` are stateless renderers over `&mut App`.
mod feeds;
mod runtime;
mod settings;
pub use feeds::{FeedBundle, FeedKind};
pub use settings::{SettingsRow, SettingsState, settings_rows};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use anyhow::Result;
use chrono::{DateTime, Local, NaiveDate, Utc};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::style::Style;
use ratatui::widgets::TableState;
use tokio::sync::Notify;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use crate::alphai::{self, Article};
use crate::config::{self, ChartDefaults, Config, UiDefaults};
use crate::domain::{Interval, Range, Sessions, TickerData};
use crate::indicators::MaType;
use crate::keymap::{Action, Keymap};
use crate::motion;
use crate::poller::{SharedEvery, SharedParams, SharedSource, SharedSymbols, SourceEvent};
use crate::portfolio::{self, Position};
use crate::theme::Theme;
use crate::ui;
pub use crate::motion::PRICE_FLASH;
/// How long every symbol has to be failing before the app looks for another
/// source. Three cycles at the default 15s poll, which is enough to tell a
/// blocked provider from one unlucky round of timeouts, and on a long poll
/// interval it simply means the next cycle.
const FALLBACK_AFTER: Duration = Duration::from_secs(45);
/// How long a footer notice stays up. Long enough to be read on a glance
/// back at the terminal, short enough not to sit on top of the key hints
/// for the rest of the session; the header keeps naming the live source
/// after it fades.
const NOTICE: Duration = Duration::from_secs(60);
/// How the price chart draws history: candlesticks or the classic close line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChartStyle {
Candles,
Line,
}
/// News feed scope the f key cycles: the selected ticker, the whole market
/// (story-collapsed), or the 48h trending top 10. Session-only, like the
/// chart options.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NewsScope {
#[default]
Ticker,
Market,
Trending,
}
impl NewsScope {
pub fn next(self) -> Self {
match self {
Self::Ticker => Self::Market,
Self::Market => Self::Trending,
Self::Trending => Self::Ticker,
}
}
/// Label for block titles and head lines.
pub fn label(self, symbol: &str) -> &str {
match self {
Self::Ticker => symbol,
Self::Market => "market",
Self::Trending => "trending",
}
}
}
/// State of the full-article card overlay (v in the News/Insider views).
#[derive(Default)]
pub struct ArticleOverlay {
pub open: bool,
pub scroll: u16,
/// Set by the view during a frame when it drew the card in place (the
/// News chart layout), so `ui::draw` skips the fullscreen one.
pub inline: bool,
}
/// Which line the one-line prompt is taking.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub enum PromptKind {
/// A ticker for the watchlist (a).
#[default]
Ticker,
/// A holding: quantity and average price, for `Prompt::target` (p).
Position,
}
/// State of the prompt overlay (a and p anywhere). A typed symbol is not
/// validated here: whether it exists is the source's answer, and the row
/// carries that answer already, as a price or as an error.
#[derive(Default)]
pub struct Prompt {
pub open: bool,
pub kind: PromptKind,
pub input: String,
/// The ticker a position line applies to when the line names none.
pub target: String,
/// Set for the cases the prompt itself can rule on, such as a symbol
/// already on the list or a quantity that is not a number.
pub error: Option<String>,
}
/// State of the help overlay (? anywhere): the full key table.
#[derive(Default)]
pub struct HelpOverlay {
pub open: bool,
pub scroll: u16,
}
/// Where the News view puts the article card pane relative to the list
/// (x cycles, and so does the settings row). Seeded from
/// `[ui] news_layout`; Save in the settings screen writes it back.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NewsLayout {
/// List on the left, card on the right.
Side,
/// Side, plus the ticker's chart above the list with the selected
/// article marked on it: the story and the move it went with on one
/// screen. Ticker scope on a wide terminal only; elsewhere it reads as
/// Side, since a market-wide story has no one chart to belong to.
#[default]
Chart,
/// List on top, card below.
Stacked,
}
impl NewsLayout {
/// Every layout in cycle order: the default first.
pub const ALL: [Self; 3] = [Self::Chart, Self::Stacked, Self::Side];
pub fn next(self) -> Self {
self.step(1)
}
/// The neighbour in cycle order, `dir` 1 forward and -1 back, wrapping.
pub fn step(self, dir: isize) -> Self {
let n = Self::ALL.len() as isize;
let i = Self::ALL.iter().position(|l| *l == self).unwrap_or(0) as isize;
Self::ALL[(i + dir).rem_euclid(n) as usize]
}
/// The name `[ui] news_layout` spells it with.
pub fn name(self) -> &'static str {
match self {
Self::Side => "side",
Self::Chart => "chart",
Self::Stacked => "stacked",
}
}
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|l| l.name().eq_ignore_ascii_case(name.trim()))
}
}
/// Window of the Insider view's Form 4 chart panel, cycled by the g key:
/// hidden, trailing 3 months, trailing 12 months. Seeded from
/// `[ui] insider_chart`, then session-only, like the chart options.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InsiderChartWindow {
Off,
#[default]
M3,
M12,
}
impl InsiderChartWindow {
pub fn next(self) -> Self {
match self {
Self::Off => Self::M3,
Self::M3 => Self::M12,
Self::M12 => Self::Off,
}
}
/// Calendar days the window covers; whole weeks, so the weekly bars
/// stay uniform. None = the panel is hidden.
pub fn days(self) -> Option<u32> {
match self {
Self::Off => None,
Self::M3 => Some(91),
Self::M12 => Some(364),
}
}
/// Label for the panel title and the config value.
pub fn label(self) -> &'static str {
match self {
Self::Off => "off",
Self::M3 => "3m",
Self::M12 => "12m",
}
}
}
/// One ticker's earnings reads with the moment they were fetched. Cached far
/// longer than a feed (a read changes once a quarter), so the timestamp lives
/// beside the data rather than in a feed bundle.
pub struct EarningsSlot {
pub data: alphai::TickerEarnings,
pub fetched: Instant,
}
/// The last successful macro response and its requested UTC date window.
pub struct CalendarSlot {
pub events: Vec<alphai::CalendarEvent>,
pub fetched: Instant,
pub from: NaiveDate,
pub to: NaiveDate,
}
/// The default combos the t and T keys cycle through (`[chart] presets`
/// overrides them); wraps at the ends. A startup combo not in the table
/// (e.g. -r 3mo) jumps to the first preset on t and to the last on T.
pub const RANGE_PRESETS: [(Range, Interval); 5] = [
(Range::D1, Interval::M5),
(Range::D5, Interval::M15),
(Range::Mo1, Interval::M60),
(Range::Mo6, Interval::D1),
(Range::Y1, Interval::D1),
];
fn next_preset(
presets: &[(Range, Interval)],
cur: (Range, Interval),
dir: isize,
) -> (Range, Interval) {
let n = presets.len() as isize;
match presets.iter().position(|&p| p == cur) {
Some(i) => presets[((i as isize + dir).rem_euclid(n)) as usize],
None if dir > 0 => presets[0],
None => presets[presets.len() - 1],
}
}
pub struct AppInit {
pub symbols: Vec<String>,
/// Validated `[[positions]]`; empty when the section is absent.
pub positions: Vec<Position>,
pub shared_symbols: SharedSymbols,
pub source: SharedSource,
pub source_name: &'static str,
pub range: Range,
pub interval: Interval,
/// Whether the chart draws the pre and post market candles too.
pub sessions: Sessions,
pub params: SharedParams,
pub every: SharedEvery,
pub rx: UnboundedReceiver<SourceEvent>,
pub refresh: Arc<Notify>,
pub alphai_tx: UnboundedSender<alphai::Cmd>,
pub config: Config,
/// Where Save writes the config back; None disables persisting.
pub config_path: Option<PathBuf>,
pub theme: Theme,
pub theme_name: &'static str,
pub chart: ChartDefaults,
pub ui: UiDefaults,
/// Resolved from `[keybindings]` (defaults when the section is absent).
pub keymap: Keymap,
pub alphai_enabled: bool,
pub first_run: bool,
/// Whether a source that stops answering may be swapped for one that
/// still does (`source_fallback` in the config).
pub source_fallback: bool,
}
pub struct App {
pub symbols: Vec<String>,
/// What the user holds, in config order. Off-watchlist holdings are
/// polled too (`polled_symbols`), so every row can be valued.
pub positions: Vec<Position>,
pub data: HashMap<String, TickerData>,
pub errors: HashMap<String, String>,
/// The window each entry of `errors` was asked for, so a failure of the
/// old window is not read as the new one's until it is actually tried
/// (see `window_failed`). Kept beside `errors` rather than in it: the
/// message is what every view reads, and tests set it plainly.
error_window: HashMap<String, (Range, Interval, Sessions)>,
/// When a poll changed a symbol's price: (moment, tick was up). Views
/// pulse the price for `PRICE_FLASH` after it via `price_flash_dir`;
/// the first data a symbol ever gets sets no flash (nothing changed).
pub price_flash: HashMap<String, (Instant, bool)>,
pub animations: bool,
pub synchronized_output: bool,
price_refreshing: bool,
animation_epoch: Instant,
/// Symbols whose rows came off disk or from an abandoned source,
/// with the unix second they were fetched. The rail
/// badges them so a blocked source never passes old prices off as live;
/// the first real poll of a symbol clears its entry.
pub from_cache: HashMap<String, i64>,
/// Last successful fetch per symbol, for labelling retained prices
/// when a fallback changes the source before new quotes arrive.
quote_fetched: HashMap<String, i64>,
/// Since when every symbol on the watchlist has been failing. The
/// fallback is measured from here; any successful poll clears it.
pub(crate) source_trouble_since: Option<Instant>,
/// Sources this session has already given up on, so a fallback never
/// walks back into the one that just failed.
abandoned: Vec<&'static str>,
/// Whether an unusable source may be swapped for a working one
/// (`source_fallback` in the config).
pub(crate) source_fallback: bool,
/// Set once there is nothing left to fall back to: without it the app
/// would rebuild every source on every frame of a long outage. Cleared
/// whenever the user picks a source themselves.
fallback_exhausted: bool,
/// A short-lived line for the footer: what the app did on its own, such
/// as switching source. Errors have their own place; this is for
/// actions, and it fades.
pub notice: Option<(String, Instant)>,
pub selected: usize,
pub view_idx: usize,
pub source_name: &'static str,
/// How stale the active source's prices are (`DataSource::delay_note`),
/// re-read whenever the settings screen swaps the source. The quote
/// rail badges it so a delayed price is never read as a live one.
pub source_delay: Option<&'static str>,
/// Whether the source has extended-hours candles at all, cached like
/// `source_delay` (see `extended_unavailable`).
pub source_extended: bool,
/// A test's frozen clock, read through `now`. The app itself always
/// runs on the wall clock.
#[cfg(test)]
pub(crate) frozen_now: Option<DateTime<Utc>>,
pub range: Range,
pub interval: Interval,
/// Whether the chart draws the pre and post market candles too.
pub sessions: Sessions,
/// The window each symbol's candles were fetched for. A preset or
/// session switch changes `range`/`interval`/`sessions` at once, but
/// the rows only follow when the poller answers, which on a paged
/// source takes seconds. Until then the chart draws the rows on their
/// own window (see `chart_window`) rather than relabelling them.
data_window: HashMap<String, (Range, Interval, Sessions)>,
pub last_update: Option<DateTime<Local>>,
pub table_state: TableState,
/// The portfolio view's own cursor: its rows are the positions, which
/// are neither the watchlist nor in its order.
pub portfolio_selected: usize,
pub portfolio_state: TableState,
// Chart options: seeded from [chart], then session-only toggles
pub chart_style: ChartStyle,
pub show_sma: bool,
pub show_rsi: bool,
pub show_volume: bool,
/// Whether the price chart marks the ticker's news on its candles
/// (`n`, `[chart] news_markers`). The marks are drawn from the feed
/// already in the cache, so they never cost a request.
pub show_news_markers: bool,
pub ma_type: MaType,
/// Validated [chart] values: indicator periods and the t/T preset cycle.
pub chart: ChartDefaults,
// AlphAI feed state: every fetched feed by cache key (news under the
// symbol/market/trending keys, insider under `ins:SYM`)
pub feeds: HashMap<String, FeedBundle>,
/// Uids the reader has had under the cursor, plus the baseline of each
/// feed's first fetch, by feed cache key. Rows outside this set are new
/// since the user last looked and render the unseen marker; resting the
/// cursor on a row retires it (`mark_selected_seen`). Session-only and
/// survives bundle replacement, so markers live through TTL refetches
/// and manual `r`.
pub feed_seen: HashMap<String, HashSet<String>>,
pub alphai_errors: HashMap<String, String>,
pub alphai_enabled: bool,
pub news_selected: usize,
pub news_scope: NewsScope,
pub news_layout: NewsLayout,
/// Minimum relevance score in the ticker and market news feeds (1..=10,
/// applied server-side). Seeded from `[ui] news_min_score`, then
/// session-only via +/-, like the scope and layout.
pub news_min_score: u8,
/// Same for the insider feed, where the score tracks the trade size, so
/// this filters by dollar value. Seeded from `[ui] insider_min_score`;
/// +/- adjust whichever feed the visible view shows.
pub insider_min_score: u8,
/// Window of the Insider view's chart panel (g cycles off/3m/12m).
pub insider_chart: InsiderChartWindow,
/// The Insider view's card column beside the filing list; v toggles it.
/// Session-only, on at start.
pub insider_card: bool,
/// Set by the Insider view each frame: whether the terminal is wide
/// enough for that column, so v knows whether to toggle it or fall back
/// to the fullscreen card.
pub insider_card_fits: bool,
/// Whether the quote rail is drawn (`[ui] quote_rail`).
pub show_rail: bool,
/// Bare mode (`z`, `--bare`, `[ui] bare`): the header and footer give
/// their rows to the view. For a tmux pane, which carries its own
/// status bar and needs the rows more than it needs the app's chrome.
pub bare: bool,
/// Earnings reads by symbol, each with the moment it was fetched. Its
/// own map rather than a feed bundle: the payload has no pagination, no
/// sort and no score filter, and it outlives a feed's TTL by an order of
/// magnitude (a read changes once a quarter).
pub earnings: HashMap<String, EarningsSlot>,
/// The macro calendar window and when it landed. One market-wide payload
/// for every ticker, so it is not keyed by symbol.
pub calendar: Option<CalendarSlot>,
pub calendar_selection: ui::calendar::Selection,
pub calendar_state: TableState,
pub(crate) calendar_refresh_requested: bool,
pub(crate) report_date_asked: Option<Instant>,
pub(crate) report_date_retry: HashSet<String>,
pub(crate) report_dates_paused: Option<String>,
/// SetKey acknowledgements form a barrier against old-key responses.
pub(crate) alphai_key_pending: usize,
/// Scroll of the Earnings view's body; reset when the ticker changes.
pub earnings_scroll: u16,
/// How long a fetched AlphAI bundle stays fresh. Seeded from
/// `[ui] alphai_ttl_secs` (default `alphai::CACHE_TTL`), file-only.
pub alphai_ttl: Duration,
/// Scroll of the embedded card pane (News view); reset on selection moves.
pub card_scroll: u16,
pub news_table_state: TableState,
pub article_overlay: ArticleOverlay,
pub help: HelpOverlay,
pub settings: SettingsState,
pub prompt: Prompt,
/// The watchlist as the price poller sees it; kept in step with
/// `symbols` by `add_symbol` and `remove_selected_symbol`.
pub shared_symbols: SharedSymbols,
/// Whether `a` and `d` write the watchlist to the config. False for a
/// session started on tickers from the command line while the file
/// holds a list of its own (see `persist_watchlist`).
pub watchlist_saved: bool,
pub config: Config,
pub config_path: Option<PathBuf>,
pub theme: Theme,
/// The preset `theme` was built from. The cycle key and the settings
/// row move this name and rebuild the theme from it, so what is on
/// screen always matches what the same name would give after a
/// restart (explicit `[theme]` slots included).
pub theme_name: &'static str,
pub keymap: Keymap,
source: SharedSource,
/// The fetch window the poller re-reads each cycle. Public like the
/// shared watchlist: what the keys push into it is the behaviour worth
/// asserting on, not the field they set on `App`.
pub params: SharedParams,
/// The poll interval the poller re-reads before every sleep; the
/// settings screen edits it live.
every: SharedEvery,
inflight: HashSet<String>,
alphai_tx: UnboundedSender<alphai::Cmd>,
rx: UnboundedReceiver<SourceEvent>,
refresh: Arc<Notify>,
}
impl App {
pub fn new(init: AppInit) -> Self {
let source_delay = init.source.read().unwrap().delay_note();
let source_extended = init.source.read().unwrap().extended_candles();
let watchlist_saved = watchlist_is_saved(&init.config.watchlist, &init.symbols);
let mut app = Self {
watchlist_saved,
symbols: init.symbols,
shared_symbols: init.shared_symbols,
prompt: Prompt::default(),
data: HashMap::new(),
errors: HashMap::new(),
error_window: HashMap::new(),
price_flash: HashMap::new(),
animations: init.ui.animations,
synchronized_output: init.ui.synchronized_output,
price_refreshing: false,
animation_epoch: Instant::now(),
from_cache: HashMap::new(),
quote_fetched: HashMap::new(),
source_trouble_since: None,
abandoned: Vec::new(),
source_fallback: init.source_fallback,
fallback_exhausted: false,
notice: None,
selected: 0,
view_idx: init.ui.view_idx,
source_name: init.source_name,
source_delay,
source_extended,
#[cfg(test)]
frozen_now: None,
range: init.range,
interval: init.interval,
sessions: init.sessions,
data_window: HashMap::new(),
last_update: None,
table_state: TableState::default(),
chart_style: init.chart.style,
show_sma: init.chart.sma,
show_rsi: init.chart.rsi,
show_volume: init.chart.volume,
show_news_markers: init.chart.news_markers,
ma_type: init.chart.ma_type,
chart: init.chart,
feeds: HashMap::new(),
feed_seen: HashMap::new(),
alphai_errors: HashMap::new(),
alphai_enabled: init.alphai_enabled,
news_selected: 0,
news_scope: init.ui.news_scope,
news_layout: init.ui.news_layout,
news_min_score: init.ui.news_min_score,
insider_min_score: init.ui.insider_min_score,
insider_chart: init.ui.insider_chart,
insider_card: true,
insider_card_fits: false,
show_rail: init.ui.quote_rail,
bare: init.ui.bare,
earnings: HashMap::new(),
calendar: None,
calendar_selection: ui::calendar::Selection::default(),
calendar_state: TableState::default(),
calendar_refresh_requested: false,
report_date_asked: None,
report_date_retry: HashSet::new(),
report_dates_paused: None,
alphai_key_pending: 0,
earnings_scroll: 0,
alphai_ttl: init.ui.alphai_ttl,
card_scroll: 0,
news_table_state: TableState::default(),
positions: init.positions,
portfolio_selected: 0,
portfolio_state: TableState::default(),
article_overlay: ArticleOverlay::default(),
help: HelpOverlay::default(),
settings: SettingsState::default(),
config: init.config,
config_path: init.config_path,
theme: init.theme,
theme_name: init.theme_name,
keymap: init.keymap,
source: init.source,
params: init.params,
every: init.every,
inflight: HashSet::new(),
alphai_tx: init.alphai_tx,
rx: init.rx,
refresh: init.refresh,
};
if init.first_run {
app.open_settings();
app.settings.first_run = true;
}
app
}
pub fn selected_symbol(&self) -> &str {
&self.symbols[self.selected]
}
/// Puts one ticker's last-good rows on screen before the first poll
/// lands. Marked as cached until that poll replaces them, so the age of
/// what is on screen is never a guess.
pub fn seed_cached(&mut self, symbol: String, entry: crate::cache::Entry) {
self.quote_fetched.insert(symbol.clone(), entry.fetched);
self.from_cache.insert(symbol.clone(), entry.fetched);
// The store only hands out rows saved for the starting window.
self.data_window.insert(symbol.clone(), self.window());
self.data.insert(symbol, entry.data);
}
fn window(&self) -> (Range, Interval, Sessions) {
(self.range, self.interval, self.sessions)
}
/// The window to draw `symbol`'s candles on, and whether a different
/// one is on its way. Rows are drawn on the window they were fetched
/// for: drawn on the new one, 15m bars read as hours and the axis
/// extrapolates the wrong step until the poller answers.
pub fn chart_window(&self, symbol: &str) -> ((Range, Interval, Sessions), bool) {
let current = self.window();
let Some(&drawn) = self.data_window.get(symbol) else {
return (current, false);
};
let pending = drawn.0 != current.0
|| drawn.1 != current.1
|| (drawn.2 != current.2 && sessions_matter(symbol, current.1));
(if pending { drawn } else { current }, pending)
}
/// Whether the window on the keys was tried for `symbol` and refused.
/// An error left over from the previous window says nothing about the
/// one on its way: after a preset change that symbol is loading again.
pub fn window_failed(&self, symbol: &str) -> bool {
self.error_window.get(symbol) == Some(&self.window())
}
/// How old the retained rows are, as a label.
pub fn cached_age(&self, symbol: &str) -> Option<String> {
self.from_cache
.get(symbol)
.map(|at| crate::cache::age_label(*at))
}
/// The still-current footer notice, if it has not faded yet.
pub fn notice(&self) -> Option<&str> {
self.notice
.as_ref()
.filter(|(_, at)| at.elapsed() < NOTICE)
.map(|(text, _)| text.as_str())
}
/// The still-active price pulse of a symbol: Some(tick was up) for
/// `PRICE_FLASH` after a poll changed its price, then None.
pub fn price_flash_dir(&self, symbol: &str) -> Option<bool> {
self.price_flash
.get(symbol)
.filter(|(at, _)| self.animations && at.elapsed() < PRICE_FLASH)
.map(|&(_, up)| up)
}
pub fn price_style(&self, symbol: &str, base: Style) -> Style {
let Some(up) = self.price_flash_dir(symbol) else {
return base;
};
let elapsed = self.price_flash[symbol].0.elapsed();
motion::pulse(
base,
if up { self.theme.up } else { self.theme.down },
elapsed,
PRICE_FLASH,
)
}
pub fn refreshing(&self) -> bool {
self.price_refreshing || !self.inflight.is_empty()
}
/// A fixed-width ASCII cell, including when idle or motion is off.
pub fn refresh_marker(&self) -> char {
if !self.refreshing() {
' '
} else if self.animations {
motion::spinner(self.animation_epoch.elapsed())
} else {
'*'
}
}
/// Identity of the visible view (its `view_idx` is the tab position).
pub fn view_id(&self) -> ui::ViewId {
ui::VIEWS[self.view_idx].id()
}
pub(crate) fn apply(&mut self, event: SourceEvent) {
match event {
SourceEvent::Refreshing { source, active } => {
if Arc::ptr_eq(&source, &self.price_source()) {
self.price_refreshing = active;
}
}
SourceEvent::Data {
params,
source,
symbol,
mut data,
} => {
if !self.accepts_price_event(&source, &symbol)
|| params.is_some_and(|p| p != (self.range, self.interval, self.sessions))
{
return;
}
self.errors.remove(&symbol);
self.error_window.remove(&symbol);
self.quote_fetched
.insert(symbol.clone(), chrono::Utc::now().timestamp());
// A live answer clears the outage clock and retires the
// cached rows this symbol started on.
self.source_trouble_since = None;
let was_cached = self.from_cache.remove(&symbol).is_some();
// A successful but partial response must not make a known
// current-session print disappear. Its original timestamp
// and reference close remain visible; a new session retires it.
if let Some(old) = self.data.get(&symbol)
&& old.quote.timing.extended.is_some()
&& old.quote.extended_price().is_some()
&& data.quote.extended_price().is_none()
{
data.quote.extended = old.quote.extended;
data.quote.timing.extended = old.quote.timing.extended;
data.quote.timing.extended_feed = old.quote.timing.extended_feed;
data.quote.timing.extended_reference = Some(old.quote.extended_reference());
}
if let Some(old) = self.data.get(&symbol)
&& old.quote.price != data.quote.price
// The first real price after a cached one is not a tick:
// pulsing it would report yesterday's move as just now.
&& !was_cached
&& self.animations
{
self.price_flash.insert(
symbol.clone(),
(Instant::now(), data.quote.price > old.quote.price),
);
}
data.update_current_bar(self.interval);
self.data_window
.insert(symbol.clone(), params.unwrap_or(self.window()));
self.data.insert(symbol, data);
self.last_update = Some(Local::now());
}
SourceEvent::Error {
params,
source,
symbol,
error,
} => {
if !self.accepts_price_event(&source, &symbol)
|| params.is_some_and(|p| p != (self.range, self.interval, self.sessions))
{
return;
}
self.error_window.insert(symbol.clone(), self.window());
self.errors.insert(symbol, error);
self.last_update = Some(Local::now());
// One failing ticker is a bad symbol; all of them is the
// source, and that is what the fallback waits on.
if self.source_trouble_since.is_none() && self.all_prices_failing() {
self.source_trouble_since = Some(Instant::now());
}
}
SourceEvent::Alphai(ev) => self.apply_alphai(ev),
}
}
fn accepts_price_event(
&self,
source: &Arc<dyn crate::source::DataSource>,
symbol: &str,
) -> bool {
// Name alone cannot distinguish rebuilt credentials for the same
// provider. Pending responses retain the exact source instance.
Arc::ptr_eq(source, &self.price_source())
&& self
.shared_symbols
.read()
.unwrap()
.iter()
.any(|s| s == symbol)
}
pub(crate) fn price_source(&self) -> Arc<dyn crate::source::DataSource> {
self.source.read().unwrap().clone()
}
fn all_prices_failing(&self) -> bool {
let symbols = self.shared_symbols.read().unwrap();
!symbols.is_empty() && symbols.iter().all(|s| self.errors.contains_key(s))
}
/// State shared by manual and automatic source changes. The caller
/// decides whether to retain quotes and reset the fallback history.
fn set_price_source(&mut self, source: Arc<dyn crate::source::DataSource>) {
self.source_name = source.name();
self.source_delay = source.delay_note();
self.source_extended = source.extended_candles();
*self.source.write().unwrap() = source;
self.errors.clear();
self.error_window.clear();
self.source_trouble_since = None;
self.price_flash.clear();
self.price_refreshing = false;
self.notice = None;
self.refresh.notify_one();
}
/// Swaps a source that has stopped answering for one that has not.
///
/// Yahoo, the keyless default, blocks by IP for tens of minutes at a
/// time and no retry can shorten that, so the only real repair is a
/// different provider. The swap waits for every symbol to be failing
/// (one bad ticker is a bad ticker) and for `FALLBACK_AFTER` on top of
/// that, keeps the rows that are on screen, and says what it did. It
/// never switches back on its own: probing a throttled source is how
/// the block gets extended, and the header names the source anyway.
pub(crate) fn fallback_if_stuck(&mut self) {
if !self.source_fallback || self.fallback_exhausted || self.settings.open {
return;
}
// The polled symbols can change while the grace period runs.
if !self.all_prices_failing() {
self.source_trouble_since = None;
return;
}
let Some(since) = self.source_trouble_since else {
return;
};
if since.elapsed() < FALLBACK_AFTER {
return;
}
let Some(src) = self.fallback_source() else {
// Nothing else is configured: stop looking until the user picks
// a source themselves, or this rebuilds a client every frame.
self.fallback_exhausted = true;
return;
};
let failed = self.source_name;
self.abandoned.push(failed);
self.from_cache.extend(self.quote_fetched.clone());
self.set_price_source(src);
let name = self.source_name;
self.notice = Some((
format!("{failed} stopped answering, switched to {name} (s to choose another)"),
Instant::now(),
));
}
/// The first registered source that is not the current one, has not
/// already failed this session, and has the credentials it needs.
fn fallback_source(&self) -> Option<Arc<dyn crate::source::DataSource>> {
crate::source::registry::SOURCES
.iter()
.filter(|info| {
!info.id.eq_ignore_ascii_case(self.source_name)
&& !self.abandoned.contains(&info.id)
})
.find_map(|info| crate::source::make_source(info.id, &self.config).ok())
}
/// Returns true when the app should quit. Fixed keys resolve first
/// (Ctrl-C, Esc, the positional 1-9 digits); everything else goes
/// through the keymap and dispatches on `Action`, with the same view
/// guards the raw keys used — a remap can never bypass them.
pub(crate) fn handle_key(&mut self, key: KeyEvent) -> bool {
if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
return true;
}
if self.prompt.open {
return self.handle_prompt_key(key);
}
if self.settings.open {
return self.handle_settings_key(key);
}
if self.article_overlay.open {
return self.handle_overlay_key(key);
}
if self.help.open {
return self.handle_help_key(key);
}
if key.code == KeyCode::Esc {
return true;
}
if let KeyCode::Char(c @ '1'..='9') = key.code {
let idx = c as usize - '1' as usize;
if idx < ui::VIEWS.len() {
self.switch_view(idx);
}
return false;
}
let news_view = ui::VIEWS[self.view_idx].navigates_articles();
let chart_view = ui::VIEWS[self.view_idx].has_chart_panel();
let earnings_view = ui::VIEWS[self.view_idx].shows_earnings();
let calendar_view = ui::VIEWS[self.view_idx].shows_calendar();
// ←→ walk the watchlist wherever the view is scoped to one ticker.
let lr_ticker = news_view || earnings_view;
let news_feed = ui::VIEWS[self.view_idx].feed_shown() == Some(FeedKind::News);
let any_feed = ui::VIEWS[self.view_idx].feed_shown().is_some();
let Some(action) = self.keymap.resolve(&key) else {
return false;
};
match action {
Action::Quit => return true,
Action::AddTicker => {
self.prompt = Prompt {
open: true,
..Default::default()
}
}
Action::RemoveTicker => self.remove_selected_symbol(),
Action::Position => self.open_position_prompt(),
Action::NextView => self.switch_view((self.view_idx + 1) % ui::VIEWS.len()),
Action::PrevView => {
self.switch_view((self.view_idx + ui::VIEWS.len() - 1) % ui::VIEWS.len())
}
Action::Settings => self.open_settings(),
Action::Help => {
self.help = HelpOverlay {
open: true,
scroll: 0,
}
}
Action::Refresh => self.manual_refresh(),
Action::Up if calendar_view => self.move_calendar(-1),
Action::Down if calendar_view => self.move_calendar(1),
Action::PageUp if calendar_view => self.move_calendar(-10),
Action::PageDown if calendar_view => self.move_calendar(10),
Action::Open if calendar_view => self.open_calendar_row(),
// News/Insider: up/down scroll articles, left/right switch ticker.
Action::Up if news_view => {
self.news_selected = self.news_selected.saturating_sub(1);
self.card_scroll = 0;
}
Action::Down if news_view => {
let max = self.visible_articles().map_or(0, <[Article]>::len);
if self.news_selected + 1 < max {
self.news_selected += 1;
self.card_scroll = 0;
} else {
// Already on the last row: page the feed instead.
self.request_more_articles();
}
}
Action::Left if lr_ticker => self.select_symbol(self.selected.saturating_sub(1)),
Action::Right if lr_ticker => {
self.select_symbol((self.selected + 1).min(self.symbols.len() - 1))
}
// The earnings body is a document: up/down scroll it, and these
// arms must stay above the unguarded ones at the end of the
// match, which move the watchlist selection instead.
Action::Up if earnings_view => {
self.earnings_scroll = self.earnings_scroll.saturating_sub(1)
}
Action::Down if earnings_view => {
self.earnings_scroll = self.earnings_scroll.saturating_add(1)
}
// Card pane scrolling (the list keeps up/down).
Action::PageUp if earnings_view => {
self.earnings_scroll = self.earnings_scroll.saturating_sub(10)
}
Action::PageDown if earnings_view => {
self.earnings_scroll = self.earnings_scroll.saturating_add(10)
}
Action::PageUp if news_view => self.card_scroll = self.card_scroll.saturating_sub(10),
Action::PageDown if news_view => self.card_scroll = self.card_scroll.saturating_add(10),
Action::CycleLayout if self.view_id() == ui::ViewId::News => {
self.news_layout = self.news_layout.next();
self.card_scroll = 0;
}
Action::Open if news_view => {
if let Some(a) = self
.visible_articles()
.and_then(|list| list.get(self.news_selected))
{
open_url(&self.article_url(a));
}
}
// The read's own page on alphai.io, which also links the filing.
// The payload carries no source URL of its own, so this ignores
// the "open the original source" setting.
Action::Open if earnings_view => {
if let Some(url) = ui::earnings::open_url(self) {
open_url(&url);
}
}
// Insider: v shows and hides the card column beside the list,
// where there is room for one.
Action::Card if self.view_id() == ui::ViewId::Insider && self.insider_card_fits => {
self.insider_card = !self.insider_card;
self.card_scroll = 0;
}
Action::Card
if news_view && self.visible_articles().is_some_and(|list| !list.is_empty()) =>
{
self.article_overlay = ArticleOverlay {
open: true,
..Default::default()
};
}
Action::CycleScope if news_feed => {
self.news_scope = self.news_scope.next();
self.news_selected = 0;
self.card_scroll = 0;
}
Action::InsiderChart if self.view_id() == ui::ViewId::Insider => {
self.insider_chart = self.insider_chart.next();
}
Action::ScoreUp if any_feed => self.adjust_min_score(1),
Action::ScoreDown if any_feed => self.adjust_min_score(-1),
Action::ChartStyle if chart_view => {
self.chart_style = match self.chart_style {
ChartStyle::Candles => ChartStyle::Line,
ChartStyle::Line => ChartStyle::Candles,
}
}
Action::ToggleSma if chart_view => self.show_sma = !self.show_sma,
Action::ToggleRsi if chart_view => self.show_rsi = !self.show_rsi,
Action::ToggleVolume if chart_view => self.show_volume = !self.show_volume,
Action::NewsMarkers if chart_view => self.show_news_markers = !self.show_news_markers,
Action::MaType if chart_view => {
self.ma_type = match self.ma_type {
MaType::Sma => MaType::Ema,
MaType::Ema => MaType::Sma,
}
}
Action::NextPreset => self.cycle_range(1),
Action::PrevPreset => self.cycle_range(-1),
Action::ToggleBare => self.bare = !self.bare,
Action::ToggleExtended => self.toggle_sessions(),
Action::NextTheme => self.cycle_theme(1),
Action::PrevTheme => self.cycle_theme(-1),
Action::Up if self.view_id() == ui::ViewId::Portfolio => self.move_portfolio(-1),
Action::Down if self.view_id() == ui::ViewId::Portfolio => self.move_portfolio(1),
Action::Up => self.selected = self.selected.saturating_sub(1),
Action::Down => self.selected = (self.selected + 1).min(self.symbols.len() - 1),
_ => {}
}
false
}
/// Keys while the article card overlay is open; it swallows everything so
/// list navigation does not shift under the reader. Esc always closes.
fn handle_overlay_key(&mut self, key: KeyEvent) -> bool {
if key.code == KeyCode::Esc {
self.article_overlay = ArticleOverlay::default();
return false;
}
match self.keymap.resolve(&key) {
Some(Action::Quit) => return true,
Some(Action::Card) => self.article_overlay = ArticleOverlay::default(),
Some(Action::Up) => {
self.article_overlay.scroll = self.article_overlay.scroll.saturating_sub(1)
}
// The render pass clamps the scroll to the card's real height.
Some(Action::Down) => {
self.article_overlay.scroll = self.article_overlay.scroll.saturating_add(1)
}
Some(Action::PageUp) => {
self.article_overlay.scroll = self.article_overlay.scroll.saturating_sub(10)
}
Some(Action::PageDown) => {
self.article_overlay.scroll = self.article_overlay.scroll.saturating_add(10)
}
Some(Action::Open) => {
if let Some(a) = self
.visible_articles()
.and_then(|list| list.get(self.news_selected))
{
open_url(&self.article_url(a));
}
}
_ => {}
}
false
}
/// Keys while the help overlay is open; like the article card it swallows
/// everything. Esc or ? closes, q still quits.
/// Keys while the add-ticker prompt is open. It swallows everything,
/// the settings pattern, so typing "d" is a letter rather than the
/// remove action.
fn handle_prompt_key(&mut self, key: KeyEvent) -> bool {
// Tickers are short; a position line carries two numbers as well.
// The caps are there so a stuck key cannot grow the line past its
// box.
let cap = match self.prompt.kind {
PromptKind::Ticker => 16,
PromptKind::Position => 32,
};
match key.code {
KeyCode::Esc => self.prompt = Prompt::default(),
KeyCode::Enter => match self.commit_prompt() {
Ok(()) => self.prompt = Prompt::default(),
Err(msg) => self.prompt.error = Some(msg),
},
KeyCode::Backspace => {
self.prompt.input.pop();
self.prompt.error = None;
}
// The readline gesture for "start over". The position prompt
// opens prefilled with what is held, so clearing the line is a
// common move rather than an exotic one.
KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
self.prompt.input.clear();
self.prompt.error = None;
}
// Modified keys are gestures, not text: ctrl-h used to arrive
// as a plain "h" and land in the middle of a quantity.
KeyCode::Char(c)
if !key
.modifiers
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
&& self.prompt.input.chars().count() < cap =>
{
self.prompt.input.push(c);
self.prompt.error = None;
}
_ => {}
}
false
}
fn commit_prompt(&mut self) -> Result<(), String> {
let typed = self.prompt.input.clone();
match self.prompt.kind {
PromptKind::Ticker => self.add_symbol(typed.trim().to_uppercase().as_str()),
PromptKind::Position => {
let target = self.prompt.target.clone();
let entry = portfolio::parse_entry(&typed, &target)?;
self.apply_position(entry)
}
}
}
/// Opens the position prompt on the ticker in front of the reader: the
/// row under the portfolio cursor in that view, the selected ticker
/// anywhere else. Prefilled with what is held already, so correcting a
/// number is not a retype, and an emptied line clears the holding.
fn open_position_prompt(&mut self) {
let target = self.position_target();
let input = self
.position(&target)
.map(|p| format!("{} {}", p.qty, p.avg_price))
.unwrap_or_default();
self.prompt = Prompt {
open: true,
kind: PromptKind::Position,
input,
target,
error: None,
};
}
fn position_target(&self) -> String {
if self.view_id() == ui::ViewId::Portfolio
&& let Some(p) = self.positions.get(self.portfolio_selected)
{
return p.symbol.clone();
}
self.selected_symbol().to_string()
}
pub fn position(&self, symbol: &str) -> Option<&Position> {
self.positions.iter().find(|p| p.symbol == symbol)
}
/// Moves the portfolio cursor, and the watchlist cursor with it when
/// the row's ticker is on the watchlist: the rail sits above every
/// view and would otherwise quote a different ticker than the row the
/// cursor is on.
fn move_portfolio(&mut self, dir: isize) {
if self.positions.is_empty() {
return;
}
let last = self.positions.len() as isize - 1;
let next = (self.portfolio_selected as isize + dir).clamp(0, last) as usize;
self.portfolio_selected = next;
let symbol = self.positions[next].symbol.clone();
if let Some(at) = self.symbols.iter().position(|s| *s == symbol) {
self.select_symbol(at);
}
}
/// Writes a position through and saves it. Like the watchlist keys, and
/// unlike the display options, it does not wait for Save in the
/// settings screen: a quantity and a price someone typed are their
/// data, not a display preference, and losing them on quit would read
/// as a bug.
fn apply_position(&mut self, entry: portfolio::Entry) -> Result<(), String> {
match entry {
portfolio::Entry::Set {
symbol,
qty,
avg_price,
} => {
let next = Position {
symbol,
qty,
avg_price,
};
match self.positions.iter_mut().find(|p| p.symbol == next.symbol) {
Some(slot) => *slot = next,
None => self.positions.push(next),
}
}
portfolio::Entry::Clear { symbol } => self.positions.retain(|p| p.symbol != symbol),
}
self.portfolio_selected = self
.portfolio_selected
.min(self.positions.len().saturating_sub(1));
// A holding off the watchlist is polled too, and the nudge saves
// the new row a full interval of waiting for its first price.
self.sync_shared_symbols();
self.refresh.notify_one();
self.persist_positions()
}
/// Saves the positions into the config file, leaving every other
/// section as it was loaded. Deliberately not `settings_merged_config`:
/// that one also persists the live watchlist and the settings rows,
/// which nobody asked this keypress to do.
fn persist_positions(&mut self) -> Result<(), String> {
self.config.positions = self.positions.clone();
if self.config_path.is_none() {
return Ok(());
}
config::save_at(self.config_path.as_deref(), &self.config)
.map_err(|e| format!("kept for this session only: {e}"))
}
/// Writes the watchlist through after `a` or `d`, the way a holding is:
/// a ticker someone added is their data, and losing it on quit read as
/// a bug. A session started on tickers from the command line is left
/// alone while the file holds another list, or `alphai-tui TSLA` and
/// one keypress would replace the saved watchlist with two tickers.
/// Save in the settings screen still keeps such a list on purpose.
fn persist_watchlist(&mut self) {
if !self.watchlist_saved {
self.notice = Some((
"Tickers from the command line are not saved (s, then Save, keeps them)".into(),
Instant::now(),
));
return;
}
self.config.watchlist = self.symbols.clone();
if self.config_path.is_none() {
return;
}
if let Err(e) = config::save_at(self.config_path.as_deref(), &self.config) {
self.notice = Some((
format!("Watchlist kept for this session only: {e}"),
Instant::now(),
));
}
}
/// Adds a symbol to the live watchlist, selects it and saves the list.
/// The poller reads the shared list at the top of its next cycle, and
/// the nudge makes that cycle start now instead of up to one interval
/// later.
fn add_symbol(&mut self, symbol: &str) -> Result<(), String> {
if symbol.is_empty() {
return Err("type a ticker, e.g. AAPL".into());
}
if let Some(at) = self.symbols.iter().position(|s| s == symbol) {
// Not an error worth dwelling on: put the cursor where the
// ticker already is, and say why nothing was added.
self.select_symbol(at);
return Err(format!("{symbol} is already on the watchlist"));
}
self.symbols.push(symbol.to_string());
self.sync_shared_symbols();
self.select_symbol(self.symbols.len() - 1);
self.refresh.notify_one();
self.persist_watchlist();
Ok(())
}
/// Drops the selected symbol. The last one stays: every view reads
/// `selected_symbol()` directly, so an empty watchlist needs empty
/// states before it can be reached.
fn remove_selected_symbol(&mut self) {
if self.symbols.len() < 2 {
return;
}
let gone = self.symbols.remove(self.selected);
self.report_date_retry.remove(&gone);
self.sync_shared_symbols();
self.persist_watchlist();
// Prices are cheap to fetch again; the AlphAI feeds are not, so
// their cache survives a removal and a re-add costs no request.
// A holding keeps its price: it is still polled, and blanking the
// row would leave the portfolio view showing "…" until the tick.
if self.position(&gone).is_none() {
self.data.remove(&gone);
self.data_window.remove(&gone);
self.errors.remove(&gone);
self.error_window.remove(&gone);
self.price_flash.remove(&gone);
self.from_cache.remove(&gone);
self.quote_fetched.remove(&gone);
}
self.select_symbol(self.selected.min(self.symbols.len() - 1));
}
/// Moves the watchlist cursor. Everything scoped to the selected
/// ticker starts over, or the new ticker's feed would open at the old
/// one's scroll position.
fn select_symbol(&mut self, idx: usize) {
self.selected = idx;
self.news_selected = 0;
self.card_scroll = 0;
self.earnings_scroll = 0;
}
/// Every symbol the poller fetches: the watchlist plus anything held
/// that is not on it. A holding with no price is a row that cannot be
/// valued, so it is worth the request; the budget warning in `main`
/// counts this list for the same reason.
pub fn polled_symbols(&self) -> Vec<String> {
portfolio::polled_symbols(&self.symbols, &self.positions)
}
fn sync_shared_symbols(&self) {
*self.shared_symbols.write().unwrap() = self.polled_symbols();
}
fn handle_help_key(&mut self, key: KeyEvent) -> bool {
if key.code == KeyCode::Esc {
self.help = HelpOverlay::default();
return false;
}
match self.keymap.resolve(&key) {
Some(Action::Quit) => return true,
Some(Action::Help) => self.help = HelpOverlay::default(),
Some(Action::Up) => self.help.scroll = self.help.scroll.saturating_sub(1),
// The render pass clamps the scroll to the table's real height.
Some(Action::Down) => self.help.scroll = self.help.scroll.saturating_add(1),
Some(Action::PageUp) => self.help.scroll = self.help.scroll.saturating_sub(10),
Some(Action::PageDown) => self.help.scroll = self.help.scroll.saturating_add(10),
_ => {}
}
false
}
/// URL Enter opens for an article. News items default to their alphai.io
/// article page (settings can flip this to the original source); insider
/// filings always open the original, which points at the SEC filing.
fn article_url(&self, a: &Article) -> String {
let url = if self.view_id() == ui::ViewId::News && !self.config.news_open_original() {
a.alphai_url().unwrap_or_else(|| a.original.url.clone())
} else {
a.original.url.clone()
};
with_utm(&url)
}
/// p / P: walk the preset list forward or back.
fn cycle_theme(&mut self, dir: isize) {
self.set_theme(crate::theme::step_preset(self.theme_name, dir));
}
/// Switch to a named preset (the p key, the settings row). Rebuilt
/// through the same path the config takes, so the `[theme]` slots the
/// user spelled out keep overriding the palette; the frame style comes
/// from `[ui] borders` and does not belong to the preset. Session-only
/// until Save writes the name into the config.
pub(crate) fn set_theme(&mut self, name: &'static str) {
let panels = self.theme.panels;
let mut warnings = Vec::new();
let (mut theme, name) =
Theme::resolve(self.config.theme.as_ref(), Some(name), &mut warnings);
theme.panels = panels;
self.theme = theme;
self.theme_name = name;
}
/// The time the Calendar reads, for its rows, its cursor and what
/// Enter opens alike. A test that pins its agenda to a date freezes
/// this too; otherwise the keys would act on today's agenda instead of
/// the one the test built.
pub(crate) fn now(&self) -> DateTime<Utc> {
#[cfg(test)]
if let Some(now) = self.frozen_now {
return now;
}
Utc::now()
}
fn switch_view(&mut self, idx: usize) {
if idx != self.view_idx {
self.view_idx = idx;
self.news_selected = 0;
self.card_scroll = 0;
self.earnings_scroll = 0;
if ui::VIEWS[idx].shows_calendar() {
self.calendar_selection = ui::calendar::Selection::default();
self.calendar_state = TableState::default();
}
}
}
fn move_calendar(&mut self, delta: isize) {
let rows = ui::calendar::agenda(self, self.now());
let Some(current) = self.calendar_selection.resolve(&rows) else {
return;
};
let next = current.saturating_add_signed(delta).min(rows.len() - 1);
self.calendar_selection.choose(&rows, next);
if let ui::calendar::Kind::Report { symbol } = &rows[next].kind
&& let Some(idx) = self.symbols.iter().position(|s| s == symbol)
{
self.select_symbol(idx);
}
}
fn open_calendar_row(&mut self) {
match ui::calendar::open_target(self, self.now()) {
Some(ui::calendar::OpenTarget::Url(url)) => open_url(&url),
Some(ui::calendar::OpenTarget::Earnings(symbol)) => {
if let Some(idx) = self.symbols.iter().position(|s| s == &symbol) {
self.select_symbol(idx);
self.switch_view(ui::view_index(ui::ViewId::Earnings));
}
}
Some(ui::calendar::OpenTarget::Unavailable) => {
self.notice = Some(("No source link for this event".into(), Instant::now()));
}
None => {}
}
}
/// t / T: jump to the next/previous range/interval preset and wake the
/// price poller. Only `refresh.notify_one()` here: `manual_refresh()`
/// would also drop the visible AlphAI bundle and burn a request from
/// its budget for what is purely a price-history change.
fn cycle_range(&mut self, dir: isize) {
let (range, interval) = next_preset(&self.chart.presets, (self.range, self.interval), dir);
self.range = range;
self.interval = interval;
self.push_params();
}
/// Why `E` cannot change the chart in front of the reader, if it
/// cannot. The switch still flips (it is one setting for the session,
/// and the next ticker or preset may use it), but a key that does
/// nothing visible has to say why.
pub fn extended_unavailable(&self) -> Option<String> {
let symbol = self.selected_symbol();
if !self.source_extended {
return Some(format!(
"{} has no candle history, so there are no pre or post market candles to draw",
self.source_name
));
}
if self.interval == Interval::D1 {
return Some(
"Daily candles cover the regular session only, pick an intraday preset (t)".into(),
);
}
if crate::market::is_crypto(symbol) {
return Some(format!(
"{symbol} trades around the clock, it has no pre or post market"
));
}
if !crate::market::is_us_equity(symbol) {
return Some(format!(
"Pre and post market candles are drawn for US listings only, not {symbol}"
));
}
None
}
/// E: draw the pre and post market candles, or stop. Same shape as the
/// preset cycle, and the same reason for only nudging the price
/// poller: nothing about the AlphAI feeds changes.
///
/// Switching off needs no fetch to look right: dropping the extended
/// candles is all a regular-hours answer would change, so the rows are
/// trimmed and retagged here and the chart follows the key at once.
/// The trim goes by the interval the rows were fetched at, which is not
/// the current one while a preset change is still pending.
fn toggle_sessions(&mut self) {
let before = self.window();
self.sessions = self.sessions.toggled();
if self.sessions == Sessions::Extended
&& let Some(why) = self.extended_unavailable()
{
self.notice = Some((why, Instant::now()));
}
if self.sessions == Sessions::Regular {
for (symbol, data) in &mut self.data {
let window = self.data_window.entry(symbol.clone()).or_insert(before);
if sessions_matter(symbol, window.1) {
data.candles.retain(|c| {
crate::market::window_at(c.ts)
.is_some_and(|w| w.session == crate::market::Session::Open)
});
}
window.2 = Sessions::Regular;
}
}
self.push_params();
}
fn push_params(&mut self) {
*self.params.write().unwrap() = (self.range, self.interval, self.sessions);
self.refresh.notify_one();
}
}
/// Whether the watchlist a session starts on is the one the file keeps: it
/// is, unless tickers on the command line replaced a saved list. With no
/// saved list there is nothing to overwrite, and the first `a` saves the
/// list on screen.
pub(crate) fn watchlist_is_saved(saved: &[String], symbols: &[String]) -> bool {
saved.is_empty()
|| saved
.iter()
.map(|s| s.to_uppercase())
.eq(symbols.iter().cloned())
}
/// Whether a ticker's candles differ between regular and extended hours.
/// Only a US listing's intraday bars do: crypto trades around the clock,
/// and a daily bar is the regular session either way (the same test
/// `source::normalize_sessions` makes).
fn sessions_matter(symbol: &str, interval: Interval) -> bool {
interval != Interval::D1 && crate::market::is_us_equity(symbol)
}
/// Tag an outgoing article link with this client as the traffic source, so
/// alphai.io and original publishers can attribute the referral. Left as-is
/// when the URL already carries a utm_source (never clobber the feed's own
/// attribution); the fragment, if any, stays at the end where it belongs.
fn with_utm(url: &str) -> String {
if url.contains("utm_source=") {
return url.to_string();
}
let (base, frag) = match url.split_once('#') {
Some((base, frag)) => (base, Some(frag)),
None => (url, None),
};
let sep = if base.contains('?') { '&' } else { '?' };
match frag {
Some(frag) => format!("{base}{sep}utm_source=alphai-tui#{frag}"),
None => format!("{base}{sep}utm_source=alphai-tui"),
}
}
/// Open a URL with the platform handler; failures are ignored (worst case the
/// article just does not open — never crash the TUI over it). Tests that press
/// an open key must not launch the real browser.
pub fn open_url(url: &str) {
if cfg!(test) || !(url.starts_with("https://") || url.starts_with("http://")) {
return;
}
#[cfg(target_os = "macos")]
let mut cmd = std::process::Command::new("open");
#[cfg(all(unix, not(target_os = "macos")))]
let mut cmd = std::process::Command::new("xdg-open");
#[cfg(target_os = "windows")]
let mut cmd = {
let mut c = std::process::Command::new("cmd");
c.args(["/C", "start", ""]);
c
};
let _ = cmd
.arg(url)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
}
#[cfg(test)]
mod tests {
use super::{RANGE_PRESETS, next_preset, with_utm};
use crate::domain::{Interval, Range};
#[test]
fn range_presets_wrap_both_ways() {
let first = RANGE_PRESETS[0];
let last = RANGE_PRESETS[RANGE_PRESETS.len() - 1];
assert_eq!(next_preset(&RANGE_PRESETS, first, 1), RANGE_PRESETS[1]);
assert_eq!(next_preset(&RANGE_PRESETS, last, 1), first);
assert_eq!(next_preset(&RANGE_PRESETS, first, -1), last);
}
#[test]
fn utm_tag_appended_to_plain_and_query_urls() {
assert_eq!(
with_utm("https://alphai.io/news/article/07-10/abc/slug"),
"https://alphai.io/news/article/07-10/abc/slug?utm_source=alphai-tui"
);
assert_eq!(
with_utm("https://example.com/story?id=7"),
"https://example.com/story?id=7&utm_source=alphai-tui"
);
}
#[test]
fn utm_tag_respects_existing_source_and_fragment() {
// A feed URL that already attributes its source is left untouched.
let tagged = "https://example.com/story?utm_source=newsletter";
assert_eq!(with_utm(tagged), tagged);
// The fragment stays terminal, the query lands before it.
assert_eq!(
with_utm("https://example.com/story#section"),
"https://example.com/story?utm_source=alphai-tui#section"
);
}
#[test]
fn range_presets_absorb_unknown_startup_combo() {
// A CLI combo outside the table joins the cycle at the nearest edge.
let odd = (Range::Mo3, Interval::M5);
assert_eq!(next_preset(&RANGE_PRESETS, odd, 1), RANGE_PRESETS[0]);
assert_eq!(
next_preset(&RANGE_PRESETS, odd, -1),
RANGE_PRESETS[RANGE_PRESETS.len() - 1]
);
}
}