-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
1223 lines (1129 loc) · 32.6 KB
/
Copy pathserver.go
File metadata and controls
1223 lines (1129 loc) · 32.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
// Copyright 2026ff novatechflow (Alexander Alten)
// SPDX-License-Identifier: PolyForm-Shield-1.0.0
//
// polyDisplay aggregator server.
//
// Polls Polymarket + (Kraken-first, Coinbase-fallback) on its own schedule,
// caches the result, and serves ONE cheap endpoint (/api/state) plus the static
// web app. The browser therefore makes a single LAN request and never
// touches an external API, cert, rate limit, or geoblock.
//
// go run . # dev
// go build -o polydisplayd . # binary for launchd / systemd (see install.sh)
//
// Optional: CG_DEMO_KEY (CoinGecko). Watchlist: POLYDISPLAY_ASSETS in the
// process env or a .env file in the working directory (see .env.example).
package main
import (
_ "embed"
"encoding/json"
"fmt"
"io"
"log"
"math/rand/v2"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
)
//go:embed VERSION
var serverVersion string
/* ------------------------- config ------------------------- */
type Coin struct {
Sym string `json:"sym"`
Name string `json:"name"`
ID string `json:"id"` // CoinGecko id
Bn string `json:"bn,omitempty"` // legacy market-symbol override
}
type Config struct {
Wallet string `json:"wallet"`
CandleDays int `json:"candleDays"`
Port int `json:"port"`
Sort string `json:"sort"` // "az" (symbol A-Z) | "config" (as added)
Coins []Coin `json:"coins"`
}
const configPath = "config.json"
const envPath = ".env"
func defaultConfig() Config {
return Config{
Wallet: "",
CandleDays: 1,
Sort: "trades",
}
}
// KEY=VALUE lines. Existing process env wins. Quotes around values are stripped.
func loadEnvFile(path string) {
b, err := os.ReadFile(path)
if err != nil {
return
}
for _, line := range strings.Split(string(b), "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
k, v, ok := strings.Cut(line, "=")
if !ok {
continue
}
k = strings.TrimSpace(k)
v = strings.Trim(strings.TrimSpace(v), `"'`)
if k == "" || os.Getenv(k) != "" {
continue
}
os.Setenv(k, v)
}
}
// POLYDISPLAY_ASSETS=SYM:Name:id,SYM:id,... Name may contain spaces.
// Two fields → name defaults to SYM. A legacy fourth-field market override is
// reduced to its base symbol for Kraken and Coinbase.
func parseAssets(s string) []Coin {
var out []Coin
for _, item := range strings.Split(s, ",") {
item = strings.TrimSpace(item)
if item == "" {
continue
}
p := strings.SplitN(item, ":", 4)
var c Coin
switch len(p) {
case 2:
c = Coin{Sym: p[0], Name: p[0], ID: p[1]}
case 3:
c = Coin{Sym: p[0], Name: p[1], ID: p[2]}
case 4:
c = Coin{Sym: p[0], Name: p[1], ID: p[2], Bn: p[3]}
default:
continue
}
c.Sym = strings.TrimSpace(c.Sym)
c.Name = strings.TrimSpace(c.Name)
c.ID = strings.TrimSpace(c.ID)
c.Bn = strings.TrimSpace(c.Bn)
if c.Sym == "" || c.ID == "" {
continue
}
if c.Name == "" {
c.Name = c.Sym
}
out = append(out, c)
}
return out
}
func coinsFromEnv() []Coin {
return parseAssets(os.Getenv("POLYDISPLAY_ASSETS"))
}
// POLYDISPLAY_PORT wins; else config.json; else 8080.
func listenPort(file int) int {
if s := strings.TrimSpace(os.Getenv("POLYDISPLAY_PORT")); s != "" {
if p, err := strconv.Atoi(s); err == nil && p > 0 && p < 65536 {
return p
}
}
if file > 0 {
return file
}
return 8080
}
func loadConfig() Config {
c := defaultConfig()
b, err := os.ReadFile(configPath)
if err != nil {
saveConfig(c)
} else if json.Unmarshal(b, &c) != nil {
c = defaultConfig()
}
c.Port = listenPort(c.Port)
if c.CandleDays == 0 {
c.CandleDays = 7
}
if c.Sort == "" {
c.Sort = "trades"
}
if len(c.Coins) == 0 {
c.Coins = coinsFromEnv()
}
return c
}
// order coins for display per cfg.Sort
//
// "trades" (default): tokens in current Polymarket positions first, then A-Z
// "az": symbol A-Z "config": as added
func sortedCoins(coins []Coin, mode string, active map[string]bool) []Coin {
out := make([]Coin, len(coins))
copy(out, coins)
byAZ := func(i, j int) bool { return strings.ToUpper(out[i].Sym) < strings.ToUpper(out[j].Sym) }
switch mode {
case "config":
// keep as added
case "az":
sort.SliceStable(out, byAZ)
default: // "trades"
sort.SliceStable(out, func(i, j int) bool {
ai, aj := active[out[i].ID], active[out[j].ID]
if ai != aj {
return ai // traded assets float to the top
}
return byAZ(i, j)
})
}
return out
}
// which watchlist tokens are referenced by current Polymarket positions
// (e.g. a "Will Ethereum reach $X" market activates ETH)
func activeCoins(positions []Position, coins []Coin) map[string]bool {
active := map[string]bool{}
for _, p := range positions {
lt := strings.ToLower(p.Title)
for _, cn := range coins {
if strings.Contains(lt, strings.ToLower(cn.Name)) ||
(len(cn.Sym) >= 3 && strings.Contains(lt, strings.ToLower(cn.Sym))) {
active[cn.ID] = true
}
}
}
return active
}
func saveConfig(c Config) {
b, _ := json.MarshalIndent(c, "", " ")
os.WriteFile(configPath, b, 0644)
}
/* ------------------------- state ------------------------- */
type Candle [5]float64 // [openTimeMs, open, high, low, close]
type CoinState struct {
Sym string `json:"sym"`
Name string `json:"name"`
ID string `json:"id"`
Price float64 `json:"price"`
Chg24h float64 `json:"chg24h"`
Source string `json:"source"` // "kraken" | "coinbase" | ""
Active bool `json:"active"` // referenced by a current Polymarket position
Candles []Candle `json:"candles"`
Cand24 []Candle `json:"cand24"` // last 24h, whatever the display period
}
type Position struct {
Title string `json:"title"`
Outcome string `json:"outcome"`
Asset string `json:"asset"`
Size float64 `json:"size"`
AvgPrice float64 `json:"avgPrice"`
CurPrice float64 `json:"curPrice"`
Redeemable bool `json:"redeemable"`
CashPnl float64 `json:"cashPnl"`
PercentPnl float64 `json:"percentPnl"`
CurrentValue float64 `json:"currentValue"`
ConditionID string `json:"conditionId"`
EndDate string `json:"endDate"`
Slug string `json:"slug,omitempty"`
EventSlug string `json:"eventSlug,omitempty"`
PriceToBeat *float64 `json:"priceToBeat,omitempty"`
}
type Act struct {
Time int64 `json:"t"`
Type string `json:"type"` // TRADE, REDEEM, MERGE, SPLIT, REWARD, ...
Side string `json:"side"` // BUY / SELL (for TRADE)
Size float64 `json:"size"`
Price float64 `json:"price"`
Usdc float64 `json:"usdc"`
Title string `json:"title"`
Outcome string `json:"outcome"`
}
// Portfolio P/L over the whole account history (realized + unrealized), from
// Polymarket's user-pnl feed. The open positions' own value and P/L are summed
// in the column header, not here.
type PnL struct {
Total float64 `json:"total"` // all-time, realized + unrealized
D1 *float64 `json:"d1"` // the day's P/L, as polymarket.com shows it
D7 *float64 `json:"d7"`
D30 *float64 `json:"d30"`
Series [][2]float64 `json:"series"`
}
type State struct {
Version string `json:"version"`
Updated int64 `json:"updated"`
Wallet string `json:"wallet"`
CandleDays int `json:"candleDays"`
Positions []Position `json:"positions"`
Coins []CoinState `json:"coins"`
Activity []Act `json:"activity"`
Pnl *PnL `json:"pnl,omitempty"`
Note string `json:"note"`
}
var (
mu sync.RWMutex
cfg Config
state State
candles = map[string][]Candle{} // id -> candles (refreshed slowly)
cand24 = map[string][]Candle{} // id -> last 24h, for the trend read
csource = map[string]string{} // id -> candle source
marketPrice = map[string]float64{} // id -> last good spot price
slowMu sync.Mutex
// Fresh connection per request: a VPN's short idle timeout was dropping the
// pooled keep-alive connections during the 20s gap between cycles, so the
// first couple of requests each cycle failed (BTC/ETH showed price 0).
client = &http.Client{
Timeout: 12 * time.Second,
Transport: &http.Transport{Proxy: http.ProxyFromEnvironment, DisableKeepAlives: true},
}
trigger = make(chan struct{}, 1)
)
/* --------------------- Polymarket pacing --------------------- */
//
// The APIs are rate limited per public IP by Cloudflare. Keep each endpoint on
// its own schedule, space calls to the shared Data API host, and add jitter so
// multiple clients behind the same egress do not synchronize their requests.
// data-api host; a var so tests can point it at a stub
var polyBase = "https://data-api.polymarket.com"
const (
positionsInterval = 30 * time.Second
activityInterval = time.Minute
pnlInterval = 30 * time.Minute
dataAPIMinGap = 5 * time.Second
activityStartWait = 10 * time.Second
pnlStartWait = 20 * time.Second
polyBackoffMin = time.Minute
polyBackoffMax = 30 * time.Minute
)
type pollSchedule struct {
nextAt time.Time
backoff time.Duration
}
var (
positionsPoll pollSchedule
activityPoll pollSchedule
pnlPoll pollSchedule
dataAPILastAt time.Time
polyWallet string // wallet the cached positions/activity belong to
lastPositions []Position
lastActivity []Act
)
// The P/L series is a separate host with its own history-sized response, and it
// only moves as fast as prices do, so it gets a slower cadence of its own.
var pnlBase = "https://user-pnl-api.polymarket.com"
const pnlSeriesMax = 120 // points kept for the sparkline
var pnlSeries [][2]float64
func jitter(d time.Duration) time.Duration {
if d <= 0 {
return d
}
// Positive-only jitter preserves minimum delays and Retry-After semantics.
return d + time.Duration(rand.Int64N(max(1, int64(d/10))))
}
func (p *pollSchedule) success(now time.Time, interval time.Duration) {
p.backoff = 0
p.nextAt = now.Add(jitter(interval))
}
func (p *pollSchedule) failed(now time.Time, retryAfter time.Duration) time.Duration {
if p.backoff == 0 {
p.backoff = polyBackoffMin
} else if p.backoff < polyBackoffMax {
p.backoff *= 2
}
if p.backoff > polyBackoffMax {
p.backoff = polyBackoffMax
}
wait := jitter(p.backoff)
if retryAfter > wait {
wait = retryAfter
}
p.nextAt = now.Add(wait)
return wait
}
func polyBackoffNote(p pollSchedule) string {
return fmt.Sprintf("polymarket: rate limited, retrying in %s",
time.Until(p.nextAt).Round(time.Second))
}
/* ------------------------- HTTP helpers ------------------------- */
// httpError carries the upstream status so callers can treat 429 specially.
type httpError struct {
Status int
RetryAfter time.Duration // from the Retry-After header, 0 if absent
}
func (e *httpError) Error() string { return fmt.Sprintf("HTTP %d", e.Status) }
// Retry-After is either a delay in seconds or an HTTP date.
func parseRetryAfter(v string) time.Duration {
if v == "" {
return 0
}
if secs, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
if t, err := http.ParseTime(v); err == nil {
if d := time.Until(t); d > 0 {
return d
}
}
return 0
}
// host+path only - keeps the wallet and query noise out of the log line
func shortURL(raw string) string {
if i := strings.Index(raw, "?"); i >= 0 {
raw = raw[:i]
}
return strings.TrimPrefix(strings.TrimPrefix(raw, "https://"), "http://")
}
// Log upstream failures, but collapse repeats so a temporary provider outage
// does not bury the first useful error in repeated refresh attempts.
const upstreamLogEvery = 10 * time.Minute
var (
upstreamLogMu sync.Mutex
upstreamLoggedAt = map[string]time.Time{}
)
func logUpstream(url string, outcome interface{}) {
key := fmt.Sprintf("%s|%v", shortURL(url), outcome)
upstreamLogMu.Lock()
last, seen := upstreamLoggedAt[key]
fresh := !seen || time.Since(last) >= upstreamLogEvery
if fresh {
upstreamLoggedAt[key] = time.Now()
}
upstreamLogMu.Unlock()
if fresh {
log.Printf("upstream %s -> %v", shortURL(url), outcome)
}
}
func getJSON(url string, out interface{}, headers map[string]string) error {
var lastErr error
for attempt := 0; attempt < 2; attempt++ { // retry once on a network error
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
lastErr = err
continue
}
if resp.StatusCode != 200 {
ra := parseRetryAfter(resp.Header.Get("Retry-After"))
resp.Body.Close()
err := &httpError{Status: resp.StatusCode, RetryAfter: ra}
logUpstream(url, err)
return err
}
b, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
resp.Body.Close()
if err != nil {
lastErr = err
continue
}
return json.Unmarshal(b, out)
}
if lastErr != nil {
logUpstream(url, lastErr)
}
return lastErr
}
func cgHeaders() map[string]string {
if k := os.Getenv("CG_DEMO_KEY"); k != "" {
return map[string]string{"x-cg-demo-api-key": k}
}
return nil
}
/* ------------------------- data fetchers ------------------------- */
var (
krakenBase = "https://api.kraken.com"
coinbaseBase = "https://api.exchange.coinbase.com"
)
func marketSymbol(c Coin) string {
s := strings.ToUpper(strings.TrimSpace(c.Sym))
if c.Bn != "" { // accept old fourth-field values such as WIFUSDT
s = strings.ToUpper(strings.TrimSpace(c.Bn))
for _, suffix := range []string{"USDT", "USD"} {
s = strings.TrimSuffix(s, suffix)
}
s = strings.TrimRight(s, "-/")
}
return s
}
func krakenPair(c Coin) string {
s := marketSymbol(c)
if s == "BTC" {
s = "XBT"
}
return s + "USD"
}
func coinbaseProduct(c Coin) string { return marketSymbol(c) + "-USD" }
func candleParams(days int, provider string) (interval, limit int) {
if provider == "kraken" {
switch {
case days <= 1:
return 30, 48
case days <= 7:
return 240, 42
case days <= 14:
return 240, 84
default:
return 240, 180
}
}
switch {
case days <= 1:
return 900, 96
case days <= 7:
return 3600, 168
case days <= 14:
return 21600, 56
default:
return 21600, 120
}
}
func trimCandles(in []Candle, limit int) []Candle {
sort.Slice(in, func(i, j int) bool { return in[i][0] < in[j][0] })
if len(in) > limit {
return in[len(in)-limit:]
}
return in
}
func fetchKrakenCandles(c Coin, days int) ([]Candle, error) {
interval, limit := candleParams(days, "kraken")
q := url.Values{}
q.Set("pair", krakenPair(c))
q.Set("interval", strconv.Itoa(interval))
q.Set("assetVersion", "1")
q.Set("since", strconv.FormatInt(time.Now().Add(-time.Duration(days)*24*time.Hour).Unix(), 10))
u := krakenBase + "/0/public/OHLC?" + q.Encode()
var raw struct {
Error []string `json:"error"`
Result map[string]json.RawMessage `json:"result"`
}
if err := getJSON(u, &raw, nil); err != nil {
return nil, err
}
if len(raw.Error) > 0 {
return nil, fmt.Errorf("%s", strings.Join(raw.Error, ", "))
}
var rows [][]interface{}
for key, value := range raw.Result {
if key != "last" && json.Unmarshal(value, &rows) == nil {
break
}
}
out := make([]Candle, 0, len(rows))
for _, k := range rows {
if len(k) < 5 {
continue
}
t, _ := strconv.ParseFloat(fmt.Sprint(k[0]), 64)
o, _ := strconv.ParseFloat(fmt.Sprint(k[1]), 64)
h, _ := strconv.ParseFloat(fmt.Sprint(k[2]), 64)
l, _ := strconv.ParseFloat(fmt.Sprint(k[3]), 64)
cl, _ := strconv.ParseFloat(fmt.Sprint(k[4]), 64)
out = append(out, Candle{t * 1000, o, h, l, cl})
}
if len(out) == 0 {
return nil, fmt.Errorf("empty")
}
return trimCandles(out, limit), nil
}
func fetchCoinbaseCandles(c Coin, days int) ([]Candle, error) {
granularity, limit := candleParams(days, "coinbase")
end := time.Now().UTC()
q := url.Values{}
q.Set("granularity", strconv.Itoa(granularity))
q.Set("start", end.Add(-time.Duration(days)*24*time.Hour).Format(time.RFC3339))
q.Set("end", end.Format(time.RFC3339))
u := coinbaseBase + "/products/" + url.PathEscape(coinbaseProduct(c)) + "/candles?" + q.Encode()
var raw [][]float64
if err := getJSON(u, &raw, nil); err != nil {
return nil, err
}
out := make([]Candle, 0, len(raw))
for _, k := range raw {
if len(k) >= 5 {
out = append(out, Candle{k[0] * 1000, k[3], k[2], k[1], k[4]})
}
}
if len(out) == 0 {
return nil, fmt.Errorf("empty")
}
return trimCandles(out, limit), nil
}
func fetchMarketCandles(c Coin, days int) ([]Candle, string, error) {
cs, kerr := fetchKrakenCandles(c, days)
if kerr == nil {
return cs, "kraken", nil
}
cs, cerr := fetchCoinbaseCandles(c, days)
if cerr == nil {
return cs, "coinbase", nil
}
return nil, "", fmt.Errorf("kraken: %v; coinbase: %v", kerr, cerr)
}
func pairKey(s string) string {
s = strings.NewReplacer("/", "", "-", "").Replace(strings.ToUpper(s))
if strings.HasPrefix(s, "XBT") {
s = "BTC" + strings.TrimPrefix(s, "XBT")
}
return s
}
func fetchKrakenPrices(coins []Coin) (map[string]float64, error) {
if len(coins) == 0 {
return map[string]float64{}, nil
}
pairs := make([]string, 0, len(coins))
ids := map[string]string{}
for _, c := range coins {
pair := krakenPair(c)
pairs = append(pairs, pair)
ids[pairKey(pair)] = c.ID
}
u := krakenBase + "/0/public/Ticker?pair=" + url.QueryEscape(strings.Join(pairs, ",")) + "&assetVersion=1"
var raw struct {
Error []string `json:"error"`
Result map[string]struct {
Close []string `json:"c"`
} `json:"result"`
}
if err := getJSON(u, &raw, nil); err != nil {
return nil, err
}
if len(raw.Error) > 0 {
return nil, fmt.Errorf("%s", strings.Join(raw.Error, ", "))
}
out := map[string]float64{}
for pair, ticker := range raw.Result {
id, ok := ids[pairKey(pair)]
if !ok || len(ticker.Close) == 0 {
continue
}
if p, err := strconv.ParseFloat(ticker.Close[0], 64); err == nil && p > 0 {
out[id] = p
}
}
return out, nil
}
func fetchCoinbasePrice(c Coin) (float64, error) {
var raw struct {
Price string `json:"price"`
}
u := coinbaseBase + "/products/" + url.PathEscape(coinbaseProduct(c)) + "/ticker"
if err := getJSON(u, &raw, nil); err != nil {
return 0, err
}
p, err := strconv.ParseFloat(raw.Price, 64)
if err != nil || p <= 0 {
return 0, fmt.Errorf("no price")
}
return p, nil
}
func candleChange24(price float64, data []Candle) float64 {
if price <= 0 || len(data) == 0 || data[0][1] <= 0 {
return 0
}
return (price/data[0][1] - 1) * 100
}
func fetchPositions(wallet string) ([]Position, error) {
url := polyBase + "/positions?user=" + wallet +
"&sizeThreshold=0.1&limit=100&sortBy=CURRENT&sortDirection=DESC"
var out []Position
err := getJSON(url, &out, nil)
open := out[:0]
for _, p := range out {
if p.Redeemable && p.CurPrice == 0 {
continue
}
open = append(open, p)
}
out = open
fillMarketMetadata(out)
// Soonest resolution first; undated last. ISO timestamps sort as strings.
sort.SliceStable(out, func(i, j int) bool {
a, b := out[i].EndDate, out[j].EndDate
if (a == "") != (b == "") {
return b == ""
}
return a < b
})
return out, err
}
// gamma host; a var so tests can point it at a stub
var gammaBase = "https://gamma-api.polymarket.com"
type marketMeta struct {
EndDate string
PriceToBeat *float64
}
// End times never move once a market exists. Up/Down reference prices can
// appear after the market metadata is first published, so retry those until set.
var marketMetadata = map[string]marketMeta{}
func normID(id string) string {
return strings.ToLower(strings.TrimSpace(id))
}
func isUpDown(p Position) bool {
if strings.EqualFold(p.Outcome, "up") || strings.EqualFold(p.Outcome, "down") {
return true
}
s := strings.ToLower(p.EventSlug + " " + p.Slug + " " + p.Title)
return strings.Contains(s, "updown") ||
strings.Contains(s, "up-down") ||
strings.Contains(s, "up/down") ||
strings.Contains(s, "up or down") ||
strings.Contains(s, "up-or-down")
}
// /positions only carries a date ("2026-08-12"), which can't separate a market
// closing at noon from one closing at 18:00. gamma has the full timestamp.
func fillMarketMetadata(pos []Position) {
var missing []string
seen := map[string]bool{}
for _, p := range pos {
cid := normID(p.ConditionID)
if cid == "" {
continue
}
meta, ok := marketMetadata[cid]
needsPrice := isUpDown(p) && meta.PriceToBeat == nil
if (!ok || needsPrice) && !seen[cid] {
seen[cid] = true
missing = append(missing, p.ConditionID)
}
}
for len(missing) > 0 {
n := min(len(missing), 20)
if err := loadMarketMetadata(missing[:n]); err != nil {
log.Printf("gamma: end times unavailable, sorting by date: %v", err)
break
}
missing = missing[n:]
}
for i, p := range pos {
if meta, ok := marketMetadata[normID(p.ConditionID)]; ok {
if meta.EndDate != "" {
pos[i].EndDate = meta.EndDate
}
pos[i].PriceToBeat = meta.PriceToBeat
}
}
}
func loadMarketMetadata(ids []string) error {
url := gammaBase + "/markets?limit=" + strconv.Itoa(len(ids))
for _, id := range ids {
url += "&condition_ids=" + id
}
var raw []struct {
ConditionID string `json:"conditionId"`
EndDate string `json:"endDate"`
PriceToBeat *float64 `json:"priceToBeat"`
EventMetadata struct {
PriceToBeat *float64 `json:"priceToBeat"`
} `json:"eventMetadata"`
Events []struct {
EventMetadata struct {
PriceToBeat *float64 `json:"priceToBeat"`
} `json:"eventMetadata"`
} `json:"events"`
}
if err := getJSON(url, &raw, nil); err != nil {
return err
}
for _, m := range raw {
cid := normID(m.ConditionID)
meta := marketMeta{EndDate: m.EndDate}
if prev, ok := marketMetadata[cid]; ok && prev.PriceToBeat != nil {
meta.PriceToBeat = prev.PriceToBeat
}
if m.PriceToBeat != nil && *m.PriceToBeat > 0 {
meta.PriceToBeat = m.PriceToBeat
} else if m.EventMetadata.PriceToBeat != nil && *m.EventMetadata.PriceToBeat > 0 {
meta.PriceToBeat = m.EventMetadata.PriceToBeat
}
for _, event := range m.Events {
if event.EventMetadata.PriceToBeat != nil && *event.EventMetadata.PriceToBeat > 0 {
meta.PriceToBeat = event.EventMetadata.PriceToBeat
break
}
}
marketMetadata[cid] = meta
}
// Cache the misses too, so an unknown market isn't re-queried every cycle.
for _, id := range ids {
cid := normID(id)
if _, ok := marketMetadata[cid]; !ok {
marketMetadata[cid] = marketMeta{}
}
}
return nil
}
func fetchActivity(wallet string) ([]Act, error) {
url := polyBase + "/activity?user=" + wallet + "&limit=20"
var raw []struct {
Timestamp int64 `json:"timestamp"`
Type string `json:"type"`
Side string `json:"side"`
Size float64 `json:"size"`
Price float64 `json:"price"`
UsdcSize float64 `json:"usdcSize"`
Title string `json:"title"`
Outcome string `json:"outcome"`
}
if err := getJSON(url, &raw, nil); err != nil {
return nil, err
}
out := make([]Act, 0, len(raw))
for _, a := range raw {
out = append(out, Act{a.Timestamp, a.Type, a.Side, a.Size, a.Price, a.UsdcSize, a.Title, a.Outcome})
}
return out, nil
}
// Cumulative account P/L, hourly over the last 30 days.
func fetchPnlSeries(wallet string) ([][2]float64, error) {
url := pnlBase + "/user-pnl?user_address=" + wallet + "&interval=1m&fidelity=1h"
var raw []struct {
T int64 `json:"t"`
P float64 `json:"p"`
}
if err := getJSON(url, &raw, nil); err != nil {
return nil, err
}
if len(raw) == 0 {
return nil, fmt.Errorf("empty")
}
out := make([][2]float64, 0, len(raw))
for _, p := range raw {
out = append(out, [2]float64{float64(p.T), p.P})
}
return out, nil
}
// Change over a trailing number of hourly samples. Polymarket's own profile
// anchors this by sample, not by clock: its "1D" series is 24 hourly points
// spanning 23h, so the day's P/L is the change against the point 24 samples
// back. Matching that anchor makes the card agree with polymarket.com exactly.
// nil when the series is too young to cover the window.
func pnlDelta(series [][2]float64, samples int) *float64 {
i := len(series) - samples
if len(series) < 2 || samples < 1 || i < 0 {
return nil
}
d := series[len(series)-1][1] - series[i][1]
return &d
}
// Thin to at most max points, always keeping the first and last.
func thin(series [][2]float64, max int) [][2]float64 {
if len(series) <= max || max < 2 {
return series
}
out := make([][2]float64, 0, max)
step := float64(len(series)-1) / float64(max-1)
for i := 0; i < max-1; i++ {
out = append(out, series[int(float64(i)*step)])
}
return append(out, series[len(series)-1])
}
func buildPnl(series [][2]float64) *PnL {
if len(series) == 0 {
return nil
}
return &PnL{
Total: series[len(series)-1][1],
D1: pnlDelta(series, 24),
D7: pnlDelta(series, 7*24),
D30: pnlDelta(series, 30*24),
Series: thin(series, pnlSeriesMax),
}
}
// refresh the cached P/L series when it's due; failures keep the last one
func refreshPnl(wallet string, now time.Time) {
if wallet == "" || now.Before(pnlPoll.nextAt) {
return
}
s, err := fetchPnlSeries(wallet)
if err == nil {
pnlSeries = s
pnlPoll.success(now, pnlInterval)
return
}
var retryAfter time.Duration
if he, ok := err.(*httpError); ok && he.Status == 429 {
retryAfter = he.RetryAfter
}
wait := pnlPoll.failed(now, retryAfter)
log.Printf("polymarket pnl: request failed, backing off %s", wait.Round(time.Second))
}
/* ------------------------- refresh loops ------------------------- */
// fast: positions + live prices (every 20s)
func refreshFast() {
mu.RLock()
c := cfg
mu.RUnlock()
now := time.Now()
note := ""
positions, activity := lastPositions, lastActivity
wallet := strings.TrimSpace(c.Wallet)
if wallet != polyWallet { // wallet changed -> refetch now, drop stale data
polyWallet = wallet
positionsPoll = pollSchedule{}
activityPoll = pollSchedule{nextAt: now.Add(activityStartWait)}
pnlPoll = pollSchedule{nextAt: now.Add(pnlStartWait)}
dataAPILastAt = time.Time{}
positions, activity = nil, nil
pnlSeries = nil
}
if wallet == "" {
positions, activity = nil, nil
} else if now.Before(positionsPoll.nextAt) {
if positionsPoll.backoff > 0 { // say why positions are stale
note = polyBackoffNote(positionsPoll)
}
} else {
p, err := fetchPositions(wallet)
finishedAt := time.Now()
dataAPILastAt = finishedAt
he, isHTTP := err.(*httpError)
switch {
case err == nil:
positions = p
positionsPoll.success(finishedAt, positionsInterval)
case isHTTP && he.Status == 429:
wait := positionsPoll.failed(finishedAt, he.RetryAfter)
log.Printf("polymarket positions: rate limited, backing off %s", wait.Round(time.Second))
note = polyBackoffNote(positionsPoll)
default:
note = "polymarket: " + err.Error()
wait := positionsPoll.failed(finishedAt, 0)
log.Printf("polymarket positions: request failed, backing off %s", wait.Round(time.Second))
}
}
// Never burst activity immediately after positions on the shared Data API.
if wallet != "" && !now.Before(activityPoll.nextAt) &&
(dataAPILastAt.IsZero() || now.Sub(dataAPILastAt) >= dataAPIMinGap) {
a, err := fetchActivity(wallet)
finishedAt := time.Now()
dataAPILastAt = finishedAt
he, isHTTP := err.(*httpError)
switch {
case err == nil:
activity = a
activityPoll.success(finishedAt, activityInterval)
case isHTTP && he.Status == 429:
wait := activityPoll.failed(finishedAt, he.RetryAfter)
log.Printf("polymarket activity: rate limited, backing off %s", wait.Round(time.Second))
default:
wait := activityPoll.failed(finishedAt, 0)
log.Printf("polymarket activity: request failed, backing off %s", wait.Round(time.Second))
}
}
lastPositions, lastActivity = positions, activity
if wallet == "" {
pnlSeries = nil
} else {
refreshPnl(wallet, time.Now())
}
// Kraken returns all requested tickers in one call. Only missing pairs fall
// back to Coinbase, and the last good price survives a provider outage.
prices, _ := fetchKrakenPrices(c.Coins)
if prices == nil {
prices = map[string]float64{}
}