-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2326 lines (2192 loc) · 89.6 KB
/
Copy pathapp.js
File metadata and controls
2326 lines (2192 loc) · 89.6 KB
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
"use strict";
// Same coin-stack artwork as favicon.svg, minus its own background rect -
// the header's .mark box already supplies the border/background, so only
// the icon geometry is duplicated here (kept in sync by hand; there's no
// build step to share an asset between an <img> and this inline markup).
const STACK_MARK_SVG = `<svg width="17" height="17" viewBox="0 0 32 32">
<g stroke="#0c0b0a" stroke-width="1" stroke-linejoin="round">
<rect x="5.5" y="18.45" width="21" height="5.8" fill="#a9803a"/>
<rect x="5.5" y="12.95" width="21" height="5.8" fill="#d4b56a"/>
<rect x="5.5" y="7.45" width="21" height="5.8" fill="#f0d9a0"/>
<ellipse cx="16" cy="24.25" rx="10.5" ry="2.9" fill="#8a6c30"/>
<ellipse cx="16" cy="18.75" rx="10.5" ry="2.9" fill="#a9803a"/>
<ellipse cx="16" cy="13.25" rx="10.5" ry="2.9" fill="#d4b56a"/>
<ellipse cx="16" cy="7.75" rx="10.5" ry="2.9" fill="#f0d9a0"/>
</g>
<ellipse cx="16" cy="7.75" rx="6.2" ry="1.4" fill="none" stroke="#0c0b0a" stroke-width="0.7" opacity="0.55"/>
</svg>`;
const HOLDINGS_KEY = "stackemall.holdings";
const CACHE_KEY = "stackemall.quotesCache";
const NEWS_KEY = "stackemall.news";
const SETTINGS_KEY = "stackemall.settings";
const HISTORY_KEY = "stackemall.history";
const PRIVACY_KEY = "stackemall.privacy";
const HISTORY_MAX_DAYS = 365;
const REFRESH_MS = 30_000;
const NEWS_MS = 5 * 60_000;
const SPARKLINE_MS = 6 * 60 * 60_000;
const STALE_MS = 4 * REFRESH_MS;
const CURRENCY_OPTIONS = [
{ code: "DKK", label: "Danish krone" },
{ code: "EUR", label: "Euro" },
{ code: "GBP", label: "British pound" },
{ code: "SEK", label: "Swedish krona" },
{ code: "NOK", label: "Norwegian krone" },
{ code: "USD", label: "US dollar" },
];
const CURRENCY_LOCALES = {
USD: "en-US",
DKK: "da-DK",
EUR: "de-DE",
GBP: "en-GB",
SEK: "sv-SE",
NOK: "nb-NO",
};
const TIME_FORMAT_OPTIONS = [
{ value: "auto", label: "Match browser" },
{ value: "24", label: "24-hour" },
{ value: "12", label: "12-hour (AM/PM)" },
];
const TIMEZONE_OPTIONS = [
{ value: "auto", label: "Match browser" },
{ value: "Europe/Copenhagen", label: "Copenhagen" },
{ value: "Europe/London", label: "London" },
{ value: "America/New_York", label: "New York" },
{ value: "America/Los_Angeles", label: "Los Angeles" },
{ value: "Asia/Tokyo", label: "Tokyo" },
{ value: "UTC", label: "UTC" },
];
const SORT_OPTIONS = [
{ value: "value", label: "Value" },
{ value: "changePct", label: "Today's %" },
{ value: "pnl", label: "P/L" },
{ value: "symbol", label: "Ticker" },
];
const DEFAULT_SETTINGS = { localCurrency: "DKK", timeFormat: "auto", timezone: "auto", sortBy: "value", showWire: true };
const CRYPTO = {
"BTC-USD": { id: "bitcoin", name: "Bitcoin" },
BTC: { id: "bitcoin", name: "Bitcoin" },
BITCOIN: { id: "bitcoin", name: "Bitcoin" },
"ETH-USD": { id: "ethereum", name: "Ethereum" },
ETH: { id: "ethereum", name: "Ethereum" },
ETHEREUM: { id: "ethereum", name: "Ethereum" },
"SOL-USD": { id: "solana", name: "Solana" },
SOL: { id: "solana", name: "Solana" },
};
const QUICK_ADDS = [
{ symbol: "BTC-USD", label: "Bitcoin" },
{ symbol: "ETH-USD", label: "Ethereum" },
{ symbol: "AAPL", label: "Apple" },
{ symbol: "MSFT", label: "Microsoft" },
{ symbol: "NVDA", label: "nVidia" },
{ symbol: "GOOGL", label: "Alphabet" },
{ symbol: "AMZN", label: "Amazon" },
{ symbol: "NOVO-B.CO", label: "Novo Nordisk" },
{ symbol: "VWS.CO", label: "Vestas" },
{ symbol: "SPY", label: "S&P 500" },
];
// Resolved locally first so the search dropdown never depends on Yahoo Finance
// being reachable through a public CORS proxy (those go down/rate-limit often).
// Live results from Yahoo are merged in on top of this when they arrive.
const STOCK_DIRECTORY = [
{ symbol: "AAPL", name: "Apple", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "MSFT", name: "Microsoft", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "NVDA", name: "nVidia", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "GOOGL", name: "Alphabet (Class A)", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "GOOG", name: "Alphabet (Class C)", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "AMZN", name: "Amazon", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "META", name: "Meta Platforms", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "TSLA", name: "Tesla", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "BRK-B", name: "Berkshire Hathaway", type: "EQUITY", exchange: "NYSE" },
{ symbol: "JPM", name: "JPMorgan Chase", type: "EQUITY", exchange: "NYSE" },
{ symbol: "V", name: "Visa", type: "EQUITY", exchange: "NYSE" },
{ symbol: "MA", name: "Mastercard", type: "EQUITY", exchange: "NYSE" },
{ symbol: "UNH", name: "UnitedHealth Group", type: "EQUITY", exchange: "NYSE" },
{ symbol: "JNJ", name: "Johnson & Johnson", type: "EQUITY", exchange: "NYSE" },
{ symbol: "WMT", name: "Walmart", type: "EQUITY", exchange: "NYSE" },
{ symbol: "PG", name: "Procter & Gamble", type: "EQUITY", exchange: "NYSE" },
{ symbol: "HD", name: "Home Depot", type: "EQUITY", exchange: "NYSE" },
{ symbol: "XOM", name: "Exxon Mobil", type: "EQUITY", exchange: "NYSE" },
{ symbol: "CVX", name: "Chevron", type: "EQUITY", exchange: "NYSE" },
{ symbol: "KO", name: "Coca-Cola", type: "EQUITY", exchange: "NYSE" },
{ symbol: "PEP", name: "PepsiCo", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "MRK", name: "Merck", type: "EQUITY", exchange: "NYSE" },
{ symbol: "ABBV", name: "AbbVie", type: "EQUITY", exchange: "NYSE" },
{ symbol: "AVGO", name: "Broadcom", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "ORCL", name: "Oracle", type: "EQUITY", exchange: "NYSE" },
{ symbol: "CRM", name: "Salesforce", type: "EQUITY", exchange: "NYSE" },
{ symbol: "ADBE", name: "Adobe", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "NFLX", name: "Netflix", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "AMD", name: "Advanced Micro Devices", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "INTC", name: "Intel", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "IBM", name: "IBM", type: "EQUITY", exchange: "NYSE" },
{ symbol: "CSCO", name: "Cisco Systems", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "QCOM", name: "Qualcomm", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "TXN", name: "Texas Instruments", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "PYPL", name: "PayPal", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "DIS", name: "Walt Disney", type: "EQUITY", exchange: "NYSE" },
{ symbol: "NKE", name: "Nike", type: "EQUITY", exchange: "NYSE" },
{ symbol: "MCD", name: "McDonald's", type: "EQUITY", exchange: "NYSE" },
{ symbol: "SBUX", name: "Starbucks", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "BA", name: "Boeing", type: "EQUITY", exchange: "NYSE" },
{ symbol: "CAT", name: "Caterpillar", type: "EQUITY", exchange: "NYSE" },
{ symbol: "GE", name: "General Electric", type: "EQUITY", exchange: "NYSE" },
{ symbol: "F", name: "Ford Motor", type: "EQUITY", exchange: "NYSE" },
{ symbol: "GM", name: "General Motors", type: "EQUITY", exchange: "NYSE" },
{ symbol: "UBER", name: "Uber Technologies", type: "EQUITY", exchange: "NYSE" },
{ symbol: "ABNB", name: "Airbnb", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "SHOP", name: "Shopify", type: "EQUITY", exchange: "NYSE" },
{ symbol: "SQ", name: "Block", type: "EQUITY", exchange: "NYSE" },
{ symbol: "COIN", name: "Coinbase Global", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "PLTR", name: "Palantir Technologies", type: "EQUITY", exchange: "NYSE" },
{ symbol: "SOFI", name: "SoFi Technologies", type: "EQUITY", exchange: "NASDAQ" },
{ symbol: "SPY", name: "S&P 500", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "QQQ", name: "Nasdaq 100", type: "ETF", exchange: "NASDAQ" },
{ symbol: "DIA", name: "Dow Jones Industrial Average", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "IWM", name: "Russell 2000", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "VTI", name: "Vanguard Total Stock Market", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "VOO", name: "Vanguard S&P 500", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "ARKK", name: "ARK Innovation", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "GLD", name: "SPDR Gold Shares", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "SLV", name: "iShares Silver Trust", type: "ETF", exchange: "NYSEARCA" },
{ symbol: "GC=F", name: "Gold", type: "FUTURE", exchange: "COMEX" },
{ symbol: "SI=F", name: "Silver", type: "FUTURE", exchange: "COMEX" },
{ symbol: "PL=F", name: "Platinum", type: "FUTURE", exchange: "COMEX" },
{ symbol: "PA=F", name: "Palladium", type: "FUTURE", exchange: "COMEX" },
{ symbol: "NOVO-B.CO", name: "Novo Nordisk", type: "EQUITY", exchange: "CPH" },
{ symbol: "VWS.CO", name: "Vestas Wind Systems", type: "EQUITY", exchange: "CPH" },
{ symbol: "MAERSK-B.CO", name: "A.P. Møller - Mærsk", type: "EQUITY", exchange: "CPH" },
{ symbol: "DANSKE.CO", name: "Danske Bank", type: "EQUITY", exchange: "CPH" },
{ symbol: "ORSTED.CO", name: "Ørsted", type: "EQUITY", exchange: "CPH" },
{ symbol: "CARL-B.CO", name: "Carlsberg", type: "EQUITY", exchange: "CPH" },
{ symbol: "DSV.CO", name: "DSV", type: "EQUITY", exchange: "CPH" },
{ symbol: "GN.CO", name: "GN Store Nord", type: "EQUITY", exchange: "CPH" },
{ symbol: "PNDORA.CO", name: "Pandora", type: "EQUITY", exchange: "CPH" },
{ symbol: "TRYG.CO", name: "Tryg", type: "EQUITY", exchange: "CPH" },
{ symbol: "NDA-DK.CO", name: "Nordea Bank", type: "EQUITY", exchange: "CPH" },
{ symbol: "COLO-B.CO", name: "Coloplast", type: "EQUITY", exchange: "CPH" },
{ symbol: "AMBU-B.CO", name: "Ambu", type: "EQUITY", exchange: "CPH" },
{ symbol: "DEMANT.CO", name: "Demant", type: "EQUITY", exchange: "CPH" },
{ symbol: "ISS.CO", name: "ISS", type: "EQUITY", exchange: "CPH" },
{ symbol: "GMAB.CO", name: "Genmab", type: "EQUITY", exchange: "CPH" },
{ symbol: "NZYM-B.CO", name: "Novonesis (Novozymes)", type: "EQUITY", exchange: "CPH" },
{ symbol: "SIM.CO", name: "SimCorp", type: "EQUITY", exchange: "CPH" },
{ symbol: "RBREW.CO", name: "Royal Unibrew", type: "EQUITY", exchange: "CPH" },
{ symbol: "BAVA.CO", name: "Bavarian Nordic", type: "EQUITY", exchange: "CPH" },
];
// Metals get their own Add-dialog type (a fixed 4-option picker, not the
// general ticker search) so they're actually discoverable - they still
// resolve through the normal Yahoo ticker quote/sparkline/news paths like
// any other ticker, this only changes how the symbol gets picked and how
// they're bucketed in the stat cards.
const METALS = [
{ symbol: "GC=F", name: "Gold" },
{ symbol: "SI=F", name: "Silver" },
{ symbol: "PL=F", name: "Platinum" },
{ symbol: "PA=F", name: "Palladium" },
];
const METAL_SYMBOLS = new Set(METALS.map((m) => m.symbol));
function isMetal(symbol) {
return METAL_SYMBOLS.has(symbol);
}
// Quantity for these is priced in troy ounces (the COMEX futures contract
// unit) - not shares, not grams. Surfaced in the UI so a physical holding by
// weight doesn't get entered in the wrong unit by mistake.
const QUANTITY_UNITS = {
"GC=F": { short: "troy oz", long: "troy ounces" },
"SI=F": { short: "troy oz", long: "troy ounces" },
"PL=F": { short: "troy oz", long: "troy ounces" },
"PA=F": { short: "troy oz", long: "troy ounces" },
};
// The holding card's Qty column is one of four narrow grid cells - "troy
// ounces" risks wrapping there, so it only gets the spelled-out form where
// there's room to spare (the add/edit dialog).
function quantityUnit(symbol, long) {
const unit = QUANTITY_UNITS[symbol];
if (!unit) return "";
return long ? unit.long : unit.short;
}
const HOLDING_COLORS = [
"#d4b56a",
"#7a9bb8",
"#8fbf9f",
"#c9897a",
"#b8a1c9",
"#8aa8a3",
"#c4a574",
"#6e8b9e",
"#d1a3a0",
"#9bb07a",
];
const usdFmt = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const localFmtCache = {};
const usdParts = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
const root = document.querySelector("#app");
const headEl = document.querySelector("#app-head");
const tapeEl = document.querySelector("#app-tape");
const bodyEl = document.querySelector("#app-body");
let lastTapeHtml = null;
const cache = loadJson(CACHE_KEY);
const newsCache = loadJson(NEWS_KEY);
const historyCache = loadJson(HISTORY_KEY);
const state = {
holdings: loadHoldings(),
quotes: cache?.quotes || {},
sparklines: cache?.sparklines || {},
fx: cache?.fx || {},
news: newsCache?.news || {},
history: Array.isArray(historyCache) ? historyCache : [],
updatedAt: cache?.updatedAt || null,
status: "idle",
error: null,
modal: null,
settings: loadSettings(),
searchQ: "",
searchResults: [],
selectedSymbol: "",
selectedName: "",
quantity: "1",
costBasis: "",
tag: "",
tagFilter: new Set(),
addMode: "ticker",
privacy: Boolean(loadJson(PRIVACY_KEY)),
capturing: false,
now: Date.now(),
};
let searchTimer = 0;
function loadJson(key) {
try {
return JSON.parse(localStorage.getItem(key) || "null");
} catch {
return null;
}
}
function saveJson(key, value) {
localStorage.setItem(key, JSON.stringify(value));
}
function sanitizeHoldings(parsed) {
if (!Array.isArray(parsed)) return [];
return parsed
.filter((h) => h && typeof h.symbol === "string")
.map((h) => ({
id: String(h.id || crypto.randomUUID()),
symbol: h.symbol.trim().toUpperCase(),
name: String(h.name || h.symbol),
quantity: Number(h.quantity) || 0,
costBasis: h.costBasis == null ? null : Number(h.costBasis),
tag: h.tag ? String(h.tag).trim() : "",
}));
}
function loadHoldings() {
return sanitizeHoldings(loadJson(HOLDINGS_KEY));
}
function persist() {
saveJson(HOLDINGS_KEY, state.holdings);
}
function persistCache() {
saveJson(CACHE_KEY, {
quotes: state.quotes,
sparklines: state.sparklines,
fx: state.fx,
updatedAt: state.updatedAt,
});
}
function sanitizeSettings(saved) {
saved = saved || {};
return {
localCurrency: CURRENCY_OPTIONS.some((c) => c.code === saved.localCurrency)
? saved.localCurrency
: DEFAULT_SETTINGS.localCurrency,
timeFormat: TIME_FORMAT_OPTIONS.some((t) => t.value === saved.timeFormat)
? saved.timeFormat
: DEFAULT_SETTINGS.timeFormat,
timezone: TIMEZONE_OPTIONS.some((t) => t.value === saved.timezone)
? saved.timezone
: DEFAULT_SETTINGS.timezone,
sortBy: SORT_OPTIONS.some((s) => s.value === saved.sortBy) ? saved.sortBy : DEFAULT_SETTINGS.sortBy,
showWire: typeof saved.showWire === "boolean" ? saved.showWire : DEFAULT_SETTINGS.showWire,
};
}
function loadSettings() {
return sanitizeSettings(loadJson(SETTINGS_KEY));
}
function persistSettings() {
saveJson(SETTINGS_KEY, state.settings);
}
function esc(value) {
return String(value).replace(/[&<>"']/g, (ch) =>
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ch],
);
}
function formatUsd(n) {
return usdFmt.format(n);
}
function formatLocal(n) {
const code = state.settings.localCurrency;
if (code === "USD") return formatUsd(n);
let fmt = localFmtCache[code];
if (!fmt) {
fmt = new Intl.NumberFormat(CURRENCY_LOCALES[code] || "en-US", { style: "currency", currency: code });
localFmtCache[code] = fmt;
}
return fmt.format(n);
}
// Rounded to whole units - used where space is tight (tag chips) and a
// dozen extra pixels per chip matters more than exact cents.
const localFmtCacheCompact = {};
function formatLocalCompact(n) {
const code = state.settings.localCurrency;
let fmt = localFmtCacheCompact[code];
if (!fmt) {
fmt = new Intl.NumberFormat(CURRENCY_LOCALES[code] || "en-US", {
style: "currency",
currency: code,
minimumFractionDigits: 0,
maximumFractionDigits: 0,
});
localFmtCacheCompact[code] = fmt;
}
return fmt.format(n);
}
function splitUsd(n) {
const formatted = usdParts.format(n);
const match = formatted.match(/^(.*)([.]\d{2})$/);
if (!match) return { main: formatted, frac: "" };
return { main: match[1], frac: match[2] };
}
// Same "cents drawn dimmer" treatment as the big hero total, generalized to
// any already-formatted currency/number string - handles both a period
// decimal (USD-style "$1,234.56") and a comma decimal (da-DK style
// "1.234,56 kr."), and keeps a trailing currency suffix at full brightness.
function withDimmedDecimals(formatted) {
// Greedy main + a suffix that must start with a non-digit (or be empty)
// forces this to land on the trailing decimal group, not an earlier
// thousands-separator - "$72,782.11" would otherwise match ",78" first.
const match = formatted.match(/^(.*)([.,]\d{2})(\D.*|)$/);
if (!match) return esc(formatted);
const [, main, frac, suffix] = match;
return `${esc(main)}<span class="frac">${esc(frac)}</span>${esc(suffix)}`;
}
function formatQty(n) {
// Matches whatever locale the currency figures next to it use (da-DK's
// "." for thousands / "," for decimal is the opposite of en-US) - a
// quantity in US notation beside a DKK value in Danish notation read as
// inconsistent, even though each was individually correct.
const locale = CURRENCY_LOCALES[state.settings.localCurrency] || "en-US";
if (Number.isInteger(n)) return n.toLocaleString(locale);
const abs = Math.abs(n);
const digits = abs >= 1 ? 4 : abs >= 0.01 ? 6 : 8;
return n.toLocaleString(locale, { maximumFractionDigits: digits });
}
function formatPct(n) {
const locale = CURRENCY_LOCALES[state.settings.localCurrency] || "en-US";
const sign = n > 0 ? "+" : "";
return `${sign}${n.toLocaleString(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}%`;
}
// Unsigned - for allocation shares (always >= 0), where formatPct's "+"
// prefix would be wrong.
function formatShare(n) {
const locale = CURRENCY_LOCALES[state.settings.localCurrency] || "en-US";
return `${n.toLocaleString(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 })}%`;
}
function formatSignedUsd(n) {
const sign = n > 0 ? "+" : n < 0 ? "−" : "";
return `${sign}${usdFmt.format(Math.abs(n))}`;
}
function formatSignedLocal(n) {
const sign = n > 0 ? "+" : n < 0 ? "−" : "";
return `${sign}${formatLocal(Math.abs(n))}`;
}
function formatPrice(n, currency) {
try {
return new Intl.NumberFormat("en-US", {
style: "currency",
currency,
maximumFractionDigits: n >= 1 ? 2 : 6,
}).format(n);
} catch {
return `${n.toFixed(2)} ${currency}`;
}
}
function dateTimeZoneOption() {
return state.settings.timezone === "auto" ? {} : { timeZone: state.settings.timezone };
}
function formatTime(ts) {
const opts = {
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
...dateTimeZoneOption(),
};
if (state.settings.timeFormat === "12") opts.hour12 = true;
else if (state.settings.timeFormat === "24") opts.hour12 = false;
return new Intl.DateTimeFormat(undefined, opts).format(ts);
}
function formatDate(ts) {
return new Intl.DateTimeFormat(undefined, {
weekday: "long",
day: "numeric",
month: "long",
...dateTimeZoneOption(),
}).format(ts);
}
function relativeAgo(from, now) {
const sec = Math.max(0, Math.round((now - from) / 1000));
if (sec < 5) return "just now";
if (sec < 60) return `${sec}s ago`;
return `${Math.round(sec / 60)}m ago`;
}
function formatNewsAgo(from, now) {
const sec = Math.max(0, Math.round((now - from) / 1000));
if (sec < 60) return "now";
if (sec < 3600) return `${Math.floor(sec / 60)}m`;
if (sec < 86400) return `${Math.floor(sec / 3600)}h`;
if (sec < 86400 * 7) return `${Math.floor(sec / 86400)}d`;
return new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" }).format(from);
}
function colorFor(symbol, index) {
if (symbol === "BTC-USD") return "#f0b429";
if (symbol === "ETH-USD") return "#7aa2ff";
return HOLDING_COLORS[index % HOLDING_COLORS.length];
}
// Deterministic per-tag color: same tag text always maps to the same hue,
// so "Cold storage" looks the same everywhere it appears without needing a
// fixed palette or manual color picking. Saturation/lightness are pinned to
// values that read well against the dark card background at any hue.
function tagColor(tag) {
let hash = 0;
for (let i = 0; i < tag.length; i++) {
hash = (hash * 31 + tag.charCodeAt(i)) | 0;
}
const hue = Math.abs(hash) % 360;
return {
text: `hsl(${hue}, 55%, 70%)`,
border: `hsla(${hue}, 55%, 70%, 0.4)`,
bg: `hsla(${hue}, 55%, 70%, 0.14)`,
bgActive: `hsla(${hue}, 55%, 70%, 0.28)`,
};
}
// Cash holdings use a synthetic symbol "CASH-<code>" - no ticker, no live
// quote, just an amount in a currency. Checked before the crypto/USD-suffix
// regex everywhere, since "CASH-USD" would otherwise match that pattern.
function cashCurrency(symbol) {
const m = /^CASH-([A-Z]{3})$/.exec(symbol);
return m ? m[1] : null;
}
function isCash(symbol) {
return Boolean(cashCurrency(symbol));
}
// "Other" holdings are manually-valued possessions (property, vehicles,
// collectibles) that also have no live quote - same synthetic-symbol trick
// as Cash ("OTHER-<code>"), but the quantity field holds a current value the
// user updates by hand, and a per-holding name (not derivable from the
// symbol, since several holdings can share one currency) carries the label.
function otherCurrency(symbol) {
const m = /^OTHER-([A-Z]{3})$/.exec(symbol);
return m ? m[1] : null;
}
function isOther(symbol) {
return Boolean(otherCurrency(symbol));
}
function isCrypto(quote, symbol) {
if (isCash(symbol)) return false;
if (isOther(symbol)) return false;
if (CRYPTO[symbol]) return true;
if (quote?.quoteType === "CRYPTOCURRENCY") return true;
return /-(USD|USDT)$/.test(symbol);
}
function toUsd(amount, currency, fx) {
if (!currency || currency === "USD") return amount;
const rate = fx[currency];
if (!rate) return amount;
return amount / rate;
}
function toLocal(amountUsd, fx) {
const code = state.settings.localCurrency;
if (code === "USD") return amountUsd;
return amountUsd * (fx[code] || 0);
}
function signClass(n) {
if (n > 0.0001) return "up";
if (n < -0.0001) return "down";
return "flat";
}
function cryptoMeta(symbol) {
return CRYPTO[symbol] || CRYPTO[symbol.replace(/-USD$/, "")] || null;
}
async function fetchDirect(url, timeout = 8000) {
const res = await fetch(url, { signal: AbortSignal.timeout(timeout) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res;
}
function parseProxyPayload(text) {
let body = text;
const jinaMarker = "Markdown Content:\n";
const jinaIdx = body.indexOf(jinaMarker);
if (jinaIdx !== -1) body = body.slice(jinaIdx + jinaMarker.length);
const trimmed = body.trim();
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
const json = JSON.parse(trimmed);
if (typeof json.contents === "string") {
const inner = json.contents.trim();
if (inner.startsWith("{") || inner.startsWith("[")) return JSON.parse(inner);
return inner;
}
return json;
} catch {
return trimmed;
}
}
return trimmed;
}
async function tryProxy(wrap, url) {
const res = await fetch(wrap(url), { signal: AbortSignal.timeout(7000) });
if (!res.ok) throw new Error(`proxy HTTP ${res.status}`);
const text = await res.text();
if (!text || text.trim().startsWith("<!")) throw new Error("proxy returned non-JSON");
return parseProxyPayload(text);
}
async function fetchViaProxy(url) {
// Raced in parallel (not tried one-by-one) so a slow/dead proxy doesn't
// block the others - public CORS relays go down or start rate-limiting
// without notice, so we take whichever responds with valid content first.
const proxies = [
(u) => `https://api.allorigins.win/raw?url=${encodeURIComponent(u)}`,
(u) => `https://api.allorigins.win/get?url=${encodeURIComponent(u)}`,
(u) => `https://corsproxy.io/?${encodeURIComponent(u)}`,
(u) => `https://r.jina.ai/${u}`,
];
try {
return await Promise.any(proxies.map((wrap) => tryProxy(wrap, url)));
} catch (err) {
throw err?.errors?.[0] || new Error("All proxies failed");
}
}
async function fetchJsonDirect(url) {
const res = await fetchDirect(url);
return res.json();
}
async function fetchYahoo(pathAndQuery) {
const url = `https://query1.finance.yahoo.com${pathAndQuery}`;
try {
return await (await fetchDirect(url, 4000)).json();
} catch {
return fetchViaProxy(url);
}
}
function parseYahooChart(json) {
const result = json?.chart?.result?.[0];
const meta = result?.meta;
if (!meta || meta.regularMarketPrice == null) return null;
let price = Number(meta.regularMarketPrice);
let currency = meta.currency || "USD";
let prev = Number(meta.chartPreviousClose || meta.previousClose || price);
if (currency === "GBp" || currency === "GBX") {
price /= 100;
prev /= 100;
currency = "GBP";
}
const change = price - prev;
return {
symbol: String(meta.symbol || "").toUpperCase(),
name: meta.shortName || meta.longName || meta.symbol,
price,
currency,
change,
changePercent: prev ? (change / prev) * 100 : 0,
previousClose: prev,
quoteType: meta.instrumentType || "EQUITY",
marketState: meta.marketState || "REGULAR",
exchange: meta.exchangeName || "",
};
}
// Shared by quoteCrypto and fetchCryptoSparkline - the hardcoded CRYPTO map
// only covers BTC/ETH/SOL, so anything else needs this search fallback to
// resolve a CoinGecko id at all.
async function resolveCoinGeckoId(symbol) {
const meta = cryptoMeta(symbol);
if (meta?.id) return { id: meta.id, name: meta.name };
const needle = symbol.replace(/-USD$/, "").toLowerCase();
const search = await fetchJsonDirect(
`https://api.coingecko.com/api/v3/search?query=${encodeURIComponent(needle)}`,
);
const coin = (search.coins || []).find(
(c) => c.symbol?.toLowerCase() === needle || c.id === needle,
) || search.coins?.[0];
if (!coin) throw new Error("Unknown crypto");
return { id: coin.id, name: coin.name };
}
async function quoteCrypto(symbol) {
const { id, name } = await resolveCoinGeckoId(symbol);
const data = await fetchJsonDirect(
`https://api.coingecko.com/api/v3/simple/price?ids=${encodeURIComponent(id)}&vs_currencies=usd,dkk&include_24hr_change=true`,
);
const row = data[id];
if (!row?.usd) throw new Error("No crypto price");
const changePercent = Number(row.usd_24h_change || 0);
const price = Number(row.usd);
return {
symbol,
name,
price,
currency: "USD",
change: price * (changePercent / 100) / (1 + changePercent / 100 || 1),
changePercent,
previousClose: price / (1 + changePercent / 100 || 1),
quoteType: "CRYPTOCURRENCY",
marketState: "REGULAR",
exchange: "CCC",
dkkPrice: row.dkk ? Number(row.dkk) : null,
};
}
async function quoteYahoo(symbol) {
const json = await fetchYahoo(
`/v8/finance/chart/${encodeURIComponent(symbol)}?interval=1d&range=5d`,
);
const quote = parseYahooChart(json);
if (!quote) throw new Error("No Yahoo quote");
return quote;
}
async function quoteBinanceBtc() {
const data = await fetchJsonDirect("https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT");
const price = Number(data.lastPrice);
const changePercent = Number(data.priceChangePercent);
return {
symbol: "BTC-USD",
name: "Bitcoin",
price,
currency: "USD",
change: Number(data.priceChange),
changePercent,
previousClose: Number(data.prevClosePrice),
quoteType: "CRYPTOCURRENCY",
marketState: "REGULAR",
exchange: "Binance",
};
}
// No ticker, no network call - 1 unit always equals 1 unit of that currency.
// toUsd()/toLocal() already know how to convert any currency via state.fx,
// so a synthetic "price: 1" quote is all that's needed to plug into every
// existing value/P&L/history calculation with no special-casing there.
async function quoteCash(symbol) {
const code = cashCurrency(symbol);
return {
symbol,
name: `Cash (${code})`,
price: 1,
currency: code,
change: 0,
changePercent: 0,
previousClose: 1,
quoteType: "CASH",
marketState: "REGULAR",
exchange: "Cash",
};
}
// Same synthetic "price: 1" trick as quoteCash(). No `name` field, since
// this quote is shared across every holding with this symbol (e.g. two
// different possessions both valued in DKK) - each holding's own `name`
// (the user-typed label) is what the UI actually shows.
async function quoteOther(symbol) {
const code = otherCurrency(symbol);
return {
symbol,
price: 1,
currency: code,
change: 0,
changePercent: 0,
previousClose: 1,
quoteType: "OTHER",
marketState: "REGULAR",
exchange: "Other",
};
}
async function quoteSymbol(symbol) {
if (isCash(symbol)) return quoteCash(symbol);
if (isOther(symbol)) return quoteOther(symbol);
if (cryptoMeta(symbol) || /-(USD|USDT)$/.test(symbol)) {
try {
return await quoteCrypto(symbol);
} catch {
if (symbol === "BTC-USD" || symbol === "BTC") return quoteBinanceBtc();
}
}
return quoteYahoo(symbol);
}
// Sparkline history is fetched separately from the price quote, on its own
// slow cadence - not on every 30s refresh. Two reasons: a longer chart range
// changes Yahoo's chartPreviousClose (it's relative to the start of the
// requested range, not literally "yesterday"), which would corrupt the
// day's % change if reused for quotes; and CoinGecko's free tier doesn't
// need an extra call every 30s for something purely decorative.
async function fetchStockSparkline(symbol) {
const json = await fetchYahoo(`/v8/finance/chart/${encodeURIComponent(symbol)}?interval=1d&range=1mo`);
const closes = json?.chart?.result?.[0]?.indicators?.quote?.[0]?.close || [];
return closes.filter((v) => typeof v === "number");
}
async function fetchCryptoSparkline(symbol) {
const { id } = await resolveCoinGeckoId(symbol);
const data = await fetchJsonDirect(
`https://api.coingecko.com/api/v3/coins/${id}/market_chart?vs_currency=usd&days=30&interval=daily`,
);
return (data.prices || []).map(([, p]) => p).filter((v) => typeof v === "number");
}
async function fetchSparkline(symbol) {
if (isCash(symbol) || isOther(symbol)) return [];
if (cryptoMeta(symbol) || /-(USD|USDT)$/.test(symbol)) return fetchCryptoSparkline(symbol);
return fetchStockSparkline(symbol);
}
async function fetchFx() {
const fx = { USD: 1 };
try {
const data = await fetchJsonDirect("https://open.er-api.com/v6/latest/USD");
if (data?.rates) {
for (const code of ["DKK", "EUR", "GBP", "SEK", "NOK"]) {
if (data.rates[code]) fx[code] = Number(data.rates[code]);
}
}
} catch {
try {
const data = await fetchJsonDirect("https://api.frankfurter.dev/v1/latest?from=USD&to=DKK,EUR,GBP");
Object.assign(fx, data.rates || {});
} catch {
// leave USD only
}
}
return fx;
}
function dedupeResults(list) {
const seen = new Set();
return list.filter((r) => {
if (seen.has(r.symbol)) return false;
seen.add(r.symbol);
return true;
});
}
function localTickerMatches(query) {
const needle = query.trim().toLowerCase();
if (!needle) return [];
const starts = [];
const contains = [];
for (const t of STOCK_DIRECTORY) {
const sym = t.symbol.toLowerCase();
const bareSym = sym.replace(/[.\-].*$/, "");
if (sym.startsWith(needle) || bareSym.startsWith(needle)) starts.push(t);
else if (t.name.toLowerCase().includes(needle)) contains.push(t);
}
return [...starts, ...contains];
}
function cryptoMatch(query) {
const cryptoHit = cryptoMeta(query.toUpperCase());
if (!cryptoHit) return null;
const symbol =
cryptoHit.id === "ethereum" ? "ETH-USD" : cryptoHit.id === "solana" ? "SOL-USD" : "BTC-USD";
return { symbol, name: cryptoHit.name, type: "CRYPTOCURRENCY", exchange: "CCC" };
}
function typedFallback(query) {
const symbol = query.trim().toUpperCase();
return { symbol, name: symbol, type: "", exchange: "typed" };
}
// Local matches resolve instantly with no network dependency. Yahoo's search
// API sends no CORS headers, so reaching it needs a public proxy relay -
// those are flaky, so treat any live results as a nice-to-have on top.
async function liveTickerSearch(query) {
const json = await fetchYahoo(
`/v1/finance/search?q=${encodeURIComponent(query)}"esCount=8&newsCount=0`,
);
return (json.quotes || [])
.filter((item) => item.symbol && item.quoteType !== "NONE")
.map((item) => ({
symbol: String(item.symbol).toUpperCase(),
name: item.shortname || item.longname || item.symbol,
type: item.quoteType || item.typeDisp || "",
exchange: item.exchDisp || item.exchange || "",
}));
}
function faviconFor(url) {
try {
const host = new URL(url).hostname;
return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(host)}&sz=128`;
} catch {
return "";
}
}
function parseRss(xml) {
const doc = new DOMParser().parseFromString(xml, "text/xml");
return [...doc.querySelectorAll("item")].slice(0, 3).map((item, i) => {
const title = item.querySelector("title")?.textContent || "";
const link = item.querySelector("link")?.textContent || "";
const sourceEl = item.querySelector("source");
const source = sourceEl?.textContent || item.querySelector("dc\\:creator")?.textContent || "Wire";
const sourceUrl = sourceEl?.getAttribute("url") || "";
const pub = item.querySelector("pubDate")?.textContent;
// Google News RSS items never carry an enclosure/media:content thumbnail,
// so fall back to the publisher's favicon as a small logo badge.
const thumb =
item.querySelector("enclosure")?.getAttribute("url") ||
item.querySelector("media\\:content")?.getAttribute("url") ||
faviconFor(sourceUrl || link);
return {
id: link || `${title}-${i}`,
title,
publisher: source,
link,
publishedAt: pub ? new Date(pub).getTime() : Date.now(),
thumbnail: thumb,
};
}).filter((item) => item.title && item.link);
}
// Yahoo's own finance-search endpoint (same one used for ticker search)
// returns a curated, on-topic news array with real article thumbnails.
// It's far more relevant than scraping Google News and doesn't get treated
// as abuse by the destination the way proxying Google News does.
async function newsFromYahoo(symbol, name) {
const label = name && name !== symbol ? name : symbol;
const json = await fetchYahoo(`/v1/finance/search?q=${encodeURIComponent(label)}"esCount=1&newsCount=6`);
return (json.news || [])
.filter((n) => n.title && n.link)
.slice(0, 3)
.map((n) => {
const pics = n.thumbnail?.resolutions || [];
return {
id: n.uuid || n.link,
title: n.title,
publisher: n.publisher || "Yahoo Finance",
link: n.link,
publishedAt: (n.providerPublishTime || 0) * 1000,
thumbnail: pics[pics.length - 1]?.url || faviconFor(n.link),
};
});
}
async function newsFromRss(symbol, name) {
// Ticker notation (BTC-USD, NOVO-B.CO, DANSKE.CO) never appears in article
// prose, and including it in the query badly confuses Google News' ranking
// - it starts surfacing loosely-related months-old articles over today's
// coverage. Search by the plain company/asset name only.
const label = name && name !== symbol ? name : symbol;
const query = encodeURIComponent(label);
const rssUrl = `https://news.google.com/rss/search?q=${query}&hl=en-US&gl=US&ceid=US:en`;
const xml = await fetchViaProxy(rssUrl);
const text = typeof xml === "string" ? xml : xml.contents || "";
return parseRss(text);
}
async function newsFromHn(symbol, name) {
const label = name && name !== symbol ? name : symbol.replace(/-USD$/, "");
const query = encodeURIComponent(isCrypto(null, symbol) ? label : `${label} stock`);
const json = await fetchJsonDirect(
`https://hn.algolia.com/api/v1/search_by_date?query=${query}&tags=story&hitsPerPage=8`,
);
// Algolia's search is fuzzy/full-text, not a strict match - a bare query
// like "BTC" or "Bitcoin" happily returns stories that only mention the
// term in passing (or not at all in the title). Require the title itself
// to actually be about it before treating a hit as real coverage.
const needle = label.toLowerCase();
return (json.hits || [])
.filter((hit) => hit.title && (hit.url || hit.story_url) && hit.title.toLowerCase().includes(needle))
.slice(0, 3)
.map((hit) => {
const link = hit.url || `https://news.ycombinator.com/item?id=${hit.objectID}`;
return {
id: String(hit.objectID),
title: hit.title,
publisher: "HN",
link,
publishedAt: (hit.created_at_i || 0) * 1000,
thumbnail: hit.url ? faviconFor(hit.url) : "",
};
});
}
const NEWS_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
// A "wire" implies current coverage - if the freshest match either source
// can find is months old, drop it rather than display it as if it were news.
function freshHeadlines(items) {
return items.filter((item) => state.now - item.publishedAt < NEWS_MAX_AGE_MS);
}
async function newsForHolding(holding) {
if (isCash(holding.symbol) || isOther(holding.symbol)) return [];
const quote = state.quotes[holding.symbol];
const name = quote?.name || holding.name;
try {
const yahoo = freshHeadlines(await newsFromYahoo(holding.symbol, name));
if (yahoo.length) return yahoo;