-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1749 lines (1510 loc) · 64.6 KB
/
cli.py
File metadata and controls
1749 lines (1510 loc) · 64.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
#!/usr/bin/env python3
"""Kalshi CLI - Prediction market trading tool"""
import os
import sys
import time
import base64
import requests
import typer
from rich.table import Table
from rich.console import Console
from rich.panel import Panel
from rich.columns import Columns
from rich import box
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding
app = typer.Typer(help="Kalshi prediction market CLI")
BASE_URL = "https://api.elections.kalshi.com"
console = Console()
class ApiError(Exception):
"""Raised on non-success API responses (catchable, unlike typer.Exit)"""
def __init__(self, status_code: int, message: str):
self.status_code = status_code
self.message = message
super().__init__(f"API Error {status_code}: {message}")
# ── Auth & API ──────────────────────────────────────────────
def load_env():
"""Load credentials from ~/.kalshi/.env"""
env_path = os.path.expanduser("~/.kalshi/.env")
if not os.path.exists(env_path):
return
with open(env_path, "r") as f:
for line in f:
if line.startswith("export "):
line = line[7:]
if "=" in line:
key, val = line.strip().split("=", 1)
os.environ[key] = val.strip('"').strip("'")
def load_key():
"""Load RSA private key from env var or file"""
raw = os.getenv("KALSHI_ACCESS_PRIVATE_KEY")
if raw:
try:
return serialization.load_pem_private_key(raw.encode(), password=None)
except Exception:
pass
for p in ["~/.kalshi/private_key.pem", "private_key.pem"]:
expanded = os.path.expanduser(p)
if os.path.exists(expanded):
with open(expanded, "rb") as f:
return serialization.load_pem_private_key(f.read(), password=None)
console.print("[red]Error:[/red] No private key found. Place your RSA key at ~/.kalshi/private_key.pem")
raise typer.Exit(1)
def sign_request(ts: str, method: str, path: str, key) -> str:
"""Create API request signature"""
msg = ts + method + path
sig = key.sign(
msg.encode(),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
),
hashes.SHA256(),
)
return base64.b64encode(sig).decode()
def api(method: str, endpoint: str, body: dict = None) -> dict:
"""Make an authenticated Kalshi API request"""
load_env()
key_id = os.getenv("KALSHI_ACCESS_KEY")
if not key_id:
console.print(
"[red]Error:[/red] KALSHI_ACCESS_KEY not set. "
"Run [bold]kalshi setup-shell[/bold] or set it in ~/.kalshi/.env"
)
raise typer.Exit(1)
key = load_key()
ts = str(int(time.time() * 1000))
path = "/trade-api/v2/" + endpoint
path_no_query = path.split("?")[0]
sig = sign_request(ts, method, path_no_query, key)
headers = {
"KALSHI-ACCESS-KEY": key_id,
"KALSHI-ACCESS-SIGNATURE": sig,
"KALSHI-ACCESS-TIMESTAMP": ts,
"Content-Type": "application/json",
}
url = BASE_URL + path
timeout = 10
try:
if method == "GET":
r = requests.get(url, headers=headers, timeout=timeout)
elif method == "POST":
r = requests.post(url, headers=headers, json=body, timeout=timeout)
elif method == "DELETE":
r = requests.delete(url, headers=headers, timeout=timeout)
else:
console.print(f"[red]Unsupported HTTP method:[/red] {method}")
raise typer.Exit(1)
except requests.exceptions.RequestException as e:
raise ApiError(0, f"Network error: {e}") from e
if r.status_code not in (200, 201, 204):
raise ApiError(r.status_code, r.text)
if r.status_code == 204:
return {}
return r.json()
# ── Display Helpers ─────────────────────────────────────────
def fmt_price(dollars) -> str:
"""Format a dollar price as '$0.68 (68%)'"""
if dollars is None or dollars == "N/A":
return "—"
try:
d = float(dollars)
pct = d * 100
return f"${d:.2f} ({pct:.0f}%)"
except (ValueError, TypeError):
return str(dollars)
def fmt_dollars(val) -> str:
"""Format a plain dollar amount"""
if val is None:
return "—"
try:
return f"${float(val):.2f}"
except (ValueError, TypeError):
return str(val)
def filter_by_min_odds(markets: list, min_odds: float) -> list:
"""Filter out markets where either yes or no bid is below min_odds (as %)"""
if min_odds <= 0:
return markets
threshold = min_odds / 100 # convert % to dollar value (e.g. 0.5% → 0.005)
filtered = []
for m in markets:
yes = float(m.get("yes_bid_dollars", 0) or 0)
no = float(m.get("no_bid_dollars", 0) or 0)
if yes >= threshold and no >= threshold:
filtered.append(m)
return filtered
def _parse_expiry_from_ticker(ticker: str):
"""If ticker has segment like 26FEB161745 (DDMMMHHMMSS), return ISO ts in UTC.
For 15M/5M series the segment is window start; add 15 or 5 minutes for close time.
"""
import re
from datetime import datetime, timezone, timedelta
if not ticker or "-" not in ticker:
return None
parts = ticker.split("-")
for part in parts:
if len(part) == 11 and re.match(r"\d{2}[A-Z]{3}\d{6}$", part):
try:
day = int(part[:2])
mon = {"JAN": 1, "FEB": 2, "MAR": 3, "APR": 4, "MAY": 5, "JUN": 6,
"JUL": 7, "AUG": 8, "SEP": 9, "OCT": 10, "NOV": 11, "DEC": 12}.get(part[2:5])
if not mon:
continue
h, mi, s = int(part[5:7]), int(part[7:9]), int(part[9:11])
now = datetime.now(timezone.utc)
year = now.year
dt = datetime(year, mon, day, h, mi, s, tzinfo=timezone.utc)
if dt <= now:
year += 1
dt = datetime(year, mon, day, h, mi, s, tzinfo=timezone.utc)
# 15m/5m markets: ticker time is window start, close = start + window
ticker_upper = ticker.upper()
if "15M" in ticker_upper:
dt = dt + timedelta(minutes=15)
elif "5M" in ticker_upper:
dt = dt + timedelta(minutes=5)
return dt.isoformat()
except (ValueError, KeyError):
pass
return None
def _market_expiry_ts(m: dict) -> str:
"""Best expiry timestamp: API fields first, then parsed from ticker for 15m-style markets."""
ts = (
m.get("expected_expiration_time")
or m.get("close_time")
or m.get("expiration_time")
or m.get("latest_expiration_time")
or ""
)
if ts:
return ts
ticker = m.get("ticker", "")
if ticker and ("15M" in ticker.upper() or "5M" in ticker.upper()):
parsed = _parse_expiry_from_ticker(ticker)
if parsed:
return parsed
return ""
def sort_by_expiry(markets: list) -> list:
"""Filter out expired markets, then sort by expiration ascending (soonest first).
Markets without an expiration are pushed to the end.
"""
from datetime import datetime, timezone
now = datetime.now(timezone.utc).isoformat()
future = []
for m in markets:
exp = _market_expiry_ts(m)
if exp and exp < now:
continue # skip expired
future.append(m)
def key(m):
exp = _market_expiry_ts(m)
return exp if exp else "9999"
return sorted(future, key=key)
def fmt_expiry(raw) -> str:
"""Format an expiration timestamp into a short human-readable string."""
if not raw:
return "—"
try:
from datetime import datetime, timezone
# Handle ISO format (e.g. "2026-02-08T23:30:00Z")
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
now = datetime.now(timezone.utc)
delta = dt - now
days = delta.days
if days < 0:
return "expired"
if days == 0:
hours = delta.seconds // 3600
mins = (delta.seconds % 3600) // 60
if hours > 0:
return f"{hours}h {mins}m"
return f"{mins}m"
if days < 7:
return dt.strftime("%a %I:%M%p")
if dt.year != now.year:
return dt.strftime("%b %d, %Y")
return dt.strftime("%b %d")
except Exception:
return str(raw)[:16]
def is_parlay(m: dict) -> bool:
"""Detect parlay/combo markets by checking for multiple comma-separated legs."""
for field in ("yes_sub_title", "no_sub_title", "title"):
val = m.get(field, "") or ""
if val.count(",") >= 2:
return True
return False
def _fmt_legs(text: str) -> str:
"""Format comma-separated parlay legs as one leg per line."""
if not text:
return text
parts = [p.strip() for p in text.split(",") if p.strip()]
if len(parts) <= 1:
return text
return "\n".join(parts)
def _is_binary_yes_no_market(title: str) -> bool:
"""True if the market is a single yes/no proposition (e.g. 'Will Gavin Newsom be...' or 'Team X wins by over 2.5 points') not a multi-outcome pick."""
if not title:
return False
t = title.strip().lower()
# "Will [X] be/have/win..." = one proposition → binary
if t.startswith("will ") and (" be " in t or " win " in t or " have " in t or " the " in t):
return True
# Spread markets: "Team wins by over X points" = binary
if "wins by over" in t and "points" in t:
return True
return False
def _position_side_label(yes_sub: str, no_sub: str, position: int, title: str = "") -> str:
"""Side column: multifaceted markets show the choice (e.g. Anduril, May 31 2026); yes/no markets show Yes or No."""
if position < 0:
return "No"
if _is_binary_yes_no_market(title):
return "Yes"
# Holding Yes: show outcome name for multi-outcome markets, else "Yes"
sub = yes_sub or ""
if not sub:
return "Yes"
parts = [p.strip() for p in sub.split(",") if p.strip()]
if len(parts) >= 2 and all(
p.lower().startswith("yes ") or p.lower().startswith("no ") for p in parts
):
return "Yes"
if sub.strip().lower().startswith("yes "):
return sub.strip()[4:].strip()
if sub.strip().lower().startswith("no "):
return sub.strip()[3:].strip()
return sub.strip()
def _parse_leg(leg: str) -> tuple:
"""Split a leg into (outcome, title). Outcome is 'yes'/'no', title is the proposition."""
leg = leg.strip()
if leg.lower().startswith("yes "):
return ("yes", leg[4:].strip())
if leg.lower().startswith("no "):
return ("no", leg[3:].strip())
return ("yes", leg)
def _outcome_from_ticker(ticker: str) -> str:
"""Derive a short outcome label from market ticker (e.g. range/strike suffix). KXBTC-95-96 -> 95-96; KXBTC-26FEB0917-B74250 -> $97,425)."""
if not ticker or "-" not in ticker:
return ""
parts = ticker.split("-")
if len(parts) >= 3:
suffix = "-".join(parts[-2:]) # e.g. 95-96 or 26FEB0917-B74250
# Price-range style: last segment is strike in dollars (e.g. B74250 → $74,250 or above)
last = parts[-1]
if len(last) >= 4 and last[0].isalpha() and last[1:].isdigit():
try:
num = int(last[1:])
# 1 letter + 4 digits: letter = leading digit (A=0..I=9), e.g. I7425 → 97425
if len(last) == 5 and last[0].upper() in "ABCDEFGHIJ":
lead = "ABCDEFGHIJ".index(last[0].upper())
num = lead * 10000 + num
if num >= 1000:
return f"${num:,} or above"
except ValueError:
pass
if len(last) >= 2 and last.isdigit():
try:
num = int(last)
if num >= 1000:
return f"${num:,} or above"
except ValueError:
pass
return suffix
return parts[-1] if parts else ""
def _is_generic_subtitle(sub: str) -> bool:
"""True if subtitle is just 'yes'/'no' with no actual outcome label (e.g. range markets)."""
s = (sub or "").strip().lower()
return s in ("yes", "no")
def _is_parlay_subtitle(sub: str) -> bool:
"""True if subtitle looks like parlay legs: 'Yes Team A wins, No Team B wins'."""
parts = [p.strip() for p in sub.split(",") if p.strip()]
if len(parts) < 2:
return False
return all(
p.lower().startswith("yes ") or p.lower().startswith("no ")
for p in parts
)
def _outcome_column(m: dict) -> str:
"""Outcome column: for binary Yes/No markets, color YES green or NO red based on higher %.
For multi-outcome markets: returns the outcome name.
For parlays: returns yes/no per leg.
"""
title = m.get("title", "") or ""
# Binary Yes/No markets: show YES or NO based on higher percentage
if _is_binary_yes_no_market(title):
yes_price = float(m.get("yes_bid_dollars", 0) or 0)
no_price = float(m.get("no_bid_dollars", 0) or 0)
if yes_price > no_price:
return "[green]YES[/green]"
elif no_price > yes_price:
return "[red]NO[/red]"
else:
return "YES"
# Try subtitle (for multi-outcome markets like Olympics, player props)
sub = m.get("yes_sub_title", "") or m.get("no_sub_title", "") or ""
if sub and not _is_generic_subtitle(sub):
if _is_parlay_subtitle(sub):
# Parlay: show yes/no per leg
parts = [p.strip() for p in sub.split(",") if p.strip()]
return "\n".join(_parse_leg(p)[0] for p in parts)
# Single outcome: strip "Yes "/"No " prefix if present
return _parse_leg(sub.strip())[1]
# Fall back to strike/range from API or ticker
out = m.get("strike") or m.get("strike_price") or m.get("resolution_value")
if out is not None and str(out).strip():
return str(out).strip()
ticker = m.get("ticker", "") or m.get("market_ticker", "") or ""
out = _outcome_from_ticker(ticker)
if out:
return out
return "Yes"
def _normalize_title(raw: str) -> str:
"""Single line: collapse newlines and extra spaces."""
if not raw:
return ""
return " ".join(str(raw).split())
def _title_column(m: dict) -> str:
"""Title column: one proposition (title) per line for each leg (parlays only)."""
raw = m.get("title", "") or m.get("yes_sub_title", "") or m.get("no_sub_title", "") or ""
raw = _normalize_title(raw)
if not raw:
return ""
if _is_parlay_subtitle(raw):
# Parlay: show each leg's title on its own line
parts = [p.strip() for p in raw.split(",") if p.strip()]
return "\n".join(_parse_leg(p)[1] for p in parts)
# Single market: show title as-is (strip "Yes "/"No " prefix if present)
return _parse_leg(raw)[1] if raw else raw
def _is_up_down_market(markets: list) -> bool:
"""Detect up/down price markets (e.g. 'BTC price up in next 15 mins?')."""
if not markets:
return False
return all(
"up" in (m.get("title", "") or "").lower()
and ("price" in (m.get("title", "") or "").lower() or "15 min" in (m.get("title", "") or "").lower())
for m in markets
)
def _clean_up_down_outcome(sub: str) -> str:
"""Clean up 'Price to beat: $70,783.57' → 'Target: $70,783.57'."""
s = (sub or "").strip()
if s.lower().startswith("price to beat:"):
return "Target:" + s[len("price to beat:"):]
return s
def market_table(markets: list, title: str = "Markets", show_expiry: bool = False, numbered: bool = False) -> Table:
"""Build a rich table for a list of markets.
Auto-detects whether markets have subtitles (event outcomes like player/team names).
If they do: shows Outcome + Title columns.
If they don't: shows Title + Yes/No/Volume columns.
If numbered=True, adds a # column for drill-down (1, 2, 3, ...).
"""
# Detect whether markets need an Outcome column:
# 1. Real subtitles (not generic yes/no) — multi-outcome markets like Olympics
# 2. Ticker-derived outcomes — range markets like Bitcoin price
has_real_subtitles = any(
(m.get("yes_sub_title") or m.get("no_sub_title") or "")
and not _is_generic_subtitle(m.get("yes_sub_title", "") or m.get("no_sub_title", ""))
and not _is_binary_yes_no_market(m.get("title", ""))
for m in markets
)
has_ticker_outcomes = (
not has_real_subtitles
and any(_outcome_from_ticker(m.get("ticker", "")) for m in markets)
)
has_binary_outcomes = any(_is_binary_yes_no_market(m.get("title", "")) for m in markets)
has_subtitles = has_real_subtitles or has_ticker_outcomes or has_binary_outcomes
# Up/down markets get directional column labels
up_down = _is_up_down_market(markets)
yes_label = "Up ↑" if up_down else "Yes"
no_label = "Down ↓" if up_down else "No"
t = Table(title=title, box=box.ROUNDED)
if numbered:
t.add_column("#", style="bold", justify="right", width=3)
if has_subtitles:
t.add_column("Prediction", max_width=30)
t.add_column("Title", max_width=45)
if show_expiry:
t.add_column("Expires", style="yellow")
t.add_column(yes_label, justify="right", style="green")
t.add_column(no_label, justify="right", style="red")
t.add_column("Volume", justify="right", style="dim")
t.add_column("Ticker", style="cyan", overflow="fold")
for i, m in enumerate(markets, 1):
expiry = fmt_expiry(_market_expiry_ts(m)) if show_expiry else None
yes = fmt_price(m.get("yes_bid_dollars"))
no = fmt_price(m.get("no_bid_dollars"))
vol = fmt_dollars(m.get("volume_fp", 0))
if numbered:
row = [str(i)]
else:
row = []
if has_subtitles:
outcome = _outcome_column(m)
if up_down:
outcome = _clean_up_down_outcome(outcome)
row.extend([outcome, _title_column(m)])
else:
row.append(_title_column(m))
if show_expiry:
row.append(expiry)
row.extend([yes, no, vol, m.get("ticker", "")])
t.add_row(*row)
return t
def display_event(event_data: dict, limit: int = 10, min_odds: float = 0.5, expiring: bool = False):
"""Display an event and its markets with optional min odds filter"""
e = event_data.get("event", {})
all_markets = event_data.get("markets", [])
filtered = filter_by_min_odds(all_markets, min_odds)
if expiring:
filtered = sort_by_expiry(filtered)
console.print()
console.print(f"[bold]{e.get('title', 'Event')}[/bold]")
if len(filtered) < len(all_markets):
console.print(f" {len(filtered)} of {len(all_markets)} markets (min odds: {min_odds}%)")
else:
console.print(f" {len(filtered)} markets")
console.print()
console.print(market_table(filtered[:limit], title="Event Markets", show_expiry=expiring))
# ── Series Discovery ────────────────────────────────────────
# Aliases: user term → additional search terms to broaden matching
# These supplement tag/title matching for common shorthand
SEARCH_ALIASES = {
"nfl": ["football"],
"epl": ["premier league"],
"ucl": ["champions league"],
"nba": ["basketball"],
"mlb": ["baseball"],
"nhl": ["hockey"],
"f1": ["formula 1", "motorsport"],
"mma": ["ufc"],
"sb": ["super bowl"],
"btc": ["bitcoin"],
"eth": ["ethereum"],
}
# How many series before we show a list instead of fetching all markets
SERIES_DRILL_DOWN_THRESHOLD = 5
_series_cache = None
_active_series_cache = None
def get_all_series() -> list:
"""Fetch all series from the API (cached per session)"""
global _series_cache
if _series_cache is not None:
return _series_cache
data = api("GET", "series")
_series_cache = data.get("series", [])
return _series_cache
def get_active_series_tickers() -> dict:
"""Fetch series tickers that have open events, with earliest market close time.
Returns dict: {series_ticker: earliest_close_time_iso_string}
Uses events endpoint with nested markets to get both series_ticker
and market close_time in a single paginated pass.
"""
global _active_series_cache
if _active_series_cache is not None:
return _active_series_cache
active = {} # series_ticker -> earliest close_time
with console.status("[dim]Loading active series...[/dim]"):
cursor = ""
for _ in range(20): # paginate through all open events
url = "events?status=open&limit=200&with_nested_markets=true"
if cursor:
url += f"&cursor={cursor}"
data = api("GET", url)
events = data.get("events", [])
for e in events:
st = e.get("series_ticker", "")
if not st:
continue
# Check nested markets for close times
nested = e.get("markets") or []
for m in nested:
exp = _market_expiry_ts(m)
if exp and (not active.get(st) or exp < active[st]):
active[st] = exp
# Ensure series appears even if no nested markets returned
if st not in active:
active[st] = ""
cursor = data.get("cursor", "")
if not cursor or not events:
break
_active_series_cache = active
return active
def find_matching_series(query: str, active_only: bool = True) -> list:
"""Find series matching query against title, ticker, category, and tags.
If active_only=True, only returns series that have open events.
"""
query_lower = query.lower()
# Expand with aliases
search_terms = [query_lower]
if query_lower in SEARCH_ALIASES:
search_terms.extend(SEARCH_ALIASES[query_lower])
# Also check if query is an alias value (e.g., "premier league" → add parent)
for alias_key, alias_values in SEARCH_ALIASES.items():
if query_lower in [v.lower() for v in alias_values]:
search_terms.append(alias_key)
all_series = get_all_series()
if active_only:
active_map = get_active_series_tickers()
else:
active_map = None
matches = []
seen = set()
for s in all_series:
ticker = s.get("ticker", "")
if ticker in seen:
continue
if active_map is not None and ticker not in active_map:
continue
title = s.get("title", "").lower()
ticker_lower = ticker.lower()
category = s.get("category", "").lower()
tags = " ".join(t.lower() for t in (s.get("tags") or []))
searchable = f"{title} {ticker_lower} {category} {tags}"
for term in search_terms:
if term in searchable:
matches.append(s)
seen.add(ticker)
break
return matches
def display_series_list(
series_list: list,
query: str,
expiring: bool = False,
limit: int = 10,
min_odds: float = 0.5,
):
"""Show an interactive numbered list of series. User can pick one to drill into."""
active_map = get_active_series_tickers() if expiring else {}
t = Table(title=f"'{query}' — {len(series_list)} series", box=box.ROUNDED)
t.add_column("#", style="bold", justify="right", width=3)
t.add_column("Ticker", style="cyan", overflow="fold")
t.add_column("Title", max_width=50)
if expiring:
t.add_column("Soonest", style="yellow")
t.add_column("Tags", style="dim", max_width=30)
for i, s in enumerate(series_list, 1):
tags = ", ".join(s.get("tags") or [])
row = [str(i), s.get("ticker", ""), s.get("title", "")]
if expiring:
row.append(fmt_expiry(active_map.get(s.get("ticker", ""), "")))
row.append(tags)
t.add_row(*row)
console.print(t)
# Interactive prompt
while True:
console.print()
choice = console.input("[dim]Enter # to drill down (or q to quit):[/dim] ").strip()
if not choice or choice.lower() == "q":
return
try:
idx = int(choice) - 1
if 0 <= idx < len(series_list):
selected = series_list[idx]
ticker = selected.get("ticker", "")
console.print(f"\n[bold]Loading {selected.get('title', ticker)}...[/bold]")
try:
data = api("GET", f"markets?series_ticker={ticker}&status=open&limit=200")
ms = filter_by_min_odds(data.get("markets", []), min_odds)
if expiring:
ms = sort_by_expiry(ms)
if ms:
console.print(market_table(ms[:limit], title=selected.get("title", ticker), show_expiry=expiring, numbered=True))
if not _prompt_market_drill_down(ms, limit):
return
else:
console.print("[dim]No open markets in this series[/dim]")
except ApiError as e:
console.print(f"[red]Error:[/red] {e}")
else:
console.print(f"[red]Pick 1-{len(series_list)}[/red]")
except ValueError:
console.print(f"[red]Enter a number or 'q'[/red]")
def display_series_markets(series_list: list, query: str, limit: int = 10, min_odds: float = 0.5, expiring: bool = False):
"""Fetch and display open markets across a small number of series"""
all_markets = []
series_names = []
for s in series_list:
ticker = s.get("ticker", "")
if not ticker:
continue
series_names.append(s.get("title", ticker))
try:
data = api("GET", f"markets?series_ticker={ticker}&status=open&limit=100")
for m in data.get("markets", []):
all_markets.append(m)
except ApiError:
pass
if not all_markets:
return False
filtered = filter_by_min_odds(all_markets, min_odds)
if expiring:
filtered = sort_by_expiry(filtered)
console.print()
console.print(f"[bold]{query.title()}[/bold] — {len(series_list)} series, {len(filtered)} markets")
if len(filtered) < len(all_markets):
console.print(f" [dim](filtered from {len(all_markets)}, min odds: {min_odds}%)[/dim]")
for name in series_names[:5]:
console.print(f" [dim]{name}[/dim]")
if len(series_names) > 5:
console.print(f" [dim]...and {len(series_names) - 5} more[/dim]")
console.print()
console.print(market_table(filtered[:limit], title=f"{query.title()} Markets", show_expiry=expiring))
return True
# ── Commands ────────────────────────────────────────────────
def handle_api_error(e: ApiError):
"""Print an API error and exit"""
console.print(f"[red]API Error {e.status_code}:[/red] {e.message}")
raise typer.Exit(1)
@app.command()
def markets(
limit: int = typer.Option(20, "--limit", "-l", help="Number of markets to show"),
status: str = typer.Option("open", "--status", "-s", help="Filter by status (open, closed, settled)"),
no_parlays: bool = typer.Option(False, "--no-parlays", help="Exclude parlay/multi-leg markets"),
all_markets: bool = typer.Option(False, "--all", "-a", help="Show all markets instead of just recently traded ones"),
json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
):
"""List markets on Kalshi (defaults to most recently traded)"""
ms = []
if not all_markets:
with console.status("[dim]Loading active markets from recent trades...[/dim]"):
try:
trades_data = api("GET", "markets/trades?limit=500")
trades = trades_data.get("trades", [])
except ApiError:
trades = []
# Get unique tickers from trades
seen = set()
for t in trades:
ticker = t.get("ticker", "")
if ticker:
seen.add(ticker)
# Batch fetch all markets at once
if seen:
tickers_str = ",".join(list(seen)[:100]) # API limit
try:
data = api("GET", f"markets?tickers={tickers_str}&status={status}")
ms = data.get("markets", [])
except ApiError:
ms = []
else:
try:
data = api("GET", f"markets?limit=200&status={status}")
ms = data.get("markets", [])
except ApiError as e:
handle_api_error(e)
if not ms:
console.print("[dim]No markets found[/dim]")
raise typer.Exit()
# Filter out parlays if requested
if no_parlays:
ms = [m for m in ms if not is_parlay(m)]
# Sort by volume descending
def sort_key(m):
vol = float(m.get("volume_fp", 0) or 0)
return vol
ms.sort(key=sort_key, reverse=True)
ms = ms[:limit]
# Output as JSON if global flag is set
if json_output:
import json
output = []
for m in ms:
output.append({
"ticker": m.get("ticker", ""),
"title": m.get("title", ""),
"yes_bid": m.get("yes_bid_dollars"),
"no_bid": m.get("no_bid_dollars"),
"yes_ask": m.get("yes_ask_dollars"),
"no_ask": m.get("no_ask_dollars"),
"volume": m.get("volume_fp"),
"status": m.get("status"),
"expiration": m.get("expiration_time", "")[:10] if m.get("expiration_time") else ""
})
console.print(json.dumps(output, indent=2))
raise typer.Exit()
console.print(market_table(ms, title=f"Kalshi Markets ({status}, top {len(ms)})"))
@app.command()
def search(
query: str = typer.Argument(help="Search query, ticker, or category (e.g. 'soccer', 'KXWO-GOLD-26', 'oviedo')"),
limit: int = typer.Option(10, "--limit", "-l", help="Max results"),
min_odds: float = typer.Option(0.5, "--min-odds", "-m", help="Hide markets where either side is below this % (default 0.5)"),
expiring: bool = typer.Option(False, "--expiring", "-e", help="Sort by expiration (soonest first)"),
):
"""Search markets by keyword, ticker, or category"""
query_lower = query.lower()
def apply_filters(ms: list) -> list:
"""Apply min-odds filter and optional expiry sort"""
ms = filter_by_min_odds(ms, min_odds)
if expiring:
ms = sort_by_expiry(ms)
return ms
# ── Strategy 1: Direct ticker lookup (KX...) ──
if query.upper().startswith("KX"):
# Try as market ticker (full ticker has hyphens, e.g. KXBTC15M-26FEB161715-15)
if "-" in query:
try:
data = api("GET", "markets/" + query.upper())
m = data.get("market")
if m:
console.print(market_table(apply_filters([m]), title=f"Market: {query.upper()}", show_expiry=expiring))
return
except ApiError:
pass
# Try as series ticker first when query has no hyphen (e.g. KXBTC15M)
# so we get real market close times; event API often returns container event with wrong expiry
try:
data = api("GET", f"markets?series_ticker={query.upper()}&status=open&limit=200")
ms = apply_filters(data.get("markets", []))
if ms:
console.print(market_table(ms[:limit], title=f"Series: {query.upper()}", show_expiry=expiring))
return
except ApiError:
pass
# Try as event ticker (e.g. full event id)
try:
ed = api("GET", "events/" + query.upper() + "?with_nested_markets=true")
if ed.get("event") and ed.get("markets"):
display_event(ed, limit=limit, min_odds=min_odds, expiring=expiring)
return
except ApiError:
pass
# ── Strategy 2: Search series by keyword/tag/category ──
try:
matching_series = find_matching_series(query)
if matching_series:
if len(matching_series) > SERIES_DRILL_DOWN_THRESHOLD:
# Sort and filter before slicing when -e is used
if expiring:
active_map = get_active_series_tickers()
now_iso = __import__("datetime").datetime.now(
__import__("datetime").timezone.utc
).isoformat()
# Drop series whose soonest market already expired
matching_series = [
s for s in matching_series
if not active_map.get(s.get("ticker", ""))
or active_map[s["ticker"]] >= now_iso
]
# Sort by soonest expiry before slicing
matching_series.sort(
key=lambda s: active_map.get(s.get("ticker", ""), "") or "9999"
)
display_series_list(matching_series[:50], query, expiring=expiring, limit=limit, min_odds=min_odds)
return
else:
# Few enough to fetch markets from all of them
if display_series_markets(matching_series, query, limit=limit, min_odds=min_odds, expiring=expiring):
return
except ApiError:
pass
# ── Strategy 3: Search open markets by title/ticker ──
try:
data = api("GET", "markets?limit=1000&status=open")
ms = data.get("markets", [])
matching = [
m for m in ms
if query_lower in m.get("title", "").lower()
or query_lower in m.get("ticker", "").lower()
]
matching = apply_filters(matching)
if matching:
console.print(market_table(matching[:limit], title=f"Search: {query}", show_expiry=expiring))
return
except ApiError as e:
console.print(f"[red]Error:[/red] {e}")
raise typer.Exit(1)
console.print(f"[dim]No markets found for '{query}'[/dim]")
@app.command()
def series(
query: str = typer.Argument(None, help="Optional keyword to filter series"),
all_series_flag: bool = typer.Option(False, "--all", "-a", help="Include series with no active markets"),
expiring: bool = typer.Option(False, "--expiring", "-e", help="Sort by soonest expiry, show expiry column"),
):
"""List available series (market categories). Only shows active series by default."""
try:
all_series = get_all_series()
except ApiError as e:
handle_api_error(e)
active_only = not all_series_flag
if query:
matching = find_matching_series(query, active_only=active_only)
else:
if active_only:
active_map = get_active_series_tickers()
matching = [s for s in all_series if s.get("ticker", "") in active_map]
else:
matching = all_series
if not matching:
console.print(f"[dim]No series found{' for ' + repr(query) if query else ''}[/dim]")
raise typer.Exit()
active_map = get_active_series_tickers() if expiring else {}
if expiring:
from datetime import datetime, timezone
now_iso = datetime.now(timezone.utc).isoformat()
# Drop expired series
matching = [
s for s in matching
if not active_map.get(s.get("ticker", ""))
or active_map[s["ticker"]] >= now_iso
]
# Sort by soonest expiry
matching.sort(
key=lambda s: active_map.get(s.get("ticker", ""), "") or "9999"
)
display = matching[:50]
t = Table(title=f"Series ({len(matching)})", box=box.ROUNDED)
t.add_column("#", style="bold", justify="right", width=3)
t.add_column("Ticker", style="cyan", overflow="fold")
t.add_column("Title", max_width=50)
if expiring:
t.add_column("Soonest", style="yellow")
t.add_column("Category", style="dim")
t.add_column("Tags", style="dim", max_width=30)
for i, s in enumerate(display, 1):
tags = ", ".join(s.get("tags") or [])
row = [str(i), s.get("ticker", ""), s.get("title", "")]