delphi-kit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
delphi_kit/watch.py ADDED
@@ -0,0 +1,209 @@
1
+ """Alerts for Delphi. Delphi has no notifications, webhooks or websocket, so this polls the chain and reports:
2
+
3
+ - new markets
4
+ - big moves in a market's probabilities
5
+ - markets about to close
6
+ - markets that close, settle (with the winner), fail or expire
7
+ - money a wallet can now collect
8
+
9
+ Alerts go to the terminal, as JSON lines, to a webhook, or to a Telegram chat.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+ from dataclasses import dataclass, field
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+ from typing import Callable, Iterable, Optional
22
+
23
+ import httpx
24
+
25
+ from .chain import Call
26
+ from .client import Delphi, _cache_dir
27
+ from .models import STATUSES, Market
28
+ from .search import rank
29
+
30
+
31
+ @dataclass
32
+ class Alert:
33
+ kind: str # new_market | move | closing_soon | closed | settled | failed | expired | claimable
34
+ market: str
35
+ question: Optional[str]
36
+ text: str
37
+ data: dict = field(default_factory=dict)
38
+ at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
39
+
40
+ def to_dict(self) -> dict:
41
+ return {"kind": self.kind, "market": self.market, "question": self.question, "text": self.text,
42
+ "data": self.data, "at": self.at}
43
+
44
+
45
+ @dataclass
46
+ class WatchConfig:
47
+ move: float = 0.10 # alert when an outcome moves this much (absolute) since the last alert
48
+ closing_hours: float = 6.0 # alert once when an open market is this close to closing
49
+ query: str = "" # only markets matching these words (empty = all)
50
+ markets: frozenset[str] = frozenset() # only these markets (empty = all)
51
+ wallet: Optional[str] = None # also alert when this wallet has something to collect
52
+ kinds: frozenset[str] = frozenset() # only these alert kinds (empty = all)
53
+
54
+
55
+ class Watcher:
56
+ def __init__(self, delphi: Delphi, config: WatchConfig, state_file: Path | None = None):
57
+ self.d = delphi
58
+ self.cfg = config
59
+ name = f"watch-{delphi.network.name}.json"
60
+ self.state_file = state_file or _cache_dir() / name
61
+ self.state = self._load()
62
+
63
+ def _load(self) -> dict:
64
+ try:
65
+ return json.loads(self.state_file.read_text())
66
+ except (FileNotFoundError, ValueError):
67
+ return {}
68
+
69
+ def _save(self) -> None:
70
+ self.state_file.write_text(json.dumps(self.state))
71
+
72
+ def _wanted(self, m: Market) -> bool:
73
+ if self.cfg.markets and m.address.lower() not in self.cfg.markets:
74
+ return False
75
+ if self.cfg.query.strip() and not rank([m], self.cfg.query):
76
+ return False
77
+ return True
78
+
79
+ def poll(self) -> list[Alert]:
80
+ """One pass over the chain. The first pass only records a baseline and returns no alerts."""
81
+ d, st = self.d, self.state
82
+ first = not st
83
+ seen: dict = st.setdefault("status", {})
84
+ base: dict = st.setdefault("base", {})
85
+ warned: list = st.setdefault("closing_warned", [])
86
+ alerts: list[Alert] = []
87
+
88
+ addrs = d.market_addresses()
89
+ statuses = d.reader.run([Call(d._gw[d._where[a.lower()]], "marketStatus", [a]) for a in addrs])
90
+ now_status = {a: STATUSES[s] for a, s in zip(addrs, statuses) if isinstance(s, int)}
91
+
92
+ live = [a for a, s in now_status.items() if s == "open"]
93
+ if first: # baseline: remember every status, only load the open markets
94
+ seen.update({a.lower(): s for a, s in now_status.items()})
95
+ changed: list[str] = []
96
+ else:
97
+ changed = [a for a, s in now_status.items() if seen.get(a.lower()) != s]
98
+ load = list(dict.fromkeys(live + changed))
99
+ markets = {m.address.lower(): m for m in d._load(load, with_rules=True)} if load else {}
100
+
101
+ for a in changed:
102
+ key, s = a.lower(), now_status[a]
103
+ m = markets.get(key)
104
+ prev = seen.get(key)
105
+ seen[key] = s
106
+ if first or m is None or not self._wanted(m):
107
+ continue
108
+ if prev is None:
109
+ if s == "open":
110
+ odds = ", ".join(f"{o} {p:.0%}" for o, p in zip(m.outcomes, m.probabilities))
111
+ alerts.append(Alert("new_market", m.address, m.question, f"New market: {m.question} [{odds}]",
112
+ {"outcomes": m.outcomes, "probabilities": m.probabilities}))
113
+ continue
114
+ if s == "awaiting_settlement":
115
+ alerts.append(Alert("closed", m.address, m.question, f"Trading closed: {m.question}"))
116
+ elif s == "settled":
117
+ win = m.outcomes[m.winning_outcome] if m.winning_outcome is not None and m.winning_outcome < len(m.outcomes) else "?"
118
+ alerts.append(Alert("settled", m.address, m.question, f"Settled: {m.question} → {win}",
119
+ {"winning_outcome": m.winning_outcome, "winning_label": win}))
120
+ elif s in ("failed", "expired"):
121
+ alerts.append(Alert(s, m.address, m.question,
122
+ f"{s.capitalize()} with no winner: {m.question}. Holders can liquidate at final prices."))
123
+
124
+ now = time.time()
125
+ for a in live:
126
+ m = markets.get(a.lower())
127
+ if m is None or not self._wanted(m) or not m.probabilities:
128
+ continue
129
+ key = a.lower()
130
+ ref = base.get(key)
131
+ if ref is None or len(ref) != len(m.probabilities):
132
+ base[key] = m.probabilities
133
+ else:
134
+ moves = [p - r for p, r in zip(m.probabilities, ref)]
135
+ j = max(range(len(moves)), key=lambda i: abs(moves[i]))
136
+ if abs(moves[j]) >= self.cfg.move:
137
+ base[key] = m.probabilities
138
+ if not first:
139
+ label = m.outcomes[j] if j < len(m.outcomes) else f"outcome {j}"
140
+ alerts.append(Alert("move", m.address, m.question,
141
+ f"{label} {ref[j]:.0%} → {m.probabilities[j]:.0%}: {m.question}",
142
+ {"outcome": j, "from": ref[j], "to": m.probabilities[j]}))
143
+ close = m.trading_closes_at.timestamp() if m.trading_closes_at else None
144
+ if close and 0 < close - now <= self.cfg.closing_hours * 3600 and key not in warned:
145
+ warned.append(key)
146
+ if not first:
147
+ hrs = (close - now) / 3600
148
+ alerts.append(Alert("closing_soon", m.address, m.question,
149
+ f"Closes in {hrs:.1f} h: {m.question}", {"closes_at": m.trading_closes_at.isoformat()}))
150
+
151
+ if self.cfg.wallet:
152
+ have = set(st.setdefault("claimable", []))
153
+ for p in self.d.positions(self.cfg.wallet):
154
+ if p.action and f"{p.market}:{p.outcome}" not in have:
155
+ have.add(f"{p.market}:{p.outcome}")
156
+ if not first:
157
+ amount = f" ${p.claimable_usd:.2f}" if p.claimable_usd else ""
158
+ alerts.append(Alert("claimable", p.market, p.question,
159
+ f"You can {p.action}{amount}: {p.question}", p.to_dict()))
160
+ st["claimable"] = sorted(have)
161
+
162
+ st["closing_warned"] = warned[-2000:]
163
+ self._save()
164
+ if self.cfg.kinds:
165
+ alerts = [a for a in alerts if a.kind in self.cfg.kinds]
166
+ return alerts
167
+
168
+ def run(self, every: float, sinks: Iterable[Callable[[Alert], None]], once: bool = False) -> None:
169
+ sinks = list(sinks)
170
+ while True:
171
+ try:
172
+ for a in self.poll():
173
+ for s in sinks:
174
+ try:
175
+ s(a)
176
+ except Exception as e: # noqa: BLE001
177
+ print(f"alert delivery failed: {e}", file=sys.stderr)
178
+ except Exception as e: # noqa: BLE001 (RPC hiccup: try again next round)
179
+ print(f"poll failed: {e}", file=sys.stderr)
180
+ if once:
181
+ return
182
+ time.sleep(every)
183
+
184
+
185
+ # ------------------------------------------------------------------ sinks
186
+
187
+ def print_sink(json_lines: bool = False) -> Callable[[Alert], None]:
188
+ def f(a: Alert) -> None:
189
+ print(json.dumps(a.to_dict()) if json_lines else f"[{a.kind}] {a.text} {a.market}", flush=True)
190
+ return f
191
+
192
+
193
+ def webhook_sink(url: str) -> Callable[[Alert], None]:
194
+ http = httpx.Client(timeout=15)
195
+
196
+ def f(a: Alert) -> None:
197
+ http.post(url, json=a.to_dict()).raise_for_status()
198
+ return f
199
+
200
+
201
+ def telegram_sink(token: str | None = None, chat_id: str | None = None) -> Callable[[Alert], None]:
202
+ token = token or os.environ["TELEGRAM_BOT_TOKEN"]
203
+ chat_id = chat_id or os.environ["TELEGRAM_CHAT_ID"]
204
+ http = httpx.Client(timeout=15)
205
+
206
+ def f(a: Alert) -> None:
207
+ http.post(f"https://api.telegram.org/bot{token}/sendMessage",
208
+ json={"chat_id": chat_id, "text": a.text, "disable_web_page_preview": True}).raise_for_status()
209
+ return f
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: delphi-kit
3
+ Version: 0.1.0
4
+ Summary: Read and trade Delphi prediction markets from Python and AI agents, with no API key: every market type, quotes, trades, positions, search, alerts and an MCP server.
5
+ Keywords: delphi,gensyn,prediction-markets,mcp,agents,web3
6
+ License-Expression: MIT
7
+ Requires-Dist: httpx>=0.27
8
+ Requires-Dist: web3>=7
9
+ Requires-Dist: mcp>=2.3 ; extra == 'mcp'
10
+ Requires-Python: >=3.10
11
+ Project-URL: Repository, https://github.com/neromtoobad/delphi-kit
12
+ Provides-Extra: mcp
13
+ Description-Content-Type: text/markdown
14
+
15
+ # delphi-kit
16
+
17
+ Python tools for [Delphi](https://delphi.fyi), the prediction market on the Gensyn chain. It has a library, a
18
+ `delphi` command, an MCP server so AI agents can trade under spending limits, and alerts.
19
+
20
+ It reads straight from the chain, so you need **no API key** to list, search, price or track anything. A wallet
21
+ key is only needed to trade.
22
+
23
+ It covers **every Delphi market on mainnet**: the current LMSR markets and both older parimutuel (DPM)
24
+ generations. That's 1,027 markets as of November 2026.
25
+
26
+ ```bash
27
+ pip install delphi-kit # library + CLI
28
+ pip install "delphi-kit[mcp]" # + MCP server
29
+ ```
30
+
31
+ ## Find a market and price a trade
32
+
33
+ ```console
34
+ $ delphi search bitcoin --limit 3
35
+ 0x44CF6d128e086961b7c0844dE6285c75046d7B7C Dec 25 05:00 $ 27.85 Yes 17% No 83%
36
+ Will Bitcoin exceed $100,000 by Christmas 2026?
37
+ 0x662Bba4819098F000d33d1e09Dff5dC3C3a5aa87 Dec 31 00:00 $ 19.11 Yes 33% No 67%
38
+ Will Bitcoin's Coinbase BTC-USD price be above $80,000 at 00:00 UTC on Dec 31, 2026?
39
+ 0xc43F7318bf91915dba2A3A02489bdEd2aDC1731f Jan 01 02:00 $ 39.52 Yes 22% No 78%
40
+ Will Bitcoin reach $100k in 2026?
41
+
42
+ $ delphi quote 0x4F5DC6b636c226CeC0C2403f988f24431b9Cc463 Yes --usd 5
43
+ buy 7.7223 Yes shares costs $4.9996 (avg 0.6474); probability 50.4% → 75.3%
44
+ ```
45
+
46
+ Most Delphi pools hold $10–$50, so a $5 trade can move the price 25 points. Every quote shows the probability
47
+ after your trade so you see that before you pay.
48
+
49
+ `delphi market <address>` prints the rules the AI judge will apply and the sources it will read. It also checks
50
+ that the rules file matches the hash stored on chain.
51
+
52
+ ## Library
53
+
54
+ ```python
55
+ from delphi_kit import Delphi
56
+
57
+ d = Delphi() # mainnet, read-only
58
+ for m in d.search("election", limit=5):
59
+ print(m.summary())
60
+
61
+ m = d.market("0x4F5DC6b636c226CeC0C2403f988f24431b9Cc463")
62
+ print(m.rules, m.sources, m.metadata_verified)
63
+
64
+ q = d.quote_buy(m, "Yes", usd=2) # shares, average price, probability before/after
65
+ print(q.shares, q.average_price, q.probability_after)
66
+
67
+ d = Delphi(private_key="0x...") # or set DELPHI_PRIVATE_KEY
68
+ t = d.buy(m, "Yes", usd=2, max_slippage=0.02) # approves only what this trade needs
69
+ d.sell(m, "Yes") # everything you hold in that outcome
70
+
71
+ for p in d.positions(): # every market, with what to do next
72
+ print(p.question, p.outcome_label, p.shares, p.value_usd, p.action) # action: redeem | liquidate | None
73
+ ```
74
+
75
+ You can pass an address or a `Market` anywhere one is expected, and outcomes take a label (`"Yes"`) or an index.
76
+ Money comes back as USD floats and shares as decimal numbers; every object has `.to_dict()`.
77
+
78
+ ## Command line
79
+
80
+ | command | does |
81
+ |---|---|
82
+ | `delphi markets [--status open\|settled\|…\|all]` | list markets with live odds, soonest to close first |
83
+ | `delphi search <words>` | keyword search over questions, outcomes and rules |
84
+ | `delphi market <address>` | one market in full: rules, sources, deadlines, fee, hash check |
85
+ | `delphi quote <address> <outcome> --usd N \| --shares N \| --sell N` | price a trade, send nothing |
86
+ | `delphi buy <address> <outcome> --usd N` | buy (asks you to type `yes` first unless `--yes`) |
87
+ | `delphi sell <address> <outcome> [--shares N]` | sell, default everything |
88
+ | `delphi positions [wallet]` | what a wallet holds and can collect |
89
+ | `delphi collect <address>` | redeem a settled market, or liquidate an expired or failed one |
90
+ | `delphi balance` | your USDC and gas |
91
+ | `delphi watch …` | alerts, see below |
92
+
93
+ Add `--json` to any command for machine output, and `--network testnet` or `--network competition-testnet` to
94
+ leave mainnet.
95
+
96
+ ## MCP server: let an agent trade, with limits
97
+
98
+ Claude Code:
99
+
100
+ ```bash
101
+ claude mcp add delphi -- uvx --from "delphi-kit[mcp]" delphi-mcp
102
+ ```
103
+
104
+ Claude Desktop, Cursor, or anything else that speaks MCP over stdio:
105
+
106
+ ```json
107
+ {
108
+ "mcpServers": {
109
+ "delphi": {
110
+ "command": "uvx",
111
+ "args": ["--from", "delphi-kit[mcp]", "delphi-mcp"],
112
+ "env": {
113
+ "DELPHI_PRIVATE_KEY": "0x...",
114
+ "DELPHI_ALLOW_TRADING": "true",
115
+ "DELPHI_MAX_TRADE_USD": "2",
116
+ "DELPHI_MAX_DAILY_USD": "10"
117
+ }
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
123
+ The read tools are `list_markets`, `get_market`, `quote_buy`, `quote_sell`, `get_positions` and `wallet_status`.
124
+ The write tools are `buy`, `sell` and `collect`.
125
+
126
+ Without a key or `DELPHI_ALLOW_TRADING=true` the server is read-only, and the write tools say so instead of
127
+ sending anything. With trading on, every buy is checked first:
128
+
129
+ | setting | default |
130
+ |---|---|
131
+ | `DELPHI_MAX_TRADE_USD` | 5 per trade |
132
+ | `DELPHI_MAX_DAILY_USD` | 20 per UTC day, kept in a ledger file so a restart doesn't reset it |
133
+ | `DELPHI_MAX_SLIPPAGE` | 0.03 |
134
+ | `DELPHI_ALLOWED_MARKETS` | all (comma list of addresses to restrict) |
135
+
136
+ Use a separate wallet for the agent and only put in what you're willing to lose.
137
+
138
+ ## Alerts
139
+
140
+ Delphi has no notifications or webhooks, so `delphi watch` polls the chain and tells you about:
141
+
142
+ - new markets
143
+ - moves of 10 points or more (`--move`)
144
+ - markets about to close (`--closing-hours`)
145
+ - markets that close, settle (with the winner), fail or expire
146
+ - money your wallet can now collect (`--wallet`)
147
+
148
+ ```bash
149
+ delphi watch --query "bitcoin" --telegram # TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID
150
+ delphi watch --wallet 0xYou --webhook https://… # each alert POSTed as JSON
151
+ delphi watch --json --once # one pass, JSON lines (for cron)
152
+ ```
153
+
154
+ The first run records a baseline, and alerts start from the second check.
155
+
156
+ ## What this does that the official SDK doesn't
157
+
158
+ [`@gensyn-ai/gensyn-delphi-sdk`](https://www.npmjs.com/package/@gensyn-ai/gensyn-delphi-sdk) 2.1.0 is TypeScript
159
+ only. Its mainnet config has the two DPM deployments but **not the LMSR one**, and LMSR is where most open markets
160
+ are (56 of 82 when this was written). LMSR quote functions also return three values where DPM returns one. Full
161
+ notes are in [docs/contracts.md](docs/contracts.md).
162
+
163
+ | | SDK 2.1.0 | delphi-kit |
164
+ |---|---|---|
165
+ | Language | TypeScript | Python |
166
+ | Mainnet LMSR markets | no | yes |
167
+ | List markets and positions without an API key | no (REST API needs a key) | yes, from chain |
168
+ | Keyword search | no (category filter only) | yes |
169
+ | Rules-file hash check | no | yes |
170
+ | Buy with a dollar budget | no (exact shares) | yes, never over budget |
171
+ | Default approval | unlimited | exact amount |
172
+ | Agent spending limits | no | yes |
173
+ | Alerts | no | yes |
174
+
175
+ ## Tests
176
+
177
+ ```bash
178
+ uv run pytest tests/test_unit.py # offline, about a second
179
+ uv run pytest tests/test_fork.py -s # needs Foundry's anvil, about a minute, no real money
180
+ ```
181
+
182
+ The fork tests run a private copy of Gensyn mainnet and put a throwaway wallet through two full lifecycles:
183
+
184
+ - **LMSR:** buy with a $3 budget, sell half, jump the clock past the deadline, settle as Delphi's oracle relayer,
185
+ redeem the winnings.
186
+ - **DPM:** buy, let the market expire unsettled, liquidate.
187
+
188
+ ## License
189
+
190
+ MIT
@@ -0,0 +1,21 @@
1
+ delphi_kit/__init__.py,sha256=DBWylaS-fB8-D2wQUWN2h1PrDvgBeASkC0_MUFOaxVk,420
2
+ delphi_kit/abi/DelphiFactory.json,sha256=5lZlOQzliwey5i0or8XV81L5Nz5VhPwBL8zN9tZpxCE,5573
3
+ delphi_kit/abi/DpmGateway.json,sha256=y39nHVO4Ittt5JCPvpcjNnW5x1xO-41sf8Agxo0ITEA,23823
4
+ delphi_kit/abi/DpmGatewayLegacy.json,sha256=nsJkJ2WNxgUOgJLGz_SFdwnTOwP2ZJy8D15zZ57UHko,19787
5
+ delphi_kit/abi/LmsrGateway.json,sha256=qZP4snpWC8M9TYvNZEIZluOSfAM6Z5uSXsUWc6R6qtw,22642
6
+ delphi_kit/abi/LmsrMarket.json,sha256=VXg6wFHS7QAjWfWhM8kOooiPKumDSjOwDW0os2YG_68,25843
7
+ delphi_kit/abi/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ delphi_kit/chain.py,sha256=uARqaC-nie58qkwBlc2p98aD0SckBoAYno7Gtvdo8g0,5318
9
+ delphi_kit/cli.py,sha256=0tN0Yzvnkjkbop_C3zDYH42I2yy4cqmGxAx7jbnGu1Q,9253
10
+ delphi_kit/client.py,sha256=Fo-51vRzX87Fda7kDJuEUj8y-7qPW8aAkZ_v3gesJu4,25181
11
+ delphi_kit/limits.py,sha256=hkmLe06Twoex3e-_O5XjDQnkQptbxuNyPVeeqoq3fQk,3675
12
+ delphi_kit/mcp_server.py,sha256=jVT6v7GtPIoGGTuqEZ0NhLatt9GvuzbxyrXAQsgFndk,6987
13
+ delphi_kit/models.py,sha256=3KQsMBVvwPGGHvZeTACHTmpNTIlpLIUv65uPSE3xoAI,4171
14
+ delphi_kit/networks.py,sha256=lEcwTMwySV9jH__Nvhlkrz5ulJCUIuO2z4I8NabrxwA,3854
15
+ delphi_kit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ delphi_kit/search.py,sha256=edwi9C3aUMo3LJ5a_GE_VVNebBJ69j9Cp4GsUUG3Aw8,1466
17
+ delphi_kit/watch.py,sha256=ndO7MQ8fW3MXThSHIvvG9HBOK5yDR4q1_e1EiYbeMs0,9146
18
+ delphi_kit-0.1.0.dist-info/WHEEL,sha256=3OmCxFA0ffBIsX4x0o8CdfSvZAOvO3mzEG8U_z5TvV4,80
19
+ delphi_kit-0.1.0.dist-info/entry_points.txt,sha256=W0brzA13OpRHa5tkggs7K5ppBCfsd6S8Gp9aOWyG-Rs,88
20
+ delphi_kit-0.1.0.dist-info/METADATA,sha256=vc1W845HnJnTDsuxUeKgbFa716EYaDTE0Eg2YcZxEvU,7580
21
+ delphi_kit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.8
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,4 @@
1
+ [console_scripts]
2
+ delphi = delphi_kit.cli:main
3
+ delphi-mcp = delphi_kit.mcp_server:main
4
+