Compare commits
68 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4bc9f8a326 | |||
| f8fbd68d19 | |||
| 2888563723 | |||
| 31af9ad9cf | |||
| 1837d49028 | |||
| ea409d4da5 | |||
| cbd709c50c | |||
| 2a8916e1d9 | |||
| d7a77c734d | |||
| 9cc3921e3c | |||
| 6e1cfb4e22 | |||
| 4262b7adaa | |||
| 2a6332620c | |||
| 3bec895a0a | |||
| 98eece1c50 | |||
| 0f608db47f | |||
| 351de6187e | |||
| f7946d2277 | |||
| 2a62f1812a | |||
| e26ba27a24 | |||
| 5696e3dae2 | |||
| 220978ec83 | |||
| ddbb96c799 | |||
| 6f620089b6 | |||
| 9cbcc03681 | |||
| 3495e8de3c | |||
| fe69e31929 | |||
| 74749bfdb8 | |||
| 1b2376ccb4 | |||
| b47058d75e | |||
| d26c801888 | |||
| 7aa3280e5b | |||
| 81595a89ee | |||
| b523a8890f | |||
| 9b25fdc424 | |||
| 2ef0784ddc | |||
| 5dde2cd28e | |||
| 5892772671 | |||
| 063fcb57a2 | |||
| e80e52275c | |||
| 6b50266300 | |||
| b1fe4c2fd5 | |||
| 5d82be0091 | |||
| f90605bfc7 | |||
| 20ce08adf9 | |||
| 064b301ebd | |||
| 2c4179a64e | |||
| 7b26767a97 | |||
| 53b36cce82 | |||
| 2269752b9e | |||
| 00660d890c | |||
| 097138afdd | |||
| 14ccc97e09 | |||
| 12e26d6cc9 | |||
| 2fcdac61d5 | |||
| a7e31fa2ef | |||
| 2306c6fd96 | |||
| d01ab8f15c | |||
| f72d0fe602 | |||
| 38742fbdec | |||
| 160c3890ff | |||
| 02f0c224e0 | |||
| fae9f26829 | |||
| 7fd67e7c8e | |||
| a77efc6bb8 | |||
| e397f21321 | |||
| 9a411d5146 | |||
| 99028f9073 |
Generated
+166
-6
@@ -21,6 +21,12 @@ version = "1.0.104"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||
|
||||
[[package]]
|
||||
name = "ascii"
|
||||
version = "1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16"
|
||||
|
||||
[[package]]
|
||||
name = "atomic-waker"
|
||||
version = "1.1.2"
|
||||
@@ -96,16 +102,27 @@ checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.3.1",
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chunked_transfer"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e4de3bc4ea267985becf712dc6d9eed8b04c953b3fcfb339ebc87acd9804901"
|
||||
|
||||
[[package]]
|
||||
name = "cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_urlencoded",
|
||||
"tiny_http",
|
||||
"tungstenite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -136,6 +153,12 @@ dependencies = [
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a2330da5de22e8a3cb63252ce2abb30116bf5265e89c0e01bc17015ce30a476"
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -144,6 +167,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -172,10 +196,14 @@ name = "exchange"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"data-encoding",
|
||||
"hmac",
|
||||
"matching",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha1",
|
||||
"sha2",
|
||||
"tempfile",
|
||||
]
|
||||
|
||||
@@ -284,6 +312,18 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi 5.3.0",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.4.3"
|
||||
@@ -293,8 +333,8 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"js-sys",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"rand_core",
|
||||
"r-efi 6.0.0",
|
||||
"rand_core 0.10.1",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
@@ -316,6 +356,15 @@ dependencies = [
|
||||
"hashbrown",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "http"
|
||||
version = "1.6.0"
|
||||
@@ -355,6 +404,12 @@ version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
||||
|
||||
[[package]]
|
||||
name = "httpdate"
|
||||
version = "1.0.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
||||
|
||||
[[package]]
|
||||
name = "hyper"
|
||||
version = "1.13.0"
|
||||
@@ -636,6 +691,15 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.107"
|
||||
@@ -674,7 +738,7 @@ dependencies = [
|
||||
"bytes",
|
||||
"getrandom 0.4.3",
|
||||
"lru-slab",
|
||||
"rand",
|
||||
"rand 0.10.4",
|
||||
"rand_pcg",
|
||||
"ring",
|
||||
"rustc-hash",
|
||||
@@ -710,12 +774,28 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "6.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.10.4"
|
||||
@@ -724,7 +804,26 @@ checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||
dependencies = [
|
||||
"chacha20",
|
||||
"getrandom 0.4.3",
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core 0.9.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -739,7 +838,7 @@ version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df"
|
||||
dependencies = [
|
||||
"rand_core",
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -942,6 +1041,17 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures 0.2.17",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
@@ -1057,6 +1167,18 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tiny_http"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "389915df6413a2e74fb181895f933386023c71110878cd0825588928e64cdc82"
|
||||
dependencies = [
|
||||
"ascii",
|
||||
"chunked_transfer",
|
||||
"httpdate",
|
||||
"log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.5"
|
||||
@@ -1167,6 +1289,23 @@ version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tungstenite"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"data-encoding",
|
||||
"http",
|
||||
"httparse",
|
||||
"log",
|
||||
"rand 0.9.5",
|
||||
"sha1",
|
||||
"thiserror",
|
||||
"utf-8",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.20.1"
|
||||
@@ -1197,6 +1336,12 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "utf-8"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.1.0"
|
||||
@@ -1250,6 +1395,15 @@ version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.4+wasi-0.2.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.129"
|
||||
@@ -1423,6 +1577,12 @@ version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.57.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
|
||||
@@ -7,3 +7,8 @@ version.workspace = true
|
||||
exchange = { path = "../exchange" }
|
||||
serde_json.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
|
||||
+391
-1
@@ -1,6 +1,6 @@
|
||||
# cli
|
||||
|
||||
可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。
|
||||
可信操作员的 JSON 行命令入口。启动参数指定数据库文件,程序复用同一个 Exchange 连接。标准输入的每一行对应标准输出的一条 JSON 回执。输入结束时进程退出。输入线程和交易线程之间使用有界队列,交易线程按最近一笔 GTD 的有效截止时间唤醒,最长每五秒检查一次其他到期任务。
|
||||
|
||||
## 文件依赖
|
||||
|
||||
@@ -24,6 +24,11 @@ sequenceDiagram
|
||||
U->>C: 启动并指定数据库路径
|
||||
C->>E: 打开数据库
|
||||
C->>S: 传入连接和输入输出流
|
||||
S->>E: 查询最近一笔待到期 GTD 剩余时间
|
||||
opt 达到 GTD 截止点或五秒检查周期
|
||||
S->>E: maintain 检查到期注册、释放余单并同步盘口
|
||||
S->>E: 重新计算下次唤醒时间
|
||||
end
|
||||
loop 输入一行
|
||||
U->>S: JSON 命令
|
||||
alt JSON 有效
|
||||
@@ -35,3 +40,388 @@ sequenceDiagram
|
||||
S-->>U: 输出一行 JSON 并刷新
|
||||
end
|
||||
```
|
||||
|
||||
## 市场 WebSocket
|
||||
|
||||
已有可执行文件可用 `cli DATABASE --market-ws 127.0.0.1:9001` 启动行情监听,客户端连接 `ws://127.0.0.1:9001/ws/market`。同一数据库可以由另一条 JSON 行命令会话写入。监听模式只接收市场订阅与心跳。每个连接独立维护订阅,所有连接共享一个 Exchange。当前服务提供明文 WebSocket,接入 TLS 需要相应的服务入口。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> ws["market_ws.rs"]
|
||||
main --> stdin["stream.rs"]
|
||||
ws --> subs["subscriptions.rs"]
|
||||
subs --> api["exchange::Exchange / MarketPage"]
|
||||
stdin --> api
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant W as market_ws
|
||||
participant S as 连接订阅
|
||||
participant E as Exchange
|
||||
C->>W: Upgrade /ws/market
|
||||
C->>S: type=market,订阅 YES
|
||||
S->>E: 同一快照内读取 YES 盘口和批次号
|
||||
S-->>C: 初始 book 数组,可用 initial_dump=false 省略
|
||||
C->>S: operation=subscribe,增加 NO
|
||||
S-->>C: 新增 NO 的 book 数组
|
||||
S->>E: 从该市场的已读批次号读取后续变化
|
||||
S-->>C: price_change,只含已订阅且晚于其起点的资产
|
||||
opt 成交或价格步长变化
|
||||
S-->>C: 按同一游标发送 last_trade_price 或 tick_size_change
|
||||
end
|
||||
opt 已启用扩展功能
|
||||
S->>E: 从本连接的发现游标读取后续上架公告
|
||||
S-->>C: new_market;已订阅市场最终裁决时另发 market_resolved
|
||||
end
|
||||
C->>S: operation=unsubscribe,移除 YES
|
||||
C->>W: 文本 PING
|
||||
W-->>C: 文本 PONG
|
||||
```
|
||||
|
||||
[订阅报文样例](../../docs/examples/market-ws.txt)逐行发送为文本帧。客户端可每 10 秒发送一次 `PING`。本地按 100 毫秒间隔检查新批次,单页最多 64 个批次,每个进程最多接纳 128 个同时连接的会话。这些是本地实现参数。慢连接的网络写入在释放 Exchange 锁后进行。
|
||||
|
||||
## 盘口 HTTP
|
||||
|
||||
`cli DATABASE --market-http 127.0.0.1:9002` 启动公开盘口读取服务。可与写入会话和 WebSocket 服务共用数据库文件。[HTTP 请求样例](../../docs/examples/clob-http.http)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> http["market_http.rs"]
|
||||
http --> api["exchange::Exchange::public_books"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as SDK
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /book?token_id=... 或 POST /books
|
||||
H->>E: 提交本次请求的资产 ID
|
||||
E-->>H: 一个数据库快照中的盘口列表
|
||||
H-->>C: 单盘 JSON 对象或批量 JSON 数组
|
||||
```
|
||||
|
||||
同一个 HTTP 监听器提供 `GET /v2/prices-history`。客户端按资产查询历史,接续页可以只发同一资产和上一页的游标。[请求样例](../../docs/examples/clob-http.http)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["main.rs"] --> http["market_http.rs"]
|
||||
http --> history["exchange::HistoryQuery"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 图表客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/prices-history 含资产与窗口
|
||||
H->>E: 查询历史点与分页状态
|
||||
E-->>H: data 与 pagination
|
||||
H-->>C: JSON 中的 next_cursor
|
||||
C->>H: 同一 token_id 和 cursor
|
||||
H->>E: 读取该窗口下一页
|
||||
E-->>C: 后续点及是否还有数据
|
||||
```
|
||||
|
||||
行情客户端通过 `GET /last-trade-price` 查询单个结果,通过 `POST /last-trades-prices` 发送资产数组。只带 token_ids 查询参数的批量 GET 在生产样本中返回 400。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] -->|"token_id 或资产列表"| L["exchange/last_trades.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: 查询一个或多个资产的最后一笔成交
|
||||
H->>E: last_trade_prices
|
||||
E-->>H: 仅返回有成交记录的资产及其方向
|
||||
H-->>C: 单查无成交时使用占位值,批查按资产 ID 排序并去重
|
||||
```
|
||||
|
||||
客户端可通过 `GET /tick-size?token_id=…` 或 `GET /tick-size/{token_id}` 读取当前报价步长。URL 路径中的空格编码为 %20,加号表示加号本身。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] -->|解码 token_id| T["exchange/tick_size.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /tick-size 或 /tick-size/{token_id}
|
||||
H->>E: 根据结果资产查询当前已提交步长
|
||||
E-->>H: 精确十进制数或查无市场
|
||||
H-->>C: minimum_tick_size 或 404 错误
|
||||
```
|
||||
|
||||
### 从结果资产查交易规格
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] -->|解码单个路径参数| E["exchange/clob_market.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 行情客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /markets-by-token/{token_id}
|
||||
H->>E: market_by_token
|
||||
E-->>C: condition_id、YES 和 NO 资产
|
||||
C->>H: GET /clob-markets/{condition_id}
|
||||
H->>E: clob_market_info
|
||||
E-->>C: 两个结果的标签、报价步长、最小量和费用参数
|
||||
```
|
||||
|
||||
路径参数使用百分号编码。即使查询从 NO 开始,primary_token_id 仍对应 YES。可重放请求见[行情 HTTP 示例](../../docs/examples/clob-http.http)。
|
||||
|
||||
### 查询盘口价差与中点
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 行情客户端
|
||||
participant H as market_http.rs
|
||||
participant Q as exchange/quotes.rs
|
||||
C->>H: 单查 /spread、/midpoint,批查 /spreads、/midpoints
|
||||
H->>Q: 传入结果资产 ID
|
||||
Q-->>H: 按买侧缺档取 0、卖侧缺档取 1 计算中点或价差
|
||||
H-->>C: 单查用 spread 或 mid 字段,POST 批查以资产 ID 为键
|
||||
```
|
||||
|
||||
### 查询盘口买一和卖一
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as exchange/quotes.rs
|
||||
C->>H: GET /price 或 POST /prices
|
||||
H->>H: 校验资产与方向一一配对
|
||||
H->>E: 查询盘口同侧最优档
|
||||
E-->>H: 单笔价格或按资产与方向分组的报价
|
||||
H-->>C: 单查和批查的价格均为字符串
|
||||
```
|
||||
|
||||
[可重放请求](../../docs/examples/clob-http.http)同时展示相同盘口下的买价、卖价与中点。
|
||||
|
||||
### CLOB 客户端历史曲线
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as CLOB 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as prices_history/legacy.rs
|
||||
C->>H: GET /prices-history,market 与 interval 或 startTs、endTs
|
||||
H->>E: clob_price_history,fidelity 以分钟计
|
||||
E-->>H: 返回窗口内盘口中点样本,末尾追加最近可用点
|
||||
H-->>C: history 数组,每点包含 t 和 p
|
||||
```
|
||||
|
||||
### 发布后的裁决说明
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] --> Q["exchange/clarifications.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http
|
||||
participant E as Exchange
|
||||
C->>H: GET /market-clarifications?event_id=1&market_id=3
|
||||
H->>E: 按事件和市场目录 ID 筛选,再排序和翻页
|
||||
E-->>H: 规则说明、清盘标记和本地发布时间
|
||||
H-->>C: 已发布的公告数组
|
||||
```
|
||||
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] --> G["exchange/gamma_directory.rs"]
|
||||
H --> B["exchange/book_snapshot.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market-http
|
||||
participant E as Exchange
|
||||
C->>H: GET /events/slug/nvda-closing-price-2027
|
||||
H->>E: gamma_event
|
||||
E-->>C: markets 数组,每项含该门槛的目录 ID
|
||||
C->>H: GET /markets/{id}
|
||||
H->>E: gamma_market
|
||||
E-->>C: outcomes 与 clobTokenIds,均为 JSON 数组编码的字符串
|
||||
C->>H: GET /book?token_id=选中的资产
|
||||
H-->>C: 该结果的买卖盘
|
||||
```
|
||||
|
||||
加载 [主题事件样例](../../docs/examples/topic.jsonl) 后即可按上图读取。事件与市场均支持按数字 ID 和按 slug 查询,缺失资源返回 404。路径段按 UTF-8 百分号编码,路径中的加号表示加号。当前详情入口支持无查询参数的 GET。
|
||||
|
||||
### 浏览目录
|
||||
|
||||
`GET /markets` 和 `GET /events` 返回数组。支持 limit、offset、ascending、order、active、closed,以及可重复的 id 和 slug。市场列表也支持重复的 condition_ids 和 clob_token_ids。同类标识取并集,提供多类标识时取交集。查询字符串中的加号需要编码成 %2B。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /markets 与 /events"] --> P["exchange/gamma_list.rs"] --> D["exchange/gamma_directory.rs"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market-http
|
||||
participant E as Exchange
|
||||
C->>H: GET /events?limit=1&order=id&ascending=true
|
||||
H->>E: gamma_list(Events),保留重复参数
|
||||
E-->>C: 一个事件及其可见子盘
|
||||
C->>H: GET /markets?slug=nvda-300&closed=any
|
||||
H->>E: gamma_list(Markets),按 slug 查询开放或已关闭的盘口
|
||||
E-->>C: 匹配市场数组
|
||||
```
|
||||
|
||||
### 查询公开成交
|
||||
|
||||
`GET /v2/trades?user=bob&limit=1` 按成交时间倒序返回 Bob 作为吃单方的成交。查询双方时加 `taker_only=false`。下一页传回 `pagination.next_cursor` 并重送筛选条件。condition 支持本地市场 ID,event_id 接受 Gamma 目录里的数字事件 ID。条件列表以逗号分隔。钱包、市场和资产字段使用本地账户和目录标识。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] --> T["exchange/public_trades/http.rs"] --> S["exchange/public_trades.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market-http
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/trades,user=bob,limit=1
|
||||
H->>E: 解析参数并查询该账户的成交
|
||||
E-->>H: 一条成交和下一页签名游标
|
||||
H-->>C: data、pagination
|
||||
C->>H: 重送 user 和 cursor
|
||||
H->>E: 验证签名,从上一笔订单之后继续
|
||||
E-->>C: 剩余成交,末页 next_cursor 为空
|
||||
```
|
||||
|
||||
### 裁决状态
|
||||
|
||||
`GET /v2/resolutions?condition=m` 读取单盘状态,`?event_id=1` 读取事件的各个盘口。已登记问题标识的乐观裁决市场也支持 question_id 查询。多个条件或多个事件用逗号分隔,每次选择一种查询方式。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET 参数"] --> Q["exchange/resolution/http.rs"]
|
||||
Q --> D["exchange/resolution/state.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/resolutions?event_id=1
|
||||
H->>E: 校验选择器,读取事件下的各盘
|
||||
E-->>H: 每个可见市场一行
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /v2/value"] --> V["exchange/portfolio/http.rs"]
|
||||
V --> A["exchange/portfolio.rs"] --> S["exchange/portfolio/value.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/value?user=alice&condition=e
|
||||
H->>E: 读取 e 的所有结果资产价值
|
||||
alt 持仓均可估值
|
||||
H-->>C: 200,data 含 proxy_wallet 和 value
|
||||
else 非零持仓缺价
|
||||
H-->>C: 503,Retry-After 提示重试
|
||||
end
|
||||
```
|
||||
|
||||
### 查询未平仓量
|
||||
|
||||
`GET /v2/oi` 返回单行 GLOBAL。指定 `GET /v2/oi?condition=cup` 可查 cup 的金额,空盘返回 0,归档市场从数组中省略。筛选支持逗号分隔及 condition_id、conditionId 两个别名。已有份额却无法估值时,本地返回可重试的 503。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /v2/oi"] --> E["exchange/open_interest.rs"]
|
||||
E --> D["exchange/open_interest.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /v2/oi?condition=cup
|
||||
H->>E: 验证条件,按市场汇总
|
||||
E-->>H: condition_id 和 value
|
||||
H-->>C: 200,data 数组
|
||||
```
|
||||
|
||||
### 按结果资产查询基础费
|
||||
|
||||
`GET /fee-rate?token_id=eb%3AYES%3Acup` 和 `GET /fee-rate/eb%3ANO%3Acup` 均返回 base_fee,单位为整数基点。费用样例返回 30。计算吃单费用所需的曲线系数在该市场详情的 fd.r 中。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs"] --> F["exchange/fees.rs"] --> D["exchange/schema.sql · market_fee_terms"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /fee-rate/{token_id}
|
||||
H->>E: 解码资产 ID 并查询基础费
|
||||
alt 有整数基点配置
|
||||
H-->>C: 200,base_fee
|
||||
else 市场或基础费不存在
|
||||
H-->>C: 404
|
||||
end
|
||||
```
|
||||
|
||||
### 在下单前判断互斥资产
|
||||
|
||||
官方 Python SDK 可以按 token_id 请求 `GET /neg-risk`。本地的 YES 和 NO 共用所属市场的分组。没有分组的已上架资产返回 false,无法匹配市场则返回 404。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
H["market_http.rs · GET /neg-risk"] --> E["exchange/neg_risk.rs"] --> S["exchange/schema.sql · neg_risk_members"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /neg-risk?token_id=eb%3ANO%3Aa
|
||||
H->>E: 查询市场 a 的成员关系
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
GET /v2/tokens 支持逗号分隔的资产 ID 或条件及互斥组 ID。两个选择器择一,回执按资产关联市场、事件和裁决结果。
|
||||
|
||||
+30
-4
@@ -1,13 +1,39 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::Exchange;
|
||||
use std::{env, io};
|
||||
use std::{
|
||||
env, io,
|
||||
net::{SocketAddr, TcpListener},
|
||||
};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let path = args.next().context("usage: cli DATABASE")?;
|
||||
ensure!(args.next().is_none(), "usage: cli DATABASE");
|
||||
let usage = "usage: cli DATABASE [--market-ws HOST:PORT | --market-http HOST:PORT]";
|
||||
let path = args.next().context(usage)?;
|
||||
if let Some(mode) = args.next() {
|
||||
ensure!(mode == "--market-ws" || mode == "--market-http", usage);
|
||||
let addr: SocketAddr = args
|
||||
.next()
|
||||
.and_then(|s| s.into_string().ok())
|
||||
.context(usage)?
|
||||
.parse()?;
|
||||
ensure!(args.next().is_none(), usage);
|
||||
let engine = Exchange::open(path)?;
|
||||
let listener = TcpListener::bind(addr)?;
|
||||
return if mode == "--market-http" {
|
||||
market_http::serve(engine, listener)
|
||||
} else {
|
||||
market_ws::serve(engine, listener)
|
||||
};
|
||||
}
|
||||
let mut exchange = Exchange::open(path)?;
|
||||
stream::serve(&mut exchange, io::stdin().lock(), io::stdout().lock())
|
||||
stream::serve(
|
||||
&mut exchange,
|
||||
io::BufReader::new(io::stdin()),
|
||||
io::stdout().lock(),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,912 @@
|
||||
use anyhow::Result;
|
||||
use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::{io::Read, net::TcpListener, sync::Mutex, thread};
|
||||
use tiny_http::{Header, Method, Request, Response, Server};
|
||||
|
||||
const MAX_BOOKS: usize = 500;
|
||||
const MAX_BODY: u64 = 1_048_576;
|
||||
const MISSING: &str = "No orderbook exists for the requested token id";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BookParam {
|
||||
token_id: String,
|
||||
// The official SDK can include a side on a BookParams item. The book contains both.
|
||||
#[serde(rename = "side")]
|
||||
_side: Option<exchange::PriceSide>,
|
||||
}
|
||||
|
||||
type Reply = std::result::Result<Value, (u16, &'static str)>;
|
||||
|
||||
fn query(engine: &Mutex<Exchange>, params: Vec<BookParam>, single: bool) -> Reply {
|
||||
if params.len() > MAX_BOOKS || params.iter().any(|p| p.token_id.trim().is_empty()) {
|
||||
return Err((
|
||||
400,
|
||||
if single {
|
||||
"Invalid token id"
|
||||
} else {
|
||||
"Invalid payload"
|
||||
},
|
||||
));
|
||||
}
|
||||
let tokens = params.into_iter().map(|p| p.token_id).collect::<Vec<_>>();
|
||||
let mut books = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "error getting the orderbook"))?
|
||||
.public_books(&tokens)
|
||||
.map_err(|_| (500, "error getting the orderbook"))?;
|
||||
if single {
|
||||
books.pop().ok_or((404, MISSING))
|
||||
} else {
|
||||
Ok(Value::Array(books))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum QuoteField {
|
||||
Spread,
|
||||
Midpoint,
|
||||
}
|
||||
|
||||
fn quote_response(
|
||||
engine: &Mutex<Exchange>,
|
||||
tokens: Vec<String>,
|
||||
field: QuoteField,
|
||||
single: bool,
|
||||
) -> Reply {
|
||||
let internal_error = match field {
|
||||
QuoteField::Spread => (500, "error getting the spread"),
|
||||
QuoteField::Midpoint => (500, "error getting the midpoint"),
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| internal_error)?;
|
||||
let rows = match field {
|
||||
QuoteField::Spread => exchange.spreads(&tokens),
|
||||
QuoteField::Midpoint => exchange.midpoints(&tokens),
|
||||
}
|
||||
.map_err(|error| match error {
|
||||
exchange::MarketDataError::Invalid(_) if single => (400, "Invalid token id"),
|
||||
exchange::MarketDataError::Invalid(_) => (400, "Invalid payload"),
|
||||
exchange::MarketDataError::Unavailable => internal_error,
|
||||
})?;
|
||||
if single {
|
||||
let value = rows.into_values().next().flatten().ok_or((404, MISSING))?;
|
||||
return Ok(match field {
|
||||
QuoteField::Spread => json!({"spread":value}),
|
||||
QuoteField::Midpoint => json!({"mid":value}),
|
||||
});
|
||||
}
|
||||
let result = rows
|
||||
.into_iter()
|
||||
.filter_map(|(id, value)| value.map(|s| (id, Value::String(s))))
|
||||
.collect();
|
||||
Ok(Value::Object(result))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct WirePrice {
|
||||
token_id: String,
|
||||
side: Option<String>,
|
||||
}
|
||||
|
||||
impl WirePrice {
|
||||
fn into_request(self) -> std::result::Result<exchange::PriceRequest, (u16, &'static str)> {
|
||||
let side = match self.side.as_deref() {
|
||||
Some("BUY") => exchange::PriceSide::Buy,
|
||||
Some("SELL") => exchange::PriceSide::Sell,
|
||||
_ => return Err((400, "Invalid side")),
|
||||
};
|
||||
Ok(exchange::PriceRequest {
|
||||
token_id: self.token_id,
|
||||
side,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn book_prices(engine: &Mutex<Exchange>, rows: Vec<WirePrice>, single: bool) -> Reply {
|
||||
if rows.is_empty() || rows.len() > MAX_BOOKS {
|
||||
return Err((400, "Invalid payload"));
|
||||
}
|
||||
let requests = rows
|
||||
.into_iter()
|
||||
.map(|mut row| {
|
||||
if !single && row.side.is_none() {
|
||||
row.side = Some("SELL".into());
|
||||
}
|
||||
row.into_request()
|
||||
})
|
||||
.collect::<std::result::Result<Vec<_>, _>>()?;
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let value =
|
||||
exchange
|
||||
.public_book_prices(&requests)
|
||||
.map_err(
|
||||
|error| match error.downcast_ref::<exchange::PriceQueryError>() {
|
||||
Some(exchange::PriceQueryError::InvalidToken) if single => {
|
||||
(400, "Invalid token id")
|
||||
}
|
||||
Some(exchange::PriceQueryError::MissingBook) => (404, MISSING),
|
||||
Some(_) => (400, "Invalid payload"),
|
||||
None => (500, "Internal server error"),
|
||||
},
|
||||
)?;
|
||||
if single {
|
||||
let sides = value[requests[0].token_id.as_str()]
|
||||
.as_object()
|
||||
.ok_or((404, MISSING))?;
|
||||
let price = sides
|
||||
.values()
|
||||
.next()
|
||||
.ok_or((500, "Internal server error"))?;
|
||||
return Ok(json!({"price":price}));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn batch_params<T: serde::de::DeserializeOwned>(
|
||||
req: &mut Request,
|
||||
) -> std::result::Result<Vec<T>, (u16, &'static str)> {
|
||||
if req.body_length().is_some_and(|n| n as u64 > MAX_BODY) {
|
||||
return Err((413, "Request body too large"));
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
req.as_reader()
|
||||
.take(MAX_BODY + 1)
|
||||
.read_to_end(&mut data)
|
||||
.map_err(|_| (400, "Invalid payload"))?;
|
||||
if data.len() as u64 > MAX_BODY {
|
||||
return Err((413, "Request body too large"));
|
||||
}
|
||||
serde_json::from_slice(&data).map_err(|_| (400, "Invalid payload"))
|
||||
}
|
||||
|
||||
fn last_prices(engine: &Mutex<Exchange>, tokens: Vec<String>, single: bool) -> Reply {
|
||||
let mut rows = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Internal server error"))?
|
||||
.last_trade_prices(&tokens)
|
||||
.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) if single => (400, "Invalid token id"),
|
||||
exchange::MarketDataError::Invalid(_) => (400, "Invalid payload"),
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?;
|
||||
if single {
|
||||
Ok(match rows.pop() {
|
||||
Some(row) => json!({"price":row["price"],"side":row["side"]}),
|
||||
None => json!({"price":"0.5","side":""}),
|
||||
})
|
||||
} else {
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TokenQuery {
|
||||
token_id: String,
|
||||
}
|
||||
|
||||
fn token_setting(
|
||||
name: &str,
|
||||
engine: &Mutex<Exchange>,
|
||||
params: &str,
|
||||
segment: Option<&str>,
|
||||
) -> Reply {
|
||||
let invalid = (400, "Invalid token id");
|
||||
let token = match segment {
|
||||
Some(raw) => percent_decode_str(raw).decode_utf8().map_err(|_| invalid)?,
|
||||
None => serde_urlencoded::from_str::<TokenQuery>(params)
|
||||
.map_err(|_| invalid)?
|
||||
.token_id
|
||||
.into(),
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let unavailable = |e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
};
|
||||
match name {
|
||||
"neg-risk" => {
|
||||
let flag = exchange
|
||||
.token_neg_risk(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
Ok(json!({"neg_risk":flag}))
|
||||
}
|
||||
"fee-rate" => {
|
||||
let fee = exchange
|
||||
.base_fee_bps(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "fee rate not found for market"))?;
|
||||
Ok(json!({"base_fee":fee}))
|
||||
}
|
||||
_ => {
|
||||
let tick = exchange
|
||||
.minimum_tick_size(&token)
|
||||
.map_err(unavailable)?
|
||||
.ok_or((404, "market not found"))?;
|
||||
Ok(json!({"minimum_tick_size":tick}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
|
||||
let is_token = prefix == "markets-by-token";
|
||||
let invalid = if is_token {
|
||||
"Invalid token id"
|
||||
} else {
|
||||
"Invalid condition id"
|
||||
};
|
||||
let id = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, invalid))?;
|
||||
let exchange = engine.lock().map_err(|_| (500, "Internal server error"))?;
|
||||
let info = if is_token {
|
||||
exchange.market_by_token(&id)
|
||||
} else {
|
||||
exchange.clob_market_info(&id)
|
||||
};
|
||||
info.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => (400, invalid),
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?
|
||||
.ok_or((if is_token { 404 } else { 400 }, "market not found"))
|
||||
}
|
||||
|
||||
fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
let (resource, tail) = path.strip_prefix('/')?.split_once('/')?;
|
||||
if !matches!(resource, "markets" | "events") {
|
||||
return None;
|
||||
}
|
||||
let (by_slug, raw) = match tail.strip_prefix("slug/") {
|
||||
Some(slug) => (true, slug),
|
||||
None => (false, tail),
|
||||
};
|
||||
(!raw.is_empty() && !raw.contains('/')).then_some((resource, by_slug, raw))
|
||||
}
|
||||
|
||||
fn directory_lookup(engine: &Mutex<Exchange>, route: (&str, bool, &str), params: &str) -> Reply {
|
||||
let (resource, by_slug, raw) = route;
|
||||
if !params.is_empty() {
|
||||
return Err((400, "Unsupported directory query"));
|
||||
}
|
||||
let value = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
let key = if by_slug {
|
||||
exchange::DirectoryKey::Slug(&value)
|
||||
} else {
|
||||
let id = value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|id| *id > 0 && value.bytes().all(|b| b.is_ascii_digit()))
|
||||
.ok_or((400, "Invalid directory id"))?;
|
||||
exchange::DirectoryKey::Id(id)
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Directory unavailable"))?;
|
||||
let found = match resource {
|
||||
"markets" => exchange.gamma_market(key),
|
||||
_ => exchange.gamma_event(key),
|
||||
};
|
||||
found
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.ok_or((404, "Not found"))
|
||||
}
|
||||
|
||||
fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
let invalid = (400, "Invalid clarification query");
|
||||
let fields: Vec<(String, String)> = serde_urlencoded::from_str(query).map_err(|_| invalid)?;
|
||||
let mut ids = Vec::new();
|
||||
let mut events = Vec::new();
|
||||
let mut limit = 20;
|
||||
let mut offset = 0;
|
||||
let mut ascending = false;
|
||||
for (key, value) in fields {
|
||||
match key.as_str() {
|
||||
"event_id" => events.push(value.parse().map_err(|_| invalid)?),
|
||||
"market_id" => ids.push(value.parse().map_err(|_| invalid)?),
|
||||
"limit" => limit = value.parse().map_err(|_| invalid)?,
|
||||
"offset" => offset = value.parse().map_err(|_| invalid)?,
|
||||
"ascending" => ascending = value.parse().map_err(|_| invalid)?,
|
||||
"order" if value == "id" => {}
|
||||
_ => return Err(invalid),
|
||||
}
|
||||
}
|
||||
let rows = engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Internal server error"))?
|
||||
.filtered_market_clarifications(&ids, &events, limit, offset, ascending)
|
||||
.map_err(|e| match e {
|
||||
exchange::MarketDataError::Invalid(_) => invalid,
|
||||
exchange::MarketDataError::Unavailable => (500, "Internal server error"),
|
||||
})?;
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
let (path, params) = req.url().split_once('?').unwrap_or((req.url(), ""));
|
||||
let mut allow = None;
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
"/v2/tokens"
|
||||
| "/v2/prices-history"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/value"
|
||||
| "/v2/oi"
|
||||
)
|
||||
{
|
||||
let (status, body) = data_page(path, params, engine);
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let route = path.strip_prefix('/').unwrap_or(path);
|
||||
let (name, segment) = route
|
||||
.split_once('/')
|
||||
.map_or((route, None), |(name, id)| (name, Some(id)));
|
||||
let is_setting = path == "/neg-risk"
|
||||
|| (matches!(name, "tick-size" | "fee-rate")
|
||||
&& !segment.is_some_and(|id| id.contains('/')));
|
||||
let lookup = path
|
||||
.strip_prefix('/')
|
||||
.and_then(|p| p.split_once('/'))
|
||||
.filter(|(prefix, id)| {
|
||||
matches!(*prefix, "markets-by-token" | "clob-markets") && !id.contains('/')
|
||||
});
|
||||
if let Some((prefix, id)) = lookup {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let (status, body) = match market_lookup(engine, prefix, id) {
|
||||
Ok(value) => (200, value),
|
||||
Err((status, msg)) => (status, json!({"error":msg})),
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let reply = match (req.method(), path) {
|
||||
(&Method::Get, _) if is_setting => token_setting(name, engine, params, segment),
|
||||
(_, _) if is_setting => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(&Method::Get, "/markets" | "/events") => {
|
||||
let resource = if path == "/events" {
|
||||
exchange::DirectoryResource::Events
|
||||
} else {
|
||||
exchange::DirectoryResource::Markets
|
||||
};
|
||||
let result = serde_urlencoded::from_str::<Vec<(String, String)>>(params)
|
||||
.map_err(|_| exchange::MarketDataError::Invalid("Invalid directory query".into()))
|
||||
.and_then(|fields| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| exchange::MarketDataError::Unavailable)?
|
||||
.gamma_list(resource, &fields)
|
||||
});
|
||||
match result {
|
||||
Ok(page) => Ok(Value::Array(page)),
|
||||
Err(exchange::MarketDataError::Invalid(message)) => {
|
||||
return send(req, 422, json!({"error":message}), None)
|
||||
}
|
||||
Err(exchange::MarketDataError::Unavailable) => Err((500, "Directory unavailable")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, "/market-clarifications") => clarifications(engine, params),
|
||||
(&Method::Get, "/prices-history") => {
|
||||
let result = serde_urlencoded::from_str::<exchange::ClobHistoryQuery>(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))
|
||||
.and_then(|query| {
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| HistoryError::Unavailable)?
|
||||
.clob_price_history(query)
|
||||
});
|
||||
match result {
|
||||
Ok(history) => Ok(history),
|
||||
Err(HistoryError::Invalid(message)) => {
|
||||
return send(req, 400, json!({"error":message}), None)
|
||||
}
|
||||
Err(HistoryError::Unavailable) => Err((500, "Internal server error")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, "/price") => serde_urlencoded::from_str::<WirePrice>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| book_prices(engine, vec![p], true)),
|
||||
(&Method::Post, "/prices") => {
|
||||
batch_params::<WirePrice>(&mut req).and_then(|rows| book_prices(engine, rows, false))
|
||||
}
|
||||
(&Method::Get, "/prices") => Err((400, "Invalid payload")),
|
||||
(&Method::Get, "/spread" | "/midpoint") => {
|
||||
let field = if path == "/spread" {
|
||||
QuoteField::Spread
|
||||
} else {
|
||||
QuoteField::Midpoint
|
||||
};
|
||||
serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| quote_response(engine, vec![p.token_id], field, true))
|
||||
}
|
||||
(&Method::Post, "/spreads" | "/midpoints") => {
|
||||
let field = if path == "/spreads" {
|
||||
QuoteField::Spread
|
||||
} else {
|
||||
QuoteField::Midpoint
|
||||
};
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
quote_response(
|
||||
engine,
|
||||
p.into_iter().map(|b| b.token_id).collect(),
|
||||
field,
|
||||
false,
|
||||
)
|
||||
})
|
||||
}
|
||||
(&Method::Get, "/midpoints") => Err((400, "Invalid payload")),
|
||||
(&Method::Get, "/book") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| query(engine, vec![p], true)),
|
||||
(&Method::Post, "/books") => {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| query(engine, p, false))
|
||||
}
|
||||
(&Method::Get, "/last-trade-price") => serde_urlencoded::from_str::<BookParam>(params)
|
||||
.map_err(|_| (400, "Invalid token id"))
|
||||
.and_then(|p| last_prices(engine, vec![p.token_id], true)),
|
||||
(&Method::Get, "/last-trades-prices") => Err((400, "Invalid payload")),
|
||||
(&Method::Post, "/last-trades-prices") => {
|
||||
batch_params::<BookParam>(&mut req).and_then(|p| {
|
||||
last_prices(
|
||||
engine,
|
||||
p.into_iter().map(|item| item.token_id).collect(),
|
||||
false,
|
||||
)
|
||||
})
|
||||
}
|
||||
(_, "/prices" | "/last-trades-prices" | "/midpoints") => {
|
||||
allow = Some("GET, POST");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(
|
||||
_,
|
||||
"/price"
|
||||
| "/midpoint"
|
||||
| "/spread"
|
||||
| "/book"
|
||||
| "/last-trade-price"
|
||||
| "/prices-history"
|
||||
| "/markets"
|
||||
| "/events"
|
||||
| "/market-clarifications"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/tokens"
|
||||
| "/v2/trades"
|
||||
| "/v2/resolutions"
|
||||
| "/v2/prices-history",
|
||||
) => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
(_, "/books" | "/spreads") => {
|
||||
allow = Some("POST");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
_ => match directory_route(path) {
|
||||
Some(route) if req.method() == &Method::Get => directory_lookup(engine, route, params),
|
||||
Some(_) => {
|
||||
allow = Some("GET");
|
||||
Err((405, "Method not allowed"))
|
||||
}
|
||||
None => Err((404, "Not found")),
|
||||
},
|
||||
};
|
||||
let (status, body) = match reply {
|
||||
Ok(v) => (200, v),
|
||||
Err((status, msg)) => (status, json!({"error":msg})),
|
||||
};
|
||||
send(req, status, body, allow)
|
||||
}
|
||||
|
||||
fn read_page<Q: serde::de::DeserializeOwned>(
|
||||
params: &str,
|
||||
engine: &Mutex<Exchange>,
|
||||
read: fn(&Exchange, Q) -> Result<Value, HistoryError>,
|
||||
) -> Result<Value, HistoryError> {
|
||||
let query = serde_urlencoded::from_str(params)
|
||||
.map_err(|_| HistoryError::Invalid("invalid query parameters".into()))?;
|
||||
let exchange = engine.lock().map_err(|_| HistoryError::Unavailable)?;
|
||||
read(&exchange, query)
|
||||
}
|
||||
|
||||
fn data_page(path: &str, params: &str, engine: &Mutex<Exchange>) -> (u16, Value) {
|
||||
let page = match path {
|
||||
"/v2/tokens" => read_page(params, engine, Exchange::public_tokens),
|
||||
"/v2/oi" => read_page(params, engine, Exchange::public_open_interest),
|
||||
"/v2/value" => read_page(params, engine, Exchange::public_portfolio_value),
|
||||
"/v2/trades" => read_page(params, engine, Exchange::public_trade_feed),
|
||||
"/v2/resolutions" => read_page(params, engine, Exchange::public_resolutions),
|
||||
_ => read_page(params, engine, Exchange::public_price_history),
|
||||
};
|
||||
match page {
|
||||
Ok(data) => (200, data),
|
||||
Err(HistoryError::Invalid(message)) => (
|
||||
400,
|
||||
json!({"code":"invalid_request","error":message,"retryable":false}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/tokens" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"token directory unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/oi" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"open interest unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/value" => (
|
||||
503,
|
||||
json!({"code":"unavailable","error":"portfolio valuation unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/resolutions" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"resolution state unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) if path == "/v2/trades" => (
|
||||
500,
|
||||
json!({"code":"internal","error":"trade feed unavailable","retryable":true}),
|
||||
),
|
||||
Err(HistoryError::Unavailable) => (
|
||||
500,
|
||||
json!({"code":"internal_error","error":"history unavailable","retryable":true}),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io::Result<()> {
|
||||
let mut response = Response::from_data(body.to_string().into_bytes())
|
||||
.with_status_code(status)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap());
|
||||
if status == 503 {
|
||||
response = response.with_header(Header::from_bytes("Retry-After", "1").unwrap());
|
||||
}
|
||||
if let Some(method) = allow {
|
||||
response.add_header(Header::from_bytes("Allow", method).unwrap());
|
||||
}
|
||||
req.respond(response)
|
||||
}
|
||||
|
||||
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
|
||||
let server = Server::from_listener(listener, None).map_err(anyhow::Error::from_boxed)?;
|
||||
let engine = Mutex::new(engine);
|
||||
thread::scope(|scope| {
|
||||
for _ in 0..4 {
|
||||
scope.spawn(|| {
|
||||
for req in server.incoming_requests() {
|
||||
if let Err(err) = respond(req, &engine) {
|
||||
eprintln!("market HTTP response: {err}");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::{io::Write, net::TcpStream, time::Duration};
|
||||
|
||||
#[test]
|
||||
fn socket_serves_single_and_batch_books_and_rejects_invalid_requests() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
let market = "map 2:胜者";
|
||||
db.execute(
|
||||
json!({"op":"list","id":"list","market":market,"rules":"simulated","tick_size":"0.01"}),
|
||||
)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"list","id":"path-market","market":"map+2/1","rules":"simulation","tick_size":"0.0025","base_fees":{"maker_bps":0,"taker_bps":30},"taker_fee_rate_ppm":50000})).unwrap();
|
||||
let yes = format!("eb:YES:{market}");
|
||||
let no = format!("eb:NO:{market}");
|
||||
let expected_yes = db
|
||||
.execute(json!({"op":"clob_book","token_id":yes}))
|
||||
.unwrap();
|
||||
let expected_no = db.execute(json!({"op":"clob_book","token_id":no})).unwrap();
|
||||
let max_batch = vec![json!({"token_id":yes}); MAX_BOOKS];
|
||||
let too_many = vec![json!({"token_id":yes}); MAX_BOOKS + 1];
|
||||
let addr = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = addr.local_addr().unwrap();
|
||||
let server = Server::from_listener(addr, None).unwrap();
|
||||
let encoded = "/book?token_id=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85";
|
||||
let mixed = json!([
|
||||
{"token_id":no}, {"token_id":"7"}, {"token_id":yes,"side":"BUY"}, {"token_id":no}
|
||||
]);
|
||||
let no_fills = json!({"price":"0.5","side":""});
|
||||
let batch_no_fills = json!([]);
|
||||
let csv = serde_urlencoded::to_string([("token_ids", format!("{yes},{no}"))]).unwrap();
|
||||
let last_batch = format!("/last-trades-prices?{csv}");
|
||||
let last_single = encoded.replacen("/book?", "/last-trade-price?", 1);
|
||||
let tick_query = encoded.replacen("/book?", "/tick-size?", 1);
|
||||
let lookup_pair = json!({"condition_id":"map+2/1","primary_token_id":"eb:YES:map+2/1","secondary_token_id":"eb:NO:map+2/1"});
|
||||
let lookup_info = json!({"mbf":0,"tbf":30,"fd":{"r":0.05,"e":1,"to":true},"gst":null,"nr":false,"rfqe":false,"ibce":false,"oas":0,"mos":0.01,"mts":0.0025,
|
||||
"t":[{"o":"YES","t":"eb:YES:map+2/1"},{"o":"NO","t":"eb:NO:map+2/1"}]});
|
||||
for command in [
|
||||
json!({"op":"fund","id":"v-fund","account":"unpriced-owner","cents":100}),
|
||||
json!({"op":"list","id":"v-list","market":"unpriced","rules":"valuation fixture"}),
|
||||
json!({"op":"split","id":"v-split","account":"unpriced-owner","market":"unpriced","qty":1}),
|
||||
json!({"op":"list","id":"s-list","market":"s","rules":"spread fixture"}),
|
||||
json!({"op":"open","id":"s-open","market":"s"}),
|
||||
json!({"op":"fund","id":"s-f1","account":"a","cents":100}),
|
||||
json!({"op":"fund","id":"s-f2","account":"b","cents":100}),
|
||||
json!({"op":"order","id":"s-bid","asset_id":"eb:YES:s","account":"a","side":"buy","price":39,"qty":1}),
|
||||
json!({"op":"list","id":"one-list","market":"one","rules":"one-sided fixture"}),
|
||||
json!({"op":"open","id":"one-open","market":"one"}),
|
||||
json!({"op":"order","id":"one-bid","asset_id":"eb:YES:one","account":"b","side":"buy","price":20,"qty":1}),
|
||||
json!({"op":"order","id":"s-comp","asset_id":"eb:NO:s","account":"b","side":"buy","price":59,"qty":1}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
for line in include_str!("../../../docs/examples/midpoint.jsonl").lines() {
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
let sample = json!({"eb:YES:mid-example":"0.085","eb:NO:mid-example":"0.915"});
|
||||
let pair = json!({"eb:YES:s":"0.4","eb:NO:s":"0.6","eb:YES:one":"0.6"});
|
||||
let price_batch = json!({"eb:YES:mid-example":{"BUY":"0.08","SELL":"0.09"},"eb:NO:mid-example":{"BUY":"0.91"},"eb:YES:one":{"BUY":"0.2"}});
|
||||
db.execute(json!({"op":"publish_clarification","id":"note","market":market,"content":"Map one includes overtime.","clear_book":false})).unwrap();
|
||||
let note = db
|
||||
.execute(json!({"op":"resolution","market":market}))
|
||||
.unwrap()["clarifications"]
|
||||
.clone();
|
||||
let note_id = note[0]["marketId"].as_i64().unwrap();
|
||||
let note_query = format!(
|
||||
"/market-clarifications?market_id=9999&market_id={note_id}&order=id&ascending=true"
|
||||
);
|
||||
for command in include_str!("../../../docs/examples/topic.jsonl")
|
||||
.lines()
|
||||
.take(3)
|
||||
{
|
||||
db.execute(serde_json::from_str(command).unwrap()).unwrap();
|
||||
}
|
||||
let topic = db
|
||||
.gamma_event(exchange::DirectoryKey::Slug("nvda-closing-price-2027"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let event_path = format!("/events/{}", topic["id"].as_str().unwrap());
|
||||
let first_child = &topic["markets"][0];
|
||||
assert_eq!(first_child["conditionId"], "nvda-200");
|
||||
assert_eq!(topic["markets"].as_array().unwrap().len(), 2);
|
||||
let info = db
|
||||
.gamma_market(exchange::DirectoryKey::Slug("nvda-200"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let market_path = format!("/markets/{}", info["id"].as_str().unwrap());
|
||||
assert_eq!(info["events"][0]["id"], topic["id"]);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<[String; 2]>(info["clobTokenIds"].as_str().unwrap()).unwrap()[0],
|
||||
"eb:YES:nvda-200"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_str::<[String; 2]>(info["outcomes"].as_str().unwrap()).unwrap()[1],
|
||||
"未超过"
|
||||
);
|
||||
let separate = db
|
||||
.gamma_market(exchange::DirectoryKey::Slug("map+2/1"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(separate["events"], json!([]));
|
||||
let quoted = db
|
||||
.gamma_market(exchange::DirectoryKey::Slug("s"))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(quoted["bestBid"], json!(0.39));
|
||||
assert_eq!(quoted["bestAsk"], json!(0.41));
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/tokens?token_ids=eb:NO:s,00123,eb:NO:s,eb:YES:s",String::new(),200,Some(db.public_tokens(serde_json::from_value(json!({"token_id":"eb:NO:s,123,eb:YES:s"})).unwrap()).unwrap())),
|
||||
("GET","/v2/tokens?condition=s&token_id=eb:YES:s",String::new(),400,None),
|
||||
("GET","/v2/tokens?token_id=00123,123",String::new(),200,Some(json!({"data":[]}))),
|
||||
("POST","/v2/tokens",String::new(),405,None),
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
("GET","/v2/oi?condition_id=0x0000000000000000000000000000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/oi?condition=bad-hash",String::new(),400,Some(json!({"code":"invalid_request","error":"invalid condition: bad-hash","retryable":false}))),
|
||||
("GET","/v2/oi",String::new(),503,None),
|
||||
("POST","/v2/oi",String::new(),405,None),
|
||||
("GET","/v2/value?user=0x0000000000000000000000000000000000000001",String::new(),200,Some(json!({"data":{"proxy_wallet":"0x0000000000000000000000000000000000000001","value":0}}))),
|
||||
("GET","/v2/value",String::new(),400,None),
|
||||
("GET","/v2/value?user=unpriced-owner",String::new(),503,None),
|
||||
("GET","/v2/value?user=a&condition=",String::new(),400,None),
|
||||
("GET","/v2/value?user=0x4d97dcd97ec945f40cf65f87097ace5ea0476045",String::new(),400,None),
|
||||
("POST","/v2/value",String::new(),405,None),
|
||||
("GET","/v2/trades?user=unknown&conditionId=unknown&takerOnly=false",String::new(),200,Some(empty_trades)),
|
||||
("GET","/v2/trades?offset=2",String::new(),400,None),
|
||||
("GET","/v2/trades?cursor=invalid",String::new(),400,None),
|
||||
("GET","/v2/resolutions?condition=unknown",String::new(),200,Some(json!({"data":[]}))),
|
||||
("GET","/v2/resolutions?condition=m&eventId=1",String::new(),400,None),
|
||||
("GET","/v2/resolutions?questionId=invalid",String::new(),400,None),
|
||||
("POST","/v2/resolutions",String::new(),405,None),
|
||||
("POST","/v2/trades",String::new(),405,None),
|
||||
("GET","/events?slug=nvda-closing-price-2027&closed=ANY",String::new(),200,Some(json!([topic]))),
|
||||
("GET","/markets?condition_ids=nvda-200&clob_token_ids=eb%3ANO%3Anvda-200&closed=Any",String::new(),200,Some(json!([info]))),
|
||||
("GET","/markets?active=true&closed=false&slug=map%2B2%2F1",String::new(),200,Some(json!([separate]))),
|
||||
("GET","/markets?condition_ids=s&clob_token_ids=unknown&closed=any",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?closed=any",String::new(),422,None),
|
||||
("GET","/events?closed=open",String::new(),422,None),
|
||||
("GET","/markets?limit=0",String::new(),200,Some(json!([]))),
|
||||
("GET","/events?order=unknown",String::new(),422,None),
|
||||
("POST","/markets",String::new(),405,None),
|
||||
("GET",event_path.as_str(),String::new(),200,Some(topic.clone())),
|
||||
("GET","/events/slug/nvda-closing-price-2027",String::new(),200,Some(topic)),
|
||||
("GET",market_path.as_str(),String::new(),200,Some(info.clone())),
|
||||
("GET","/markets/slug/nvda-200",String::new(),200,Some(info)),
|
||||
("GET","/markets/slug/map+2%2F1",String::new(),200,Some(separate)),
|
||||
("GET","/events/0",String::new(),400,None),
|
||||
("GET","/markets/slug/missing",String::new(),404,None),
|
||||
("GET","/events/999999",String::new(),404,None),
|
||||
("POST","/events/slug/test","{}".into(),405,None),
|
||||
("GET","/market-clarifications?event_id=1&event_id=2",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?event_id=0",String::new(),400,None),
|
||||
("GET",note_query.as_str(),String::new(),200,Some(note)),
|
||||
("GET","/market-clarifications?limit=0",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?offset=1",String::new(),200,Some(json!([]))),
|
||||
("GET","/market-clarifications?limit=101",String::new(),400,None),
|
||||
("POST","/market-clarifications","{}".into(),405,None),
|
||||
("GET","/prices-history?market=eb:YES:missing&interval=1h&fidelity=10",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:NO:missing&startTs=1000&endTs=2000",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:YES:missing&startTs=1000",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:YES:missing&interval=1d&fidelity=0",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:YES:missing&startTs=1&endTs=2&interval=max",String::new(),200,Some(json!({"history":[]}))),
|
||||
("GET","/prices-history?market=eb:YES:s&interval=1w&fidelity=4",String::new(),400,Some(json!({"error":"invalid filters: minimum 'fidelity' for '1w' range is 5"}))),
|
||||
("GET","/prices-history?market=eb:YES:s&startTs=100&endTs=1296101",String::new(),400,Some(json!({"error":"invalid filters: 'startTs' and 'endTs' interval is too long"}))),
|
||||
("POST","/prices-history","{}".into(),405,None),
|
||||
("GET","/price?token_id=eb:YES:mid-example&side=BUY",String::new(),200,Some(json!({"price":"0.08"}))),
|
||||
("GET","/price?token_id=eb:YES:mid-example&side=SELL",String::new(),200,Some(json!({"price":"0.09"}))),
|
||||
("GET","/price?token_id=eb:YES:one&side=SELL",String::new(),200,Some(json!({"price":"1"}))),
|
||||
("GET","/price?token_id=eb:YES:one&side=BUY",String::new(),200,Some(json!({"price":"0.2"}))),
|
||||
("GET","/price?token_id=eb:YES:missing&side=BUY",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("GET","/price?token_id=eb:YES:s&side=HOLD",String::new(),400,Some(json!({"error":"Invalid side"}))),
|
||||
("GET","/price?token_id=broken&side=BUY",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/prices?token_ids=eb:YES:mid-example,eb:YES:mid-example,eb:NO:mid-example&sides=BUY,SELL,BUY",String::new(),400,Some(json!({"error":"Invalid payload"}))),
|
||||
("POST","/prices",json!([{"token_id":"eb:YES:mid-example","side":"BUY"},{"token_id":"eb:NO:mid-example","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"SELL"},{"token_id":"eb:YES:one","side":"BUY"},{"token_id":"eb:YES:mid-example","side":"BUY"}]).to_string(),200,Some(price_batch)),
|
||||
("GET","/prices?token_ids=eb:YES:s,eb:NO:s&sides=BUY",String::new(),400,Some(json!({"error":"Invalid payload"}))),
|
||||
("POST","/prices",json!([{"token_id":"eb:YES:s","side":"BUY"},{"token_id":"eb:NO:missing","side":"SELL"}]).to_string(),200,Some(json!({"eb:YES:s":{"BUY":"0.39"}}))),
|
||||
("POST","/prices",json!([{"token_id":"eb:YES:s"}]).to_string(),200,Some(json!({"eb:YES:s":{"SELL":"0.41"}}))),
|
||||
("POST","/prices",json!(vec![json!({"token_id":"eb:YES:s","side":"BUY"}); MAX_BOOKS+1]).to_string(),400,None),
|
||||
("DELETE","/prices",String::new(),405,None),
|
||||
("GET","/midpoint?token_id=eb:YES:mid-example",String::new(),200,Some(json!({"mid":"0.085"}))),
|
||||
("POST","/midpoints",json!([{"token_id":"eb:YES:mid-example"},{"token_id":"eb:NO:mid-example"}]).to_string(),200,Some(sample)),
|
||||
("GET","/midpoint?token_id=eb:YES:s",String::new(),200,Some(json!({"mid":"0.4"}))),
|
||||
("GET","/midpoints?token_ids=eb:YES:s%2Ceb:NO:s",String::new(),400,Some(json!({"error":"Invalid payload"}))),
|
||||
("POST","/midpoints",json!([{"token_id":"eb:NO:s","side":"BUY"},{"token_id":"eb:YES:one"},{"token_id":"eb:YES:s"},{"token_id":"eb:YES:s"}]).to_string(),200,Some(pair)),
|
||||
("GET","/midpoint?token_id=eb:NO:one",String::new(),200,Some(json!({"mid":"0.4"}))),
|
||||
("GET","/midpoint?token_id=eb:YES:missing",String::new(),404,None),
|
||||
("GET","/midpoint",String::new(),400,None),
|
||||
("POST","/midpoints",json!(too_many).to_string(),400,None),
|
||||
("DELETE","/midpoints",String::new(),405,None),
|
||||
("GET","/spread?token_id=eb:YES:s",String::new(),200,Some(json!({"spread":"0.02"}))),
|
||||
("POST","/spreads",json!([{"token_id":"eb:YES:s"},{"token_id":"eb:NO:s","side":"SELL"},{"token_id":"eb:YES:s"},{"token_id":yes}]).to_string(),200,Some(json!({"eb:YES:s":"0.02","eb:NO:s":"0.02",(yes.as_str()):"1"}))),
|
||||
("GET","/spread?token_id=eb:NO:one",String::new(),200,Some(json!({"spread":"0.8"}))),
|
||||
("GET","/spread?token_id=eb:YES:missing",String::new(),404,Some(json!({"error":MISSING}))),
|
||||
("GET","/spread?token_id=eb:YES:map%2B2%2F1",String::new(),200,Some(json!({"spread":"1"}))),
|
||||
("POST","/spreads",json!(too_many).to_string(),400,None),
|
||||
("GET","/spreads",String::new(),405,None),
|
||||
("GET","/markets-by-token/eb:NO:map+2%2F1",String::new(),200,Some(lookup_pair)),
|
||||
("GET","/clob-markets/map+2%2F1",String::new(),200,Some(lookup_info)),
|
||||
("GET","/markets-by-token/eb:YES:missing",String::new(),404,None),
|
||||
("GET","/markets-by-token/garbage",String::new(),400,None),
|
||||
("GET","/clob-markets/missing",String::new(),400,None),
|
||||
("POST","/clob-markets/map+2%2F1","{}".into(),405,None),
|
||||
("GET",tick_query.as_str(),String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("GET","/neg-risk?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"neg_risk":false}))),
|
||||
("GET","/neg-risk?token_id=eb%3ANO%3Amissing",String::new(),404,None),
|
||||
("GET","/neg-risk?token_id=bad",String::new(),400,None),
|
||||
("GET","/neg-risk",String::new(),400,None),
|
||||
("POST","/neg-risk",String::new(),405,None),
|
||||
("GET","/fee-rate?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"base_fee":30}))),
|
||||
("GET","/fee-rate/eb:NO:map+2%2F1",String::new(),200,Some(json!({"base_fee":30}))),
|
||||
("GET","/fee-rate/eb:YES:s",String::new(),200,Some(json!({"base_fee":0}))),
|
||||
("GET","/fee-rate/eb:YES:missing",String::new(),404,Some(json!({"error":"fee rate not found for market"}))),
|
||||
("GET","/fee-rate/eb:NO:%FF",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/fee-rate",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("POST","/fee-rate/eb:YES:s",String::new(),405,None),
|
||||
("GET","/tick-size/eb%3ANO%3Amap%202%3A%E8%83%9C%E8%80%85",String::new(),200,Some(json!({"minimum_tick_size":0.01}))),
|
||||
("GET","/tick-size/eb:YES:map+2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
|
||||
("GET","/tick-size?token_id=eb%3AYES%3Amap%2B2%2F1",String::new(),200,Some(json!({"minimum_tick_size":0.0025}))),
|
||||
("GET","/tick-size/eb:YES:missing",String::new(),404,Some(json!({"error":"market not found"}))),
|
||||
("GET","/tick-size/",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/tick-size/eb:YES:%FF",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("GET","/tick-size",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("POST","/tick-size/eb:YES:e",String::new(),405,None),
|
||||
("GET",last_single.as_str(),String::new(),200,Some(no_fills)),
|
||||
("GET",last_batch.as_str(),String::new(),400,Some(json!({"error":"Invalid payload"}))),
|
||||
("POST","/last-trades-prices",json!([{"token_id":yes,"side":"SELL"},{"token_id":no}]).to_string(),200,Some(batch_no_fills)),
|
||||
("POST","/last-trades-prices","[]".into(),200,Some(json!([]))),
|
||||
("GET","/last-trade-price?token_id=eb:YES:missing",String::new(),200,Some(json!({"price":"0.5","side":""}))),
|
||||
("GET","/last-trade-price?token_id=",String::new(),400,Some(json!({"error":"Invalid token id"}))),
|
||||
("POST","/last-trades-prices",json!(too_many).to_string(),400,Some(json!({"error":"Invalid payload"}))),
|
||||
("DELETE","/last-trades-prices",String::new(),405,None),
|
||||
(
|
||||
"GET",
|
||||
encoded,
|
||||
String::new(),
|
||||
200,
|
||||
Some(expected_yes.clone()),
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/books",
|
||||
mixed.to_string(),
|
||||
200,
|
||||
Some(json!([expected_no, expected_yes, expected_no])),
|
||||
),
|
||||
(
|
||||
"GET",
|
||||
"/book?token_id=7",
|
||||
String::new(),
|
||||
404,
|
||||
Some(json!({"error": MISSING})),
|
||||
),
|
||||
("GET", "/book", String::new(), 400, None),
|
||||
("POST", "/books", "[]".into(), 200, Some(json!([]))),
|
||||
("POST", "/books", json!(max_batch).to_string(), 200, None),
|
||||
("POST", "/books", json!(too_many).to_string(), 400, None),
|
||||
(
|
||||
"POST",
|
||||
"/books",
|
||||
"{}".into(),
|
||||
400,
|
||||
Some(json!({"error":"Invalid payload"})),
|
||||
),
|
||||
(
|
||||
"POST",
|
||||
"/books",
|
||||
r#"[{"token_id":"7","side":"INVALID"}]"#.into(),
|
||||
400,
|
||||
None,
|
||||
),
|
||||
("GET", "/v2/prices-history?tokenId=eb%3AYES%3Amap+2%3A%E8%83%9C%E8%80%85&interval=1h&bucketSeconds=60", String::new(), 200,
|
||||
Some(json!({"data":[],"pagination":{"has_more":false,"next_cursor":null,"offset":0,"limit":10000}}))),
|
||||
("GET","/v2/prices-history?token_id=7&interval=1h",String::new(),400,None),
|
||||
("POST","/v2/prices-history",String::new(),405,None),
|
||||
("GET", "/books", String::new(), 405, None),
|
||||
("POST", "/order", "{}".into(), 404, None),
|
||||
];
|
||||
let count = cases.len();
|
||||
let worker = thread::spawn(move || {
|
||||
let db = Mutex::new(db);
|
||||
for _ in 0..count {
|
||||
let req = server
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
respond(req, &db).unwrap();
|
||||
}
|
||||
});
|
||||
for (method, path, body, status, expected) in cases {
|
||||
let mut socket = TcpStream::connect(port).unwrap();
|
||||
socket
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
write!(socket,"{method} {path} HTTP/1.0\r\nHost: {port}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",body.len()).unwrap();
|
||||
let mut message = String::new();
|
||||
socket.read_to_string(&mut message).unwrap();
|
||||
let (headers, body) = message.split_once("\r\n\r\n").unwrap();
|
||||
assert_eq!(
|
||||
headers.split_whitespace().nth(1).unwrap(),
|
||||
status.to_string()
|
||||
);
|
||||
assert!(headers
|
||||
.to_ascii_lowercase()
|
||||
.contains("content-type: application/json"));
|
||||
if status == 503 {
|
||||
assert!(headers.to_ascii_lowercase().contains("retry-after: 1"));
|
||||
}
|
||||
let actual: Value = serde_json::from_str(body).unwrap();
|
||||
if let Some(expected) = expected {
|
||||
assert_eq!(actual, expected);
|
||||
} else if status == 200 {
|
||||
assert_eq!(actual.as_array().unwrap().len(), MAX_BOOKS);
|
||||
} else {
|
||||
assert!(actual["error"].is_string());
|
||||
}
|
||||
}
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
use crate::subscriptions::Session;
|
||||
use anyhow::{Context, Result};
|
||||
use exchange::Exchange;
|
||||
use std::{
|
||||
io::ErrorKind,
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{Arc, Mutex},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tungstenite::{
|
||||
accept_hdr_with_config,
|
||||
handshake::server::{ErrorResponse, Request, Response},
|
||||
protocol::WebSocketConfig,
|
||||
Error, Message, WebSocket,
|
||||
};
|
||||
|
||||
const POLL: Duration = Duration::from_millis(100);
|
||||
|
||||
pub(crate) fn serve(engine: Exchange, listener: TcpListener) -> Result<()> {
|
||||
let engine = Arc::new(Mutex::new(engine));
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream?;
|
||||
// Each accepted session owns exactly one engine reference and one OS thread.
|
||||
if Arc::strong_count(&engine) > 128 {
|
||||
continue;
|
||||
}
|
||||
let engine = Arc::clone(&engine);
|
||||
thread::Builder::new()
|
||||
.name("market-ws".into())
|
||||
.spawn(move || {
|
||||
if let Err(err) = connection(stream, &engine) {
|
||||
eprintln!("market WebSocket: {err}");
|
||||
}
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send(socket: &mut WebSocket<TcpStream>, frame: serde_json::Value) -> Result<()> {
|
||||
socket.send(Message::text(serde_json::to_string(&frame)?))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn connection(stream: TcpStream, engine: &Mutex<Exchange>) -> Result<()> {
|
||||
stream.set_read_timeout(Some(Duration::from_secs(5)))?;
|
||||
stream.set_write_timeout(Some(Duration::from_secs(5)))?;
|
||||
let config = WebSocketConfig::default()
|
||||
.max_message_size(Some(65536))
|
||||
.max_frame_size(Some(65536));
|
||||
let mut socket = accept_hdr_with_config(
|
||||
stream,
|
||||
|req: &Request, resp: Response| {
|
||||
if req.uri().path() == "/ws/market" {
|
||||
Ok(resp)
|
||||
} else {
|
||||
let mut err = ErrorResponse::new(Some("unknown WebSocket path".into()));
|
||||
*err.status_mut() = tungstenite::http::StatusCode::NOT_FOUND;
|
||||
Err(err)
|
||||
}
|
||||
},
|
||||
Some(config),
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("market WebSocket handshake: {e}"))?;
|
||||
socket.get_mut().set_read_timeout(Some(POLL))?;
|
||||
let mut session = Session::default();
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
match socket.read() {
|
||||
Ok(Message::Text(s)) if s.as_str() == "PING" => socket.send(Message::text("PONG"))?,
|
||||
Ok(Message::Text(s)) => {
|
||||
let reply = {
|
||||
let mut engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
session.control(&mut engine, s.as_str())
|
||||
};
|
||||
match reply {
|
||||
Ok(snapshots) if !snapshots.is_empty() => send(&mut socket, snapshots.into())?,
|
||||
Ok(_) => {}
|
||||
Err(_) => socket.send(Message::text("INVALID OPERATION"))?,
|
||||
}
|
||||
}
|
||||
Ok(Message::Close(_)) => {
|
||||
let _ = socket.flush();
|
||||
break;
|
||||
}
|
||||
Ok(Message::Ping(_)) => socket.flush()?,
|
||||
Ok(_) => {}
|
||||
Err(Error::Io(err))
|
||||
if matches!(err.kind(), ErrorKind::TimedOut | ErrorKind::WouldBlock) => {}
|
||||
Err(Error::ConnectionClosed | Error::AlreadyClosed) => break,
|
||||
Err(err) => return Err(err).context("read market WebSocket"),
|
||||
}
|
||||
if Instant::now() >= next {
|
||||
let frames = {
|
||||
let mut engine = engine
|
||||
.lock()
|
||||
.map_err(|_| anyhow::anyhow!("exchange unavailable"))?;
|
||||
session.poll(&mut engine)?
|
||||
};
|
||||
for frame in frames {
|
||||
send(&mut socket, frame)?;
|
||||
}
|
||||
next = Instant::now() + POLL;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[test]
|
||||
fn market_socket_sends_snapshots_deltas_and_application_pongs() {
|
||||
let mut engine = Exchange::open(":memory:").unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list","market":"demo","rules":"r","tick_size":"0.01"}),
|
||||
json!({"op":"fund","id":"fund","account":"maker","cents":500}),
|
||||
json!({"op":"open","id":"open","market":"demo"}),
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let engine = Arc::new(Mutex::new(engine));
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let db = Arc::clone(&engine);
|
||||
let worker = thread::spawn(move || connection(listener.accept().unwrap().0, &db));
|
||||
let tcp = TcpStream::connect(addr).unwrap();
|
||||
tcp.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
let (mut client, _) = tungstenite::client(format!("ws://{addr}/ws/market"), tcp).unwrap();
|
||||
let controls: Vec<&str> = include_str!("../../../docs/examples/market-ws.txt")
|
||||
.lines()
|
||||
.collect();
|
||||
client.send(Message::text(controls[0])).unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // initial_dump=false
|
||||
client.send(Message::text(controls[1])).unwrap();
|
||||
let frames: Value =
|
||||
serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(frames.as_array().unwrap().len(), 1);
|
||||
assert_eq!(frames[0]["asset_id"], "eb:NO:demo");
|
||||
assert_eq!(frames[0]["event_type"], "book");
|
||||
client.send(Message::text(controls[2])).unwrap();
|
||||
client.send(Message::text("PING")).unwrap();
|
||||
assert_eq!(client.read().unwrap().into_text().unwrap(), "PONG"); // unsubscribe processed
|
||||
engine.lock().unwrap().execute(json!({"op":"order","id":"bid","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"qty":1})).unwrap();
|
||||
let delta: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(delta["event_type"], "price_change");
|
||||
assert!(delta["timestamp"].as_str().unwrap().parse::<i64>().is_ok());
|
||||
assert_eq!(delta["price_changes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(delta["price_changes"][0]["asset_id"], "eb:NO:demo");
|
||||
assert_eq!(delta["price_changes"][0]["price"], "0.7");
|
||||
let quote: Value = serde_json::from_str(client.read().unwrap().to_text().unwrap()).unwrap();
|
||||
assert_eq!(quote["event_type"], "best_bid_ask");
|
||||
assert_eq!(quote["best_ask"], "0.7");
|
||||
assert!(quote["best_bid"].is_null());
|
||||
client.close(None).unwrap();
|
||||
worker.join().unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,51 @@
|
||||
use anyhow::Result;
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, Write};
|
||||
use std::{
|
||||
io::{BufRead, Write},
|
||||
sync::mpsc::{sync_channel, RecvTimeoutError},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
pub(crate) fn serve(
|
||||
engine: &mut Exchange,
|
||||
input: impl BufRead,
|
||||
input: impl BufRead + Send + 'static,
|
||||
mut output: impl Write,
|
||||
) -> Result<()> {
|
||||
for line in input.lines() {
|
||||
let line = line?;
|
||||
// The engine stays on one thread. A bounded input queue permits idle
|
||||
// maintenance without buffering an unbounded command stream.
|
||||
let (sender, reader) = sync_channel(1);
|
||||
thread::spawn(move || {
|
||||
for line in input.lines() {
|
||||
let failed = line.is_err();
|
||||
if sender.send(line).is_err() || failed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let interval = Duration::from_secs(5);
|
||||
// New GTDs live at least two minutes, so rechecking within five seconds
|
||||
// also catches orders added by another process before their cutoff.
|
||||
let next_check = |exchange: &Exchange| -> Result<Instant> {
|
||||
let start = Instant::now();
|
||||
let wait = exchange
|
||||
.next_gtd_expiry()?
|
||||
.unwrap_or(interval)
|
||||
.min(interval);
|
||||
Ok(start + wait)
|
||||
};
|
||||
let mut next = next_check(engine)?;
|
||||
loop {
|
||||
if Instant::now() >= next {
|
||||
engine.maintain()?;
|
||||
next = next_check(engine)?;
|
||||
}
|
||||
let line = match reader.recv_timeout(next.saturating_duration_since(Instant::now())) {
|
||||
Ok(line) => line?,
|
||||
Err(RecvTimeoutError::Timeout) => continue,
|
||||
Err(RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
let result = serde_json::from_str::<Value>(&line)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|v| engine.execute(v));
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::{parse_asset_id, Exchange, MarketPage};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Control {
|
||||
#[serde(rename = "type")]
|
||||
channel: Option<String>,
|
||||
operation: Option<String>,
|
||||
assets_ids: Vec<String>,
|
||||
initial_dump: Option<bool>,
|
||||
custom_feature_enabled: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Asset {
|
||||
since: i64,
|
||||
bid: Option<String>,
|
||||
ask: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct Market {
|
||||
cursor: i64,
|
||||
assets: BTreeMap<String, Asset>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct Session {
|
||||
opened: bool,
|
||||
custom: bool,
|
||||
discovery_cursor: i64,
|
||||
markets: BTreeMap<String, Market>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn control(&mut self, engine: &mut Exchange, text: &str) -> Result<Vec<Value>> {
|
||||
let c: Control = serde_json::from_str(text)?;
|
||||
let opening = !self.opened;
|
||||
let subscribe = match (opening, c.channel.as_deref(), c.operation.as_deref()) {
|
||||
(true, Some("market"), None) | (false, None, Some("subscribe")) => true,
|
||||
(false, None, Some("unsubscribe")) => false,
|
||||
_ => anyhow::bail!("invalid market subscription operation"),
|
||||
};
|
||||
ensure!(!c.assets_ids.is_empty(), "assets_ids required");
|
||||
let mut groups = BTreeMap::<String, BTreeSet<String>>::new();
|
||||
for token in c.assets_ids {
|
||||
let (_, market) = parse_asset_id(&token)?;
|
||||
groups.entry(market.into()).or_default().insert(token);
|
||||
}
|
||||
// Validate all assets before replacing a live subscription.
|
||||
let mut next = self.clone();
|
||||
if opening {
|
||||
next.opened = true;
|
||||
next.custom = c.custom_feature_enabled.unwrap_or(false);
|
||||
}
|
||||
if subscribe && next.custom && next.markets.is_empty() {
|
||||
next.discovery_cursor = engine.market_discovery_page(None)?.cursor;
|
||||
}
|
||||
let mut snapshots = Vec::new();
|
||||
for (market, mut tokens) in groups {
|
||||
if !subscribe {
|
||||
if let Some(watch) = next.markets.get_mut(&market) {
|
||||
watch.assets.retain(|id, _| !tokens.contains(id));
|
||||
if watch.assets.is_empty() {
|
||||
next.markets.remove(&market);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(watch) = next.markets.get(&market) {
|
||||
tokens.retain(|id| !watch.assets.contains_key(id));
|
||||
}
|
||||
if tokens.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let page = engine.market_stream_page(&market, None)?;
|
||||
let watch = next.markets.entry(market).or_insert_with(|| Market {
|
||||
cursor: page.cursor,
|
||||
assets: BTreeMap::new(),
|
||||
});
|
||||
for (_, snapshot) in page.frames {
|
||||
let id = snapshot["asset_id"]
|
||||
.as_str()
|
||||
.context("snapshot asset missing")?;
|
||||
if !tokens.contains(id) {
|
||||
continue;
|
||||
}
|
||||
let best = |field: &str| {
|
||||
snapshot[field].as_array()?.last()?["price"]
|
||||
.as_str()
|
||||
.map(str::to_owned)
|
||||
};
|
||||
watch.assets.insert(
|
||||
id.into(),
|
||||
Asset {
|
||||
since: page.cursor,
|
||||
bid: best("bids"),
|
||||
ask: best("asks"),
|
||||
},
|
||||
);
|
||||
if !opening || c.initial_dump.unwrap_or(true) {
|
||||
snapshots.push(snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
*self = next;
|
||||
Ok(snapshots)
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, engine: &mut Exchange) -> Result<Vec<Value>> {
|
||||
let mut frames = Vec::new();
|
||||
if self.custom && !self.markets.is_empty() {
|
||||
let page = engine.market_discovery_page(Some(self.discovery_cursor))?;
|
||||
self.discovery_cursor = page.cursor;
|
||||
frames.extend(page.frames.into_iter().map(|(_, f)| f));
|
||||
}
|
||||
for (market, watch) in &mut self.markets {
|
||||
let page = engine.market_stream_page(market, Some(watch.cursor))?;
|
||||
watch.project(market, page, self.custom, &mut frames)?;
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
}
|
||||
|
||||
impl Market {
|
||||
fn project(
|
||||
&mut self,
|
||||
market: &str,
|
||||
page: MarketPage,
|
||||
custom: bool,
|
||||
frames: &mut Vec<Value>,
|
||||
) -> Result<()> {
|
||||
for (seq, mut event) in page.frames {
|
||||
if event["event_type"] == "market_resolved" {
|
||||
if custom && self.assets.values().any(|asset| seq > asset.since) {
|
||||
frames.push(event);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if event["event_type"] != "price_change" {
|
||||
let token = event["asset_id"]
|
||||
.as_str()
|
||||
.context("missing market event asset")?;
|
||||
if self
|
||||
.assets
|
||||
.get(token)
|
||||
.is_some_and(|asset| seq > asset.since)
|
||||
{
|
||||
frames.push(event);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let changes = event["price_changes"]
|
||||
.as_array_mut()
|
||||
.context("missing price changes")?;
|
||||
changes.retain(|c| {
|
||||
c["asset_id"]
|
||||
.as_str()
|
||||
.and_then(|id| self.assets.get(id))
|
||||
.is_some_and(|asset| seq > asset.since)
|
||||
});
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut top = Vec::new();
|
||||
if custom {
|
||||
for c in changes.iter() {
|
||||
let token = c["asset_id"].as_str().context("missing changed asset")?;
|
||||
let asset = self
|
||||
.assets
|
||||
.get_mut(token)
|
||||
.context("unknown changed asset")?;
|
||||
let bid = c["best_bid"].as_str();
|
||||
let ask = c["best_ask"].as_str();
|
||||
if (asset.bid.as_deref(), asset.ask.as_deref()) == (bid, ask) {
|
||||
continue;
|
||||
}
|
||||
asset.bid = bid.map(str::to_owned);
|
||||
asset.ask = ask.map(str::to_owned);
|
||||
let spread = bid.zip(ask).map(|(b, a)| spread(a, b)).transpose()?;
|
||||
top.push(
|
||||
json!({"event_type":"best_bid_ask","market":market,"asset_id":token,
|
||||
"best_bid":bid,"best_ask":ask,"spread":spread}),
|
||||
);
|
||||
}
|
||||
}
|
||||
for quote in &mut top {
|
||||
quote["timestamp"] = event["timestamp"].clone();
|
||||
}
|
||||
frames.push(event);
|
||||
frames.extend(top);
|
||||
}
|
||||
self.cursor = page.cursor;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn spread(ask: &str, bid: &str) -> Result<String> {
|
||||
fn units(s: &str) -> Result<i64> {
|
||||
let (w, f) = s.split_once('.').unwrap_or((s, ""));
|
||||
ensure!(f.len() <= 4, "invalid book price precision");
|
||||
Ok(w.parse::<i64>()? * 10000 + format!("{f:0<4}").parse::<i64>()?)
|
||||
}
|
||||
let n = units(ask)? - units(bid)?;
|
||||
let sign = if n < 0 { "-" } else { "" };
|
||||
let n = n.abs();
|
||||
Ok(format!("{sign}{}.{:04}", n / 10000, n % 10000)
|
||||
.trim_end_matches('0')
|
||||
.trim_end_matches('.')
|
||||
.to_owned())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn adding_an_asset_does_not_skip_backlog_or_replay_before_its_snapshot() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"l","market":"demo","rules":"r"}),
|
||||
json!({"op":"fund","id":"f","account":"maker","cents":200}),
|
||||
json!({"op":"open","id":"o","market":"demo"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let mut session = Session::default();
|
||||
let opening = r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#;
|
||||
assert_eq!(session.control(&mut db, opening).unwrap().len(), 1);
|
||||
db.execute(json!({"op":"order","id":"a","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1})).unwrap();
|
||||
let subscribe = r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#;
|
||||
let snap = session.control(&mut db, subscribe).unwrap();
|
||||
assert_eq!(snap[0]["asks"][0]["price"], "0.8");
|
||||
assert!(session.control(&mut db, subscribe).unwrap().is_empty());
|
||||
let frames = session.poll(&mut db).unwrap();
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0]["price_changes"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(frames[0]["price_changes"][0]["asset_id"], "eb:YES:demo");
|
||||
assert!(session.poll(&mut db).unwrap().is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn newly_subscribed_asset_skips_prior_tick_but_existing_asset_receives_it() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
db.execute(json!({"op":"list","id":"m","market":"demo","rules":"r","tick_size":"0.01"}))
|
||||
.unwrap();
|
||||
let mut session = Session::default();
|
||||
session
|
||||
.control(&mut db, r#"{"type":"market","assets_ids":["eb:YES:demo"]}"#)
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"tick_size_change","id":"t","asset_id":"eb:YES:demo","new_tick_size":"0.001","timestamp":"1"})).unwrap();
|
||||
let snap = session
|
||||
.control(
|
||||
&mut db,
|
||||
r#"{"operation":"subscribe","assets_ids":["eb:NO:demo"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(snap[0]["tick_size"], "0.001");
|
||||
let batch = session.poll(&mut db).unwrap();
|
||||
assert_eq!(batch.len(), 1);
|
||||
assert_eq!(batch[0]["event_type"], "tick_size_change");
|
||||
assert_eq!(batch[0]["asset_id"], "eb:YES:demo");
|
||||
}
|
||||
#[test]
|
||||
fn opted_in_sessions_discover_new_listings_and_receive_one_final_result() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
let mut inputs = include_str!("../../../docs/examples/market-lifecycle.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap());
|
||||
db.execute(inputs.next().unwrap()).unwrap();
|
||||
let mut enabled = Session::default();
|
||||
let mut standard = Session::default();
|
||||
for (s, custom) in [(&mut enabled, true), (&mut standard, false)] {
|
||||
s.control(&mut db,&json!({"type":"market","assets_ids":["eb:YES:lobby"],"custom_feature_enabled":custom}).to_string()).unwrap();
|
||||
assert!(s.poll(&mut db).unwrap().is_empty());
|
||||
}
|
||||
db.execute(inputs.next().unwrap()).unwrap();
|
||||
let listing = inputs.next().unwrap();
|
||||
db.execute(listing.clone()).unwrap();
|
||||
db.execute(listing).unwrap();
|
||||
let news = enabled.poll(&mut db).unwrap();
|
||||
assert_eq!(news.len(), 1);
|
||||
assert_eq!(news[0]["event_type"], "new_market");
|
||||
assert_eq!(news[0]["slug"], "fixture-winner");
|
||||
assert_eq!(news[0]["question"], "Who wins the series?");
|
||||
assert_eq!(news[0]["outcomes"], json!(["Froglings", "1win"]));
|
||||
assert!(standard.poll(&mut db).unwrap().is_empty());
|
||||
for s in [&mut enabled, &mut standard] {
|
||||
s.control(
|
||||
&mut db,
|
||||
r#"{"operation":"subscribe","assets_ids":["eb:YES:match-1","eb:NO:match-1"]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
db.execute(inputs.next().unwrap()).unwrap();
|
||||
db.execute(inputs.next().unwrap()).unwrap();
|
||||
assert!(enabled.poll(&mut db).unwrap().is_empty());
|
||||
let resolve = inputs.next().unwrap();
|
||||
db.execute(resolve.clone()).unwrap();
|
||||
db.execute(resolve).unwrap();
|
||||
let result = enabled.poll(&mut db).unwrap();
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0]["event_type"], "market_resolved");
|
||||
assert_eq!(result[0]["id"], news[0]["id"]);
|
||||
assert_eq!(result[0]["winning_outcome"], "1win");
|
||||
assert_eq!(result[0]["winning_asset_id"], "eb:NO:match-1");
|
||||
assert!(standard.poll(&mut db).unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,12 @@ version.workspace = true
|
||||
matching = { path = "../matching" }
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_json = { workspace = true, features = ["arbitrary_precision"] }
|
||||
rusqlite.workspace = true
|
||||
data-encoding = "2"
|
||||
sha1 = "0.10"
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
+1126
-1
File diff suppressed because it is too large
Load Diff
@@ -44,7 +44,11 @@ impl Filter {
|
||||
let sql = format!(
|
||||
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
|
||||
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
|
||||
b.amount_cents,b.spent_cents FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
b.amount_cents,COALESCE((SELECT micros FROM budget_spend_micros WHERE order_seq=orders.seq),b.spent_cents*10000),
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq),s.order_type,s.post_only,s.created_at
|
||||
FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
LEFT JOIN order_submissions s ON s.order_seq=orders.seq
|
||||
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
|
||||
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
|
||||
);
|
||||
@@ -74,10 +78,12 @@ impl Filter {
|
||||
orders.push(
|
||||
json!({"order":id,"market":market,"asset_id":crate::assets::id(&market,&outcome),
|
||||
"outcome":outcome,"side":row.get::<_,String>(3)?,
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
|
||||
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
|
||||
"price_micros":row.get::<_,i64>(4)?*100,"original_size":crate::lots::display(quantity),
|
||||
"size_matched":crate::lots::display(quantity-remaining),"open_size":crate::lots::display(if status=="live"{remaining}else{0}),
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?}),
|
||||
"order_type":row.get::<_,Option<String>>(13)?,"post_only":row.get::<_,Option<bool>>(14)?,
|
||||
"created_at":row.get::<_,Option<i64>>(15)?,
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?.map(|v|crate::inventory::decimal(v.into(),10000)),"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
}
|
||||
|
||||
@@ -63,8 +63,8 @@ impl Filter {
|
||||
trades.push(
|
||||
json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
|
||||
"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?,
|
||||
"kind":r.get::<_,String>(5)?,"price_micros":price*10000,"size":size,
|
||||
"gross_cents":price*size,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"kind":r.get::<_,String>(5)?,"price_micros":price*100,"size":crate::lots::display(size),
|
||||
"gross_cents":crate::inventory::decimal(i128::from(price)*i128::from(size),10000),"fee_micros":r.get::<_,i64>(10)?,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"role":r.get::<_,Option<String>>(9)?}),
|
||||
);
|
||||
last = Some((execution, order));
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
WITH owned AS (
|
||||
SELECT seq FROM orders WHERE account=?1 AND (?2 IS NULL OR market=?2)
|
||||
AND (?3 IS NULL OR outcome=?3) AND (?4 IS NULL OR seq=?4)
|
||||
), legs(execution,order_seq,kind,price,quantity,at_ms) AS (
|
||||
SELECT f.seq,o.seq,'transfer',f.price,f.quantity,t.at_ms
|
||||
FROM owned o CROSS JOIN fills f ON f.bid=o.seq LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,'transfer',f.price,f.quantity,t.at_ms
|
||||
FROM owned o CROSS JOIN fills f ON f.ask=o.seq LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,f.kind,f.yes_price,f.quantity,f.at_ms
|
||||
FROM owned o CROSS JOIN paired_fills f ON f.yes_order=o.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,f.kind,100-f.yes_price,f.quantity,f.at_ms
|
||||
FROM owned o CROSS JOIN paired_fills f ON f.no_order=o.seq
|
||||
)
|
||||
SELECT l.execution,o.seq,o.market,o.outcome,o.side,l.kind,l.price,l.quantity,l.at_ms,
|
||||
SELECT l.execution,l.order_seq,l.market,l.outcome,l.side,l.kind,l.price,l.quantity,l.at_ms,
|
||||
CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction'
|
||||
WHEN c.taker_order=o.seq THEN 'taker' ELSE 'maker' END
|
||||
FROM legs l JOIN orders o ON o.seq=l.order_seq
|
||||
LEFT JOIN execution_context c ON c.execution=l.execution
|
||||
WHERE (l.execution,l.order_seq)<(?5,?6)
|
||||
WHEN c.taker_order=l.order_seq THEN 'taker' ELSE 'maker' END,
|
||||
COALESCE((SELECT fee_micros FROM execution_fees WHERE execution=l.execution AND taker_order=l.order_seq),0)
|
||||
FROM wallet_trade_legs l LEFT JOIN execution_context c ON c.execution=l.execution
|
||||
WHERE l.account=?1 AND (?2 IS NULL OR l.market=?2) AND (?3 IS NULL OR l.outcome=?3)
|
||||
AND (?4 IS NULL OR l.order_seq=?4) AND (l.execution,l.order_seq)<(?5,?6)
|
||||
ORDER BY l.execution DESC,l.order_seq DESC LIMIT ?7
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Kind {
|
||||
Trade,
|
||||
Split,
|
||||
Merge,
|
||||
Conversion,
|
||||
Redeem,
|
||||
Deposit,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Direction {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
types: Option<Vec<Kind>>,
|
||||
#[serde(default)]
|
||||
include_deposits: bool,
|
||||
from_ms: Option<i64>,
|
||||
to_ms: Option<i64>,
|
||||
direction: Option<Direction>,
|
||||
after: Option<Cursor>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize, Clone, Copy)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Cursor {
|
||||
asc: bool,
|
||||
key: (i64, i64, i64, i64),
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(m) = &self.market {
|
||||
identifier(m)?;
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!((1..=1000).contains(&limit), "invalid page size");
|
||||
ensure!(
|
||||
self.from_ms.unwrap_or(0) >= 0
|
||||
&& self.to_ms.unwrap_or(i64::MAX) >= self.from_ms.unwrap_or(0),
|
||||
"invalid time range"
|
||||
);
|
||||
let asc = match self.direction {
|
||||
Some(Direction::Asc) => true,
|
||||
Some(Direction::Desc) => false,
|
||||
None => self.after.is_some_and(|c| c.asc),
|
||||
};
|
||||
let bound = if asc { i64::MIN } else { i64::MAX };
|
||||
let cursor = self.after.unwrap_or(Cursor {
|
||||
asc,
|
||||
key: (bound, bound, bound, bound),
|
||||
});
|
||||
ensure!(cursor.asc == asc, "direction conflicts with cursor");
|
||||
let sql = include_str!("activity.sql")
|
||||
.replace("/*seek*/", if asc { ">" } else { "<" })
|
||||
.replace("/*dir*/", if asc { "ASC" } else { "DESC" });
|
||||
let types = self.types.as_ref().map(serde_json::to_string).transpose()?;
|
||||
let (time, source, seq, leg) = cursor.key;
|
||||
let mut stmt = db.prepare(&sql)?;
|
||||
let mut rows = stmt.query(params![
|
||||
self.account,
|
||||
self.market,
|
||||
types,
|
||||
self.include_deposits,
|
||||
self.from_ms,
|
||||
self.to_ms,
|
||||
time,
|
||||
source,
|
||||
seq,
|
||||
leg,
|
||||
limit + 1
|
||||
])?;
|
||||
let mut items = Vec::new();
|
||||
let mut last = None;
|
||||
let mut next = None;
|
||||
while let Some(r) = rows.next()? {
|
||||
if items.len() == limit as usize {
|
||||
next = last;
|
||||
break;
|
||||
}
|
||||
let source: i64 = r.get(1)?;
|
||||
let seq: i64 = r.get(2)?;
|
||||
let leg: i64 = r.get(3)?;
|
||||
let market: Option<String> = r.get(6)?;
|
||||
let outcome: Option<String> = r.get(11)?;
|
||||
let asset = market
|
||||
.as_deref()
|
||||
.zip(outcome.as_deref())
|
||||
.map(|(m, o)| assets::id(m, o));
|
||||
let fee: i64 = r.get(14)?;
|
||||
let cash: i64 = r.get(9)?;
|
||||
let precise_cash: Option<i64> = r.get(15)?;
|
||||
let gross = precise_cash.map_or(i128::from(cash) * 10000, i128::from);
|
||||
let shares = match r.get::<_, Option<i64>>(16)? {
|
||||
Some(u) => Some(crate::inventory::decimal(u.into(), crate::inventory::UNIT)),
|
||||
None => r.get::<_, Option<i64>>(8)?.map(Into::into),
|
||||
};
|
||||
let cash_cents = if r.get::<_, String>(5)? == "DEPOSIT" {
|
||||
cash.into()
|
||||
} else {
|
||||
crate::inventory::decimal(gross, 10000)
|
||||
};
|
||||
let mut item = json!({"type":r.get::<_,String>(5)?,"account":self.account,"at_ms":r.get::<_,Option<i64>>(4)?,
|
||||
"market":market,"group":r.get::<_,Option<String>>(7)?,"asset_id":asset,"outcome":outcome,
|
||||
"shares":shares,"cash_delta_cents":cash_cents,"fee_micros":fee,"net_cash_delta_micros":gross-i128::from(fee),
|
||||
"side":r.get::<_,Option<String>>(12)?,"price_micros":r.get::<_,Option<i64>>(13)?.map(|p|p*100),
|
||||
"request_id":r.get::<_,Option<String>>(10)?,"execution":(source==1).then_some(seq),"order":(source==1).then_some(leg)});
|
||||
if let Some(raw) = r.get::<_, Option<String>>(17)? {
|
||||
item["amounts_micros"] = serde_json::from_str(&raw)?;
|
||||
}
|
||||
items.push(item);
|
||||
last = Some(Cursor {
|
||||
asc,
|
||||
key: (r.get(0)?, source, seq, leg),
|
||||
});
|
||||
}
|
||||
Ok(json!({"activity":items,"next_after":next}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
WITH activity(source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,request_id,outcome,side,price) AS (
|
||||
SELECT 0,id,0,at_ms,kind,market,group_id,shares,cash_delta,request_id,NULL,NULL,NULL
|
||||
FROM wallet_movements WHERE account=?1
|
||||
UNION ALL
|
||||
SELECT 1,execution,order_seq,at_ms,'TRADE',market,NULL,quantity,
|
||||
quantity*price*CASE side WHEN 'buy' THEN -1 ELSE 1 END,NULL,outcome,side,price
|
||||
FROM wallet_trade_legs WHERE account=?1
|
||||
)
|
||||
SELECT COALESCE(at_ms,-1) AS ts,source,seq,leg,at_ms,kind,market,group_id,shares,cash_delta,request_id,outcome,side,price,
|
||||
COALESCE((SELECT fee_micros FROM execution_fees WHERE source=1 AND execution=seq AND taker_order=leg),0),
|
||||
CASE WHEN source=1 THEN cash_delta WHEN kind='DEPOSIT' THEN (SELECT json_extract(response,'$.funded_micros')
|
||||
FROM requests WHERE id=activity.request_id) ELSE
|
||||
(SELECT cash_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
|
||||
CASE WHEN source=1 THEN shares*10000 ELSE (SELECT shares_micros FROM precise_movements WHERE request_id=activity.request_id AND account=?1) END,
|
||||
CASE WHEN kind='REDEEM' THEN (SELECT json_extract(response,'$.amounts_micros')
|
||||
FROM requests WHERE id=activity.request_id) END
|
||||
FROM activity
|
||||
WHERE (?2 IS NULL OR market=?2)
|
||||
AND (?3 IS NULL OR kind IN (SELECT value FROM json_each(?3)))
|
||||
AND (?4 OR kind<>'DEPOSIT')
|
||||
AND (?5 IS NULL OR at_ms>=?5) AND (?6 IS NULL OR at_ms<=?6)
|
||||
AND (COALESCE(at_ms,-1),source,seq,leg) /*seek*/ (?7,?8,?9,?10)
|
||||
ORDER BY ts /*dir*/,source /*dir*/,seq /*dir*/,leg /*dir*/ LIMIT ?11
|
||||
@@ -0,0 +1,37 @@
|
||||
-- Runs once per database for the receipt backfill. Creating the trigger and
|
||||
-- importing under the same write lock covers writers opening concurrently.
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS wallet_movements (
|
||||
id INTEGER PRIMARY KEY, request_id TEXT NOT NULL REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
account TEXT NOT NULL, kind TEXT NOT NULL, market TEXT, group_id TEXT,
|
||||
shares INTEGER, cash_delta INTEGER NOT NULL, at_ms INTEGER, UNIQUE(request_id,account)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS activity_by_account ON wallet_movements(account,at_ms,id);
|
||||
DROP TRIGGER IF EXISTS record_receipt_movement;
|
||||
DROP VIEW IF EXISTS receipt_movements;
|
||||
CREATE VIEW receipt_movements AS
|
||||
SELECT id AS request_id,json_extract(payload,'$.account') AS account,
|
||||
CASE json_extract(payload,'$.op') WHEN 'fund' THEN 'DEPOSIT' WHEN 'convert' THEN 'CONVERSION'
|
||||
ELSE upper(json_extract(payload,'$.op')) END AS kind,
|
||||
json_extract(payload,'$.market') AS market,json_extract(payload,'$.group') AS group_id,
|
||||
json_extract(payload,'$.qty') AS shares,
|
||||
CASE json_extract(payload,'$.op') WHEN 'fund' THEN json_extract(response,'$.funded')
|
||||
WHEN 'split' THEN -100*json_extract(response,'$.pairs')
|
||||
WHEN 'redeem' THEN json_extract(response,'$.paid')
|
||||
ELSE json_extract(response,'$.released_cents') END AS cash_delta
|
||||
FROM requests WHERE json_extract(payload,'$.op') IN ('fund','split','merge','redeem','convert')
|
||||
AND COALESCE(json_extract(response,'$.noop'),0)=0;
|
||||
CREATE TRIGGER IF NOT EXISTS record_wallet_receipt AFTER INSERT ON requests
|
||||
WHEN json_extract(NEW.payload,'$.op') IN ('fund','split','merge','redeem','convert')
|
||||
BEGIN
|
||||
INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta,at_ms)
|
||||
SELECT r.*,CAST(unixepoch('subsec')*1000 AS INTEGER) FROM receipt_movements r WHERE request_id=NEW.id
|
||||
ON CONFLICT(request_id,account) DO NOTHING;
|
||||
END;
|
||||
CREATE TABLE IF NOT EXISTS wallet_migration(version INTEGER PRIMARY KEY);
|
||||
INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta)
|
||||
SELECT r.* FROM receipt_movements r WHERE NOT EXISTS (SELECT 1 FROM wallet_migration WHERE version=1)
|
||||
ORDER BY r.request_id ON CONFLICT(request_id,account) DO NOTHING;
|
||||
INSERT OR IGNORE INTO wallet_migration VALUES(1);
|
||||
|
||||
COMMIT;
|
||||
@@ -9,6 +9,16 @@ pub(crate) fn id(market: &str, outcome: &str) -> String {
|
||||
format!("eb:{outcome}:{market}")
|
||||
}
|
||||
|
||||
pub fn parse_id(asset: &str) -> Result<(&str, &str)> {
|
||||
let (outcome, market) = asset
|
||||
.strip_prefix("eb:")
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
Ok((outcome, market))
|
||||
}
|
||||
|
||||
pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
|
||||
json!([
|
||||
{"outcome":"YES","label":yes,"asset_id":id(market,"YES")},
|
||||
@@ -18,14 +28,28 @@ pub(crate) fn outcomes(market: &str, yes: &str, no: &str) -> Value {
|
||||
|
||||
pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
identifier(market)?;
|
||||
let (yes, no, phase): (String, String, String) = db.query_row(
|
||||
"SELECT COALESCE(s.yes_label,g.yes_label,CASE WHEN t.market IS NULL THEN 'YES' ELSE 'Up' END),
|
||||
COALESCE(s.no_label,g.no_label,CASE WHEN t.market IS NULL THEN 'NO' ELSE 'Down' END),m.phase
|
||||
FROM markets m LEFT JOIN sports_markets s ON s.market=m.id LEFT JOIN topic_markets g ON g.market=m.id LEFT JOIN twap_markets t ON t.market=m.id WHERE m.id=?1",
|
||||
let mut detail = db.query_row(
|
||||
"SELECT w.yes_label,w.no_label,m.phase,a.role,a.name,w.id,w.slug,w.question
|
||||
FROM market_wire_metadata w JOIN markets m ON m.id=w.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=w.market WHERE w.market=?1",
|
||||
[market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
|r| {
|
||||
let yes:String=r.get(0)?;
|
||||
let no:String=r.get(1)?;
|
||||
let mut detail=json!({"market":market,"id":r.get::<_,String>(5)?,"slug":r.get::<_,String>(6)?,"question":r.get::<_,String>(7)?,"phase":r.get::<_,String>(2)?,"outcomes":outcomes(market,&yes,&no)});
|
||||
if let Some(role)=r.get::<_,Option<String>>(3)? {
|
||||
detail["augmented_role"]=json!(role);
|
||||
detail["outcome_name"]=json!(r.get::<_,Option<String>>(4)?);
|
||||
}
|
||||
Ok(detail)
|
||||
},
|
||||
)?;
|
||||
Ok(json!({"market":market,"phase":phase,"outcomes":outcomes(market,&yes,&no)}))
|
||||
detail["tick_size"] =
|
||||
json!(crate::tick_size::TickSize::load(db, market)?.map(|tick| tick.text()));
|
||||
detail["min_order_size"] =
|
||||
json!(crate::minimum_size::MinimumSize::load(db, market)?.map(|size| size.text()));
|
||||
detail["taker_fee_rate_ppm"] = json!(crate::fees::rate(db, market)?);
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
// Resolve only commands that address one outcome. Keep the original request
|
||||
@@ -37,11 +61,17 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
"order"
|
||||
| "book"
|
||||
| "quote"
|
||||
| "quote_history"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
| "open_orders"
|
||||
| "trades"
|
||||
| "market_sell"
|
||||
| "estimate"
|
||||
| "limit_amounts"
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "tick_size_change"
|
||||
| "market_buy"
|
||||
| "cancel_market_orders"
|
||||
)
|
||||
@@ -52,13 +82,7 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
let Some(asset) = fields.remove("asset_id") else {
|
||||
return Ok(());
|
||||
};
|
||||
let (outcome, market) = asset
|
||||
.as_str()
|
||||
.and_then(|s| s.strip_prefix("eb:"))
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.context("invalid Eventbook asset_id")?;
|
||||
ensure!(matches!(outcome, "YES" | "NO"), "invalid asset outcome");
|
||||
identifier(market)?;
|
||||
let (outcome, market) = parse_id(asset.as_str().context("invalid Eventbook asset_id")?)?;
|
||||
for (field, value) in [("market", market), ("outcome", outcome)] {
|
||||
if let Some(existing) = fields.get(field) {
|
||||
ensure!(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Config {
|
||||
other: String,
|
||||
placeholders: Vec<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub(crate) fn save(&self, tx: &Transaction, group: &str, markets: &[String]) -> Result<()> {
|
||||
let slots: BTreeSet<_> = self.placeholders.iter().collect();
|
||||
ensure!(
|
||||
!slots.is_empty()
|
||||
&& slots.len() == self.placeholders.len()
|
||||
&& slots.len() + 1 < markets.len()
|
||||
&& markets.contains(&self.other)
|
||||
&& !slots.contains(&self.other)
|
||||
&& slots.iter().all(|m| markets.contains(*m)),
|
||||
"expected named members, distinct placeholders and one Other"
|
||||
);
|
||||
for market in markets {
|
||||
let role = if market == &self.other {
|
||||
"other"
|
||||
} else if slots.contains(market) {
|
||||
"placeholder"
|
||||
} else {
|
||||
"named"
|
||||
};
|
||||
let label: String = tx.query_row(
|
||||
"SELECT COALESCE(group_title,question) FROM listed_markets WHERE market=?",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let name = (role != "placeholder").then(|| label.trim());
|
||||
tx.execute(
|
||||
"INSERT INTO augmented_outcomes(market,group_id,role,name) VALUES(?,?,?,?)",
|
||||
params![market, group, role, name],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn clarify(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
name: &str,
|
||||
question: &str,
|
||||
evidence: &str,
|
||||
) -> Result<Value> {
|
||||
let name = name.trim();
|
||||
ensure!(
|
||||
!name.is_empty() && !question.trim().is_empty() && !evidence.trim().is_empty(),
|
||||
"name, question and evidence required"
|
||||
);
|
||||
let changed = tx.execute(
|
||||
"UPDATE augmented_outcomes SET name=?2,question=?3,clarification=?4,named_at=unixepoch(),role='named'
|
||||
WHERE market=?1 AND role='placeholder' AND EXISTS
|
||||
(SELECT 1 FROM markets WHERE id=?1 AND phase IN ('preopen','continuous'))",
|
||||
params![market,name,question,evidence])?;
|
||||
ensure!(changed == 1, "expected an open, unnamed placeholder");
|
||||
Ok(json!({"market":market,"name":name}))
|
||||
}
|
||||
|
||||
// The operator supplies the observed winner and source. The exchange selects
|
||||
// the named member or the group's explicit residual outcome in one transaction.
|
||||
pub(crate) fn finalize(
|
||||
tx: &Transaction,
|
||||
group: &str,
|
||||
observed: &str,
|
||||
evidence: &str,
|
||||
) -> Result<Value> {
|
||||
let observed = observed.trim();
|
||||
ensure!(
|
||||
!observed.is_empty() && !evidence.trim().is_empty(),
|
||||
"observed winner and evidence required"
|
||||
);
|
||||
let winner: String = tx.query_row(
|
||||
"SELECT market FROM augmented_outcomes WHERE group_id=?1 AND (role='other' OR (role='named' AND name=?2))
|
||||
ORDER BY CASE role WHEN 'named' THEN 0 ELSE 1 END LIMIT 1",
|
||||
params![group,observed],|r|r.get(0))?;
|
||||
tx.execute(
|
||||
"INSERT INTO augmented_results(group_id,observed_name,winner,evidence) VALUES(?,?,?,?)",
|
||||
params![group, observed, winner, evidence],
|
||||
)?;
|
||||
let mut stmt =
|
||||
tx.prepare("SELECT market FROM neg_risk_members WHERE group_id=? ORDER BY ordinal")?;
|
||||
let markets = stmt
|
||||
.query_map([group], |r| r.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for market in markets {
|
||||
crate::market::finalize(tx, &market, if market == winner { "YES" } else { "NO" })?;
|
||||
}
|
||||
Ok(json!({"group":group,"observed_name":observed,"winner":winner,"evidence":evidence}))
|
||||
}
|
||||
+137
-40
@@ -11,6 +11,7 @@ use serde_json::{json, Value};
|
||||
pub(crate) struct NewOrder {
|
||||
pub market: String,
|
||||
pub account: String,
|
||||
pub key_id: Option<String>,
|
||||
pub outcome: String,
|
||||
pub side: String,
|
||||
pub price: i64,
|
||||
@@ -24,22 +25,49 @@ pub(crate) struct ShareExecution {
|
||||
pub seq: i64,
|
||||
pub filled: i64,
|
||||
pub status: String,
|
||||
pub gross_cents: i64,
|
||||
pub gross_micros: i64,
|
||||
pub fee_micros: i64,
|
||||
}
|
||||
impl ShareExecution {
|
||||
pub fn receipt(&self) -> Value {
|
||||
json!({"order":self.seq,"filled":self.filled,"status":self.status})
|
||||
let mut receipt = json!({"order":self.seq,"filled":crate::lots::display(self.filled),"status":self.status});
|
||||
if self.fee_micros > 0 {
|
||||
receipt["fee_micros"] = json!(self.fee_micros);
|
||||
}
|
||||
receipt
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn gross_cents(fills: &[Fill]) -> i64 {
|
||||
pub(crate) fn gross_micros(fills: &[Fill]) -> i64 {
|
||||
fills.iter().map(|f| f.price * f.quantity).sum()
|
||||
}
|
||||
|
||||
fn record_submission(
|
||||
tx: &Transaction,
|
||||
seq: i64,
|
||||
tif: TimeInForce,
|
||||
post_only: bool,
|
||||
key: Option<&str>,
|
||||
) -> Result<()> {
|
||||
let order_type = match tif {
|
||||
TimeInForce::Gtc => "GTC",
|
||||
TimeInForce::Gtd => "GTD",
|
||||
TimeInForce::Ioc => "IOC",
|
||||
TimeInForce::Fok => "FOK",
|
||||
TimeInForce::Fak => "FAK",
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO order_submissions(order_seq,order_type,post_only) VALUES(?,?,?)",
|
||||
params![seq, order_type, post_only],
|
||||
)?;
|
||||
crate::heartbeat::record_key(tx, seq, key)
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<ShareExecution> {
|
||||
let NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
@@ -49,13 +77,19 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
post_only,
|
||||
} = order;
|
||||
identifier(&account)?;
|
||||
amount(qty)?;
|
||||
ensure!(
|
||||
(1..=100_000_000_000).contains(&qty),
|
||||
"invalid order quantity"
|
||||
);
|
||||
let stage = phase(tx, &market, &["preopen", "continuous"])?;
|
||||
ensure!(
|
||||
matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"),
|
||||
"invalid instrument or side"
|
||||
);
|
||||
ensure!((0..=100).contains(&price), "invalid price");
|
||||
ensure!(
|
||||
(0..=crate::tick_size::PAR).contains(&price),
|
||||
"invalid price"
|
||||
);
|
||||
ensure!(
|
||||
tif == TimeInForce::Gtc || stage == "continuous",
|
||||
"unsupported time in force"
|
||||
@@ -64,6 +98,13 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
!post_only || (stage == "continuous" && matches!(tif, TimeInForce::Gtc | TimeInForce::Gtd)),
|
||||
"post-only requires continuous GTC or GTD"
|
||||
);
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_microshares(qty * crate::lots::MICROS)?;
|
||||
}
|
||||
crate::tick_size::validate(
|
||||
crate::tick_size::TickSize::load(tx, &market)?.as_ref(),
|
||||
price,
|
||||
)?;
|
||||
let deadline = match tif {
|
||||
TimeInForce::Gtd => {
|
||||
let expiration =
|
||||
@@ -81,12 +122,13 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
}
|
||||
};
|
||||
if side == "buy" {
|
||||
ledger::cash(tx, &account, -price * qty)?;
|
||||
ledger::cash_micros(tx, &account, -price * qty)?;
|
||||
} else {
|
||||
ledger::position(tx, &account, &market, &outcome, -qty)?;
|
||||
crate::inventory::position(tx, &account, &market, &outcome, -qty * crate::lots::MICROS)?;
|
||||
}
|
||||
tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
record_submission(tx, seq, tif, post_only, key_id.as_deref())?;
|
||||
if let Some(deadline) = deadline {
|
||||
tx.execute(
|
||||
"INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)",
|
||||
@@ -94,6 +136,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
)?;
|
||||
}
|
||||
let mut gross = 0;
|
||||
let mut fee_micros = 0;
|
||||
if stage == "continuous" {
|
||||
let incoming = Order {
|
||||
seq,
|
||||
@@ -119,8 +162,8 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
tif != TimeInForce::Fak || !fills.is_empty(),
|
||||
"FAK has no matching liquidity"
|
||||
);
|
||||
gross = gross_cents(&fills);
|
||||
settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
|
||||
gross = gross_micros(&fills);
|
||||
fee_micros = settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
|
||||
}
|
||||
let (remaining, mut status): (i64, String) = tx.query_row(
|
||||
"SELECT remaining,status FROM orders WHERE seq=?",
|
||||
@@ -131,11 +174,15 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
release(tx, seq, &account, CancelReason::Cancelled)?;
|
||||
status = "cancelled".into();
|
||||
}
|
||||
if fee_micros > 0 {
|
||||
ledger::cash_micros(tx, &account, -fee_micros)?;
|
||||
}
|
||||
Ok(ShareExecution {
|
||||
fee_micros,
|
||||
seq,
|
||||
filled: qty - remaining,
|
||||
status,
|
||||
gross_cents: gross,
|
||||
gross_micros: gross,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -143,13 +190,15 @@ pub(crate) struct BudgetBuy {
|
||||
pub market: String,
|
||||
pub outcome: String,
|
||||
pub account: String,
|
||||
pub key_id: Option<String>,
|
||||
pub amount_cents: i64,
|
||||
pub max_price: i64,
|
||||
pub max_price: Option<i64>,
|
||||
pub tif: TimeInForce,
|
||||
}
|
||||
|
||||
pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> Result<Value> {
|
||||
let BudgetBuy {
|
||||
key_id,
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
@@ -160,14 +209,27 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
identifier(&account)?;
|
||||
amount(amount_cents)?;
|
||||
phase(tx, &market, &["continuous"])?;
|
||||
ensure!(
|
||||
matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&max_price),
|
||||
"invalid outcome or price"
|
||||
);
|
||||
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
|
||||
ensure!(
|
||||
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
|
||||
"market buy requires FAK or FOK"
|
||||
);
|
||||
let max_price = books
|
||||
.protection_price(&market, &outcome, Side::Buy, amount_cents, max_price, tif)
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("insufficient opposing depth for market buy protection price")
|
||||
})?;
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
minimum.check_budget(amount_cents, max_price, rate)?;
|
||||
}
|
||||
let tick = crate::tick_size::TickSize::load(tx, &market)?;
|
||||
let amounts = crate::market_amounts::Amounts::for_order(
|
||||
tick.as_ref(),
|
||||
Side::Buy,
|
||||
amount_cents,
|
||||
max_price,
|
||||
)?;
|
||||
ledger::cash(tx, &account, -amount_cents)?;
|
||||
tx.execute(
|
||||
"INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status)
|
||||
@@ -175,16 +237,19 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
params![account, market, outcome, max_price],
|
||||
)?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
let fills = books
|
||||
record_submission(tx, seq, tif, false, key_id.as_deref())?;
|
||||
let mut fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| b.match_budget_buy(seq, max_price, amount_cents))
|
||||
.map(|b| b.match_budget_buy(seq, max_price, amount_cents * 10000))
|
||||
.unwrap_or_default();
|
||||
crate::fees::fit_budget(rate, &mut fills, amount_cents);
|
||||
ensure!(!fills.is_empty(), "no affordable liquidity");
|
||||
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
let spent = gross_cents(&fills);
|
||||
let unspent = amount_cents - spent;
|
||||
let spent = gross_micros(&fills);
|
||||
let gross_remainder = amount_cents * 10000 - spent;
|
||||
let unspent_micros = gross_remainder - crate::fees::total(rate, &fills);
|
||||
ensure!(
|
||||
tif != TimeInForce::Fok || unspent == 0,
|
||||
tif != TimeInForce::Fok || unspent_micros == 0,
|
||||
"FOK cannot fill the entire cash amount"
|
||||
);
|
||||
tx.execute(
|
||||
@@ -193,19 +258,31 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO budget_buys(order_seq,amount_cents,spent_cents) VALUES(?,?,?)",
|
||||
params![seq, amount_cents, spent],
|
||||
params![seq, amount_cents, spent / 10000],
|
||||
)?;
|
||||
settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
|
||||
ledger::cash(tx, &account, unspent)?;
|
||||
let status = if unspent == 0 {
|
||||
tx.execute(
|
||||
"INSERT INTO budget_spend_micros VALUES(?,?)",
|
||||
params![seq, spent],
|
||||
)?;
|
||||
let fee = settle(tx, &market, &outcome, fills, Some(Taker::Budget(seq)))?;
|
||||
ledger::cash_micros(tx, &account, gross_remainder - fee)?;
|
||||
let status = if unspent_micros == 0 {
|
||||
"filled"
|
||||
} else {
|
||||
tx.execute("UPDATE orders SET status='cancelled' WHERE seq=?", [seq])?;
|
||||
"cancelled"
|
||||
};
|
||||
Ok(
|
||||
json!({"order":seq,"status":status,"filled":quantity,"amount_cents":amount_cents,"spent_cents":spent,"unspent_cents":unspent}),
|
||||
)
|
||||
let mut receipt = json!({"order":seq,"status":status,"filled":crate::lots::display(quantity),"amount_cents":amount_cents,"spent_cents":crate::inventory::decimal(spent.into(),10000),"unspent_cents":crate::inventory::decimal(unspent_micros.into(),10000)});
|
||||
if let Some(amounts) = amounts {
|
||||
receipt["order_amounts"] = amounts.json();
|
||||
}
|
||||
receipt["protection_price_micros"] = json!(max_price * crate::tick_size::PRICE_MICROS);
|
||||
if fee > 0 || spent % 10000 != 0 {
|
||||
receipt["fee_micros"] = json!(fee);
|
||||
receipt["unspent_micros"] = json!(unspent_micros);
|
||||
receipt["total_spent_micros"] = json!(spent + fee);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
@@ -245,17 +322,25 @@ fn book_leg(
|
||||
let price = if outcome == view {
|
||||
fill.price
|
||||
} else {
|
||||
100 - fill.price
|
||||
crate::tick_size::PAR - fill.price
|
||||
};
|
||||
if side == "buy" {
|
||||
ensure!(price <= limit, "buy limit exceeded");
|
||||
if taker != Some(Taker::Budget(seq)) {
|
||||
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
|
||||
ledger::cash_micros(tx, &account, (limit - price) * fill.quantity)?;
|
||||
}
|
||||
ledger::position(tx, &account, market, &outcome, fill.quantity)?;
|
||||
crate::inventory::position(
|
||||
tx,
|
||||
&account,
|
||||
market,
|
||||
&outcome,
|
||||
fill.quantity
|
||||
.checked_mul(crate::lots::MICROS)
|
||||
.ok_or_else(|| anyhow::anyhow!("fill exceeds ledger range"))?,
|
||||
)?;
|
||||
} else {
|
||||
ensure!(price >= limit, "sell limit exceeded");
|
||||
ledger::cash(tx, &account, price * fill.quantity)?;
|
||||
ledger::cash_micros(tx, &account, price * fill.quantity)?;
|
||||
}
|
||||
Ok(ExecutedLeg {
|
||||
seq,
|
||||
@@ -271,7 +356,13 @@ pub(crate) fn settle(
|
||||
outcome: &str,
|
||||
fills: Vec<Fill>,
|
||||
taker: Option<Taker>,
|
||||
) -> Result<()> {
|
||||
) -> Result<i64> {
|
||||
let rate = if taker.is_some() && !fills.is_empty() {
|
||||
crate::fees::rate(tx, market)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let mut fees = 0;
|
||||
for f in fills {
|
||||
let first = book_leg(tx, market, outcome, &f, f.bid, taker)?;
|
||||
let second = book_leg(tx, market, outcome, &f, f.ask, taker)?;
|
||||
@@ -287,11 +378,7 @@ pub(crate) fn settle(
|
||||
} else {
|
||||
ensure!(first.side == second.side, "invalid complementary legs");
|
||||
let mint = first.side == "buy";
|
||||
let delta = if mint {
|
||||
100 * f.quantity
|
||||
} else {
|
||||
-100 * f.quantity
|
||||
};
|
||||
let delta = if mint { f.quantity } else { -f.quantity };
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2 AND collateral+?1>=0",
|
||||
@@ -322,11 +409,21 @@ pub(crate) fn settle(
|
||||
"INSERT INTO execution_context(execution,taker_order) VALUES(?,?)",
|
||||
params![execution, taker.map(Taker::seq)],
|
||||
)?;
|
||||
if let Some(taker) = taker {
|
||||
let fee = crate::fees::lot_fee(rate, f.price * 100, f.quantity);
|
||||
if fee > 0 {
|
||||
tx.execute(
|
||||
"INSERT INTO execution_fees VALUES(?,?,?)",
|
||||
params![execution, taker.seq(), fee],
|
||||
)?;
|
||||
fees += fee;
|
||||
}
|
||||
}
|
||||
for seq in [f.bid, f.ask] {
|
||||
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
Ok(fees)
|
||||
}
|
||||
|
||||
pub(crate) enum CancelReason {
|
||||
@@ -342,9 +439,9 @@ pub(crate) fn release(
|
||||
) -> Result<i64> {
|
||||
let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
||||
if side == "buy" {
|
||||
ledger::cash(tx, owner, price * qty)?;
|
||||
ledger::cash_micros(tx, owner, price * qty)?;
|
||||
} else {
|
||||
ledger::position(tx, owner, &market, &outcome, qty)?;
|
||||
crate::inventory::position(tx, owner, &market, &outcome, qty * crate::lots::MICROS)?;
|
||||
}
|
||||
let status = match reason {
|
||||
CancelReason::Cancelled => "cancelled",
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::decimal,
|
||||
lots,
|
||||
minimum_size::MinimumSize,
|
||||
quotes::Quote,
|
||||
resident::Books,
|
||||
tick_size::{TickSize, PAR},
|
||||
};
|
||||
use anyhow::{Context, Result};
|
||||
use matching::Side;
|
||||
use rusqlite::{OptionalExtension, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha1::{Digest, Sha1};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Level {
|
||||
price: String,
|
||||
size: String,
|
||||
}
|
||||
|
||||
// Field order is part of the official SDK's SHA-1 preimage.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Snapshot {
|
||||
market: String,
|
||||
asset_id: String,
|
||||
timestamp: String,
|
||||
hash: String,
|
||||
bids: Vec<Level>,
|
||||
asks: Vec<Level>,
|
||||
min_order_size: String,
|
||||
tick_size: String,
|
||||
neg_risk: bool,
|
||||
last_trade_price: String,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
fn set_hash(&mut self) -> Result<()> {
|
||||
self.hash.clear();
|
||||
self.hash = format!("{:x}", Sha1::digest(serde_json::to_vec(self)?));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn build(tx: &Transaction, books: &Books, token: &str) -> Result<Snapshot> {
|
||||
let (outcome, market) = assets::parse_id(token)?;
|
||||
find(tx, books, token, outcome, market)?
|
||||
.context("No orderbook exists for the requested token id")
|
||||
}
|
||||
|
||||
fn find(
|
||||
tx: &Transaction,
|
||||
books: &Books,
|
||||
token: &str,
|
||||
outcome: &str,
|
||||
market: &str,
|
||||
) -> Result<Option<Snapshot>> {
|
||||
let row: Option<(i64, bool)> = tx
|
||||
.query_row(
|
||||
"SELECT at_ms,EXISTS(SELECT 1 FROM neg_risk_members WHERE market=?1)
|
||||
FROM book_snapshot_times WHERE market=?1",
|
||||
[market],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
let Some((at_ms, neg_risk)) = row else {
|
||||
return Ok(None);
|
||||
};
|
||||
let book = books.get(market, outcome);
|
||||
let levels = |taker| {
|
||||
let mut result = Vec::new();
|
||||
if let Some(book) = book {
|
||||
for (price, size) in book.opposing_levels(taker) {
|
||||
result.push(Level {
|
||||
price: decimal(price.into(), PAR).to_string(),
|
||||
size: decimal(size, lots::PER_SHARE).to_string(),
|
||||
});
|
||||
}
|
||||
result.reverse(); // The reference client walks from the end of each side.
|
||||
}
|
||||
result
|
||||
};
|
||||
let mut snapshot = Snapshot {
|
||||
market: market.into(),
|
||||
asset_id: token.into(),
|
||||
timestamp: at_ms.to_string(),
|
||||
hash: String::new(),
|
||||
bids: levels(Side::Sell),
|
||||
asks: levels(Side::Buy),
|
||||
min_order_size: MinimumSize::load(tx, market)?
|
||||
.map(|s| s.text())
|
||||
.unwrap_or_else(|| MinimumSize::format_microshares(lots::MICROS)),
|
||||
tick_size: TickSize::load(tx, market)?
|
||||
.unwrap_or(TickSize::WHOLE_CENT)
|
||||
.text(),
|
||||
neg_risk,
|
||||
last_trade_price: Quote::current(tx, market, outcome)?
|
||||
.last
|
||||
.map(|p| decimal(p.into(), PAR).to_string())
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
snapshot.set_hash()?;
|
||||
Ok(Some(snapshot))
|
||||
}
|
||||
|
||||
pub(crate) fn read_many(
|
||||
tx: &Transaction,
|
||||
books: &mut Books,
|
||||
tokens: &[String],
|
||||
) -> Result<Vec<Value>> {
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
let mut result = Vec::with_capacity(tokens.len());
|
||||
for token in tokens {
|
||||
if let Ok((outcome, market)) = assets::parse_id(token) {
|
||||
if let Some(book) = find(tx, books, token, outcome, market)? {
|
||||
result.push(serde_json::to_value(book)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub(crate) fn read(tx: &Transaction, books: &mut Books, token: &str) -> Result<Value> {
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
Ok(serde_json::to_value(build(tx, books, token)?)?)
|
||||
}
|
||||
|
||||
pub(crate) fn event(tx: &Transaction, books: &Books, token: &str, raw: bool) -> Result<Value> {
|
||||
let s = build(tx, books, token)?;
|
||||
if raw {
|
||||
let mut frame = serde_json::to_value(s)?;
|
||||
frame["event_type"] = json!("book");
|
||||
return Ok(frame);
|
||||
}
|
||||
let stamp: String = tx.query_row(
|
||||
"SELECT strftime('%Y-%m-%dT%H:%M:%f000Z',?1/1000.0,'unixepoch')",
|
||||
[&s.timestamp],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let last_trade = (!s.last_trade_price.is_empty()).then_some(s.last_trade_price);
|
||||
Ok(json!({"topic":"market","type":"book","payload":{
|
||||
"condition_id":s.market,"asset_id":s.asset_id,"timestamp":stamp,"bids":s.bids,"asks":s.asks,
|
||||
"hash":s.hash,"min_order_size":s.min_order_size,"tick_size":s.tick_size,"neg_risk":s.neg_risk,
|
||||
"last_trade_price":last_trade
|
||||
}}))
|
||||
}
|
||||
|
||||
pub(crate) fn local_levels(books: &Books, market: &str, outcome: &str, taker: Side) -> Vec<Value> {
|
||||
let Some(book) = books.get(market, outcome) else {
|
||||
return Vec::new();
|
||||
};
|
||||
book.opposing_levels(taker)
|
||||
.map(|(price, size)| {
|
||||
json!({
|
||||
"price_micros": price * crate::tick_size::PRICE_MICROS,
|
||||
"size": decimal(size, lots::PER_SHARE),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reproduces_pinned_python_sdk_hash_vector() {
|
||||
let mut sample: Snapshot = serde_json::from_value(json!({
|
||||
"market":"0xaabbcc","asset_id":"100","timestamp":"123456789","hash":"prior",
|
||||
"bids":[{"price":"0.3","size":"100"},{"price":"0.4","size":"100"}],
|
||||
"asks":[{"price":"0.6","size":"100"},{"price":"0.7","size":"100"}],
|
||||
"min_order_size":"100","tick_size":"0.01","neg_risk":false,"last_trade_price":"0.5"
|
||||
}))
|
||||
.unwrap();
|
||||
sample.set_hash().unwrap();
|
||||
assert_eq!(sample.hash, "0458ea5755c9f73d64a14636fa5c36ed460ec394");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS book_snapshot_times (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), at_ms INTEGER NOT NULL
|
||||
);
|
||||
-- History before this schema has no reliable timestamp for a depth-only edit.
|
||||
INSERT OR IGNORE INTO book_snapshot_times SELECT id,CAST(unixepoch('subsec')*1000 AS INTEGER) FROM markets;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_listed AFTER INSERT ON markets BEGIN
|
||||
INSERT INTO book_snapshot_times VALUES(NEW.id,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_order_added AFTER INSERT ON orders
|
||||
WHEN NEW.status='live' AND NEW.remaining>0 BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_order_changed AFTER UPDATE OF status,remaining ON orders
|
||||
WHEN (NEW.status='live' OR OLD.status='live') AND (OLD.remaining<>NEW.remaining OR OLD.status<>NEW.status) BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_grid_changed AFTER INSERT ON tick_changes BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS snapshot_group_joined AFTER INSERT ON neg_risk_members BEGIN
|
||||
UPDATE book_snapshot_times SET at_ms=MAX(at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)) WHERE market=NEW.market;
|
||||
END;
|
||||
COMMIT;
|
||||
+119
-56
@@ -1,6 +1,6 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) enum Event {
|
||||
}
|
||||
impl Event {
|
||||
pub fn save(self, tx: &Transaction) -> Result<Value> {
|
||||
match self {
|
||||
let event = match self {
|
||||
Self::Sport {
|
||||
event,
|
||||
title,
|
||||
@@ -56,7 +56,7 @@ impl Event {
|
||||
scheduled_at_ms
|
||||
],
|
||||
)?;
|
||||
Ok(json!({"event":event}))
|
||||
event
|
||||
}
|
||||
Self::Topic {
|
||||
event,
|
||||
@@ -74,9 +74,15 @@ impl Event {
|
||||
"INSERT INTO topics(id,slug,title,category) VALUES(?,?,?,?)",
|
||||
params![event, slug, title, category],
|
||||
)?;
|
||||
Ok(json!({"event":event}))
|
||||
event
|
||||
}
|
||||
}
|
||||
};
|
||||
let event_id: i64 = tx.query_row(
|
||||
"SELECT id FROM event_directory_ids WHERE event=?",
|
||||
[&event],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(json!({"event":event,"event_id":event_id}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -235,6 +241,19 @@ impl Listing {
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
LimitAmounts(crate::tick_size::LimitAmounts),
|
||||
MarketAmounts(crate::market_amounts::Request),
|
||||
TickHistory(crate::tick_changes::History),
|
||||
PricesHistory(crate::prices_history::Request),
|
||||
QuoteHistory(crate::quotes::Filter),
|
||||
Price(crate::quotes::PriceRequest),
|
||||
Prices {
|
||||
requests: Vec<crate::quotes::PriceRequest>,
|
||||
},
|
||||
Volume {
|
||||
event: Option<String>,
|
||||
market: Option<String>,
|
||||
},
|
||||
Resolution {
|
||||
market: String,
|
||||
},
|
||||
@@ -242,8 +261,22 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
OpenInterest(crate::open_interest::Request),
|
||||
Holders(crate::holders::Request),
|
||||
Balance {
|
||||
account: String,
|
||||
},
|
||||
PortfolioValue {
|
||||
account: String,
|
||||
},
|
||||
Activity(crate::activity::Filter),
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
Trades(crate::account_trades::Filter),
|
||||
PublicTrades(crate::public_trades::Request),
|
||||
BookFeed(crate::depth_feed::Request),
|
||||
ClobBook {
|
||||
token_id: String,
|
||||
},
|
||||
Book {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -274,61 +307,72 @@ pub(crate) enum Query {
|
||||
impl Query {
|
||||
pub fn read(self, db: &Transaction, books: &mut crate::resident::Books) -> Result<Value> {
|
||||
match self {
|
||||
Self::Volume { event, market } => {
|
||||
Ok(
|
||||
crate::volume::Report::read(db, event.as_deref(), market.as_deref())?
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::Price(request) => request.single(db),
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
Self::PricesHistory(request) => request.read(db),
|
||||
Self::TickHistory(request) => request.read(db),
|
||||
Self::MarketAmounts(request) => request.read(db),
|
||||
Self::LimitAmounts(request) => request.read(db),
|
||||
Self::Estimate(request) => request.read(db, books),
|
||||
Self::Resolution { market } => crate::resolution::read(db, &market),
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Activity(filter) => filter.read(db),
|
||||
Self::Balance { account } => crate::ledger::balance(db, &account),
|
||||
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
|
||||
Self::Holders(request) => request.read(db),
|
||||
Self::OpenInterest(request) => request.read(db),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::PublicTrades(request) => request.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
Self::BookFeed(request) => request.read(db, books),
|
||||
Self::ClobBook { token_id } => crate::book_snapshot::read(db, books, &token_id),
|
||||
Self::Book { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT side,price,SUM(remaining) FROM visible_orders WHERE market=?1 AND outcome=?2
|
||||
GROUP BY side,price ORDER BY side, CASE side WHEN 'buy' THEN -price ELSE price END",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![market, outcome])?;
|
||||
let mut bids = Vec::new();
|
||||
let mut asks = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let side: String = row.get(0)?;
|
||||
let price: i64 = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let levels = if side == "buy" { &mut bids } else { &mut asks };
|
||||
levels.push(json!({"price_micros":price*10000,"size":size}));
|
||||
}
|
||||
let changes = books.changes(db)?;
|
||||
books.apply(changes);
|
||||
let bids = crate::book_snapshot::local_levels(
|
||||
books,
|
||||
&market,
|
||||
&outcome,
|
||||
matching::Side::Sell,
|
||||
);
|
||||
let asks = crate::book_snapshot::local_levels(
|
||||
books,
|
||||
&market,
|
||||
&outcome,
|
||||
matching::Side::Buy,
|
||||
);
|
||||
let minimum =
|
||||
crate::minimum_size::MinimumSize::load(db, &market)?.map(|size| size.text());
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks}),
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,"bids":bids,"asks":asks,"min_order_size":minimum,
|
||||
"tick_seq":crate::tick_changes::latest_seq(db,&market)?,
|
||||
"tick_size":crate::tick_size::TickSize::load(db,&market)?.map(|tick|tick.text())}),
|
||||
)
|
||||
}
|
||||
Self::Quote { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
let (bid, ask): (Option<i64>, Option<i64>) = db.query_row(
|
||||
"SELECT MAX(CASE WHEN side='buy' THEN price END),
|
||||
MIN(CASE WHEN side='sell' THEN price END)
|
||||
FROM visible_orders WHERE market=?1 AND outcome=?2",
|
||||
params![market, outcome],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
// Fills also cover databases created before timestamped history was introduced.
|
||||
let last: Option<i64> = db.query_row(
|
||||
"SELECT (SELECT price FROM (
|
||||
SELECT f.seq, f.price FROM fills f JOIN orders o ON o.seq=f.bid WHERE o.market=?1 AND o.outcome=?2
|
||||
UNION ALL SELECT seq, CASE WHEN ?2='YES' THEN yes_price ELSE 100-yes_price END FROM paired_fills WHERE market=?1
|
||||
) ORDER BY seq DESC LIMIT 1)",
|
||||
params![market, outcome],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let (display, source) = match (phase.as_str(), bid, ask, last) {
|
||||
("continuous", Some(b), Some(a), _) if (0..=10).contains(&(a - b)) => {
|
||||
(Some((a + b) * 5000), Some("midpoint"))
|
||||
}
|
||||
("continuous", _, _, Some(p)) => (Some(p * 10000), Some("last_trade")),
|
||||
_ => (None, None),
|
||||
};
|
||||
let quote = crate::quotes::Quote::current(db, &market, &outcome)?;
|
||||
let (bid, ask) = (quote.bid, quote.ask);
|
||||
let last = quote.last;
|
||||
let (display, source) = if phase == "continuous" {
|
||||
quote.mark(&phase)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
.unzip();
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,
|
||||
"best_bid_micros":bid.map(|p|p*10000),"best_ask_micros":ask.map(|p|p*10000),
|
||||
"last_trade_micros":last.map(|p|p*10000),"display_price_micros":display,"source":source}),
|
||||
"quote_seq":quote.seq,"best_bid_micros":bid.map(|p|p*100),"best_ask_micros":ask.map(|p|p*100),
|
||||
"last_trade_micros":last.map(|p|p*100),"display_price_micros":display,"source":source}),
|
||||
)
|
||||
}
|
||||
Self::Events {
|
||||
@@ -337,9 +381,9 @@ impl Query {
|
||||
limit,
|
||||
} => {
|
||||
ensure!((1..=100).contains(&limit), "invalid event page size");
|
||||
let mut stmt=db.prepare("SELECT id,slug,title,category FROM event_directory WHERE id>?1 AND (?2 IS NULL OR category=?2) ORDER BY id LIMIT ?3")?;
|
||||
let mut stmt=db.prepare("SELECT id,slug,title,category,event_id FROM numbered_events WHERE id>?1 AND (?2 IS NULL OR category=?2) ORDER BY id LIMIT ?3")?;
|
||||
let mut items=stmt.query_map(params![after.as_deref().unwrap_or(""),category,limit+1],|r| Ok(json!({
|
||||
"id":r.get::<_,String>(0)?, "slug":r.get::<_,String>(1)?, "title":r.get::<_,String>(2)?, "category":r.get::<_,String>(3)?
|
||||
"id":r.get::<_,String>(0)?, "event_id":r.get::<_,i64>(4)?, "slug":r.get::<_,String>(1)?, "title":r.get::<_,String>(2)?, "category":r.get::<_,String>(3)?
|
||||
})))?.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let next = if items.len() > limit as usize {
|
||||
items.pop();
|
||||
@@ -351,15 +395,15 @@ impl Query {
|
||||
}
|
||||
Self::Catalog { event, slug } => {
|
||||
let (key, sql) = match (event, slug) {
|
||||
(Some(id), None) => (id, "SELECT * FROM event_directory WHERE id=?1"),
|
||||
(None, Some(slug)) => (slug, "SELECT * FROM event_directory WHERE slug=?1"),
|
||||
(Some(id), None) => (id, "SELECT * FROM numbered_events WHERE id=?1"),
|
||||
(None, Some(slug)) => (slug, "SELECT * FROM numbered_events WHERE slug=?1"),
|
||||
_ => anyhow::bail!("specify either event or slug"),
|
||||
};
|
||||
identifier(&key)?;
|
||||
let (id, detail) = db.query_row(sql, [key], |r| {
|
||||
let (id, mut detail) = db.query_row(sql, [key], |r| {
|
||||
let id: String = r.get("id")?;
|
||||
let mut event = json!({
|
||||
"id": id, "slug": r.get::<_, String>("slug")?,
|
||||
"id": id, "event_id": r.get::<_, i64>("event_id")?, "slug": r.get::<_, String>("slug")?,
|
||||
"title": r.get::<_, String>("title")?, "category": r.get::<_, String>("category")?
|
||||
});
|
||||
if let Some(sport) = r.get::<_, Option<String>>("sport")? {
|
||||
@@ -371,13 +415,27 @@ impl Query {
|
||||
}
|
||||
Ok((id,event))
|
||||
})?;
|
||||
if detail.get("sport").is_some() {
|
||||
detail["kickoff"] = db.query_row(
|
||||
"SELECT due_ms,cleared_at_ms,cancelled_orders FROM sports_kickoffs WHERE event=?",
|
||||
[&id], |r| Ok(json!({"scheduled_at_ms":r.get::<_,i64>(0)?,
|
||||
"cleared_at_ms":r.get::<_,Option<i64>>(1)?,
|
||||
"cancelled_orders":r.get::<_,Option<i64>>(2)?})),
|
||||
).optional()?.unwrap_or(Value::Null);
|
||||
}
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT s.market,question,yes_label,no_label,terms,source,resolver,rules_version,
|
||||
m.rules,m.phase,group_title,group_order,n.group_id,n.ordinal
|
||||
"SELECT s.market,COALESCE(a.question,s.question),yes_label,no_label,terms,source,resolver,rules_version,
|
||||
m.rules,m.phase,COALESCE(a.name,group_title),group_order,n.group_id,n.ordinal,
|
||||
a.role,a.clarification,a.named_at,minimum.microshares,tick.step_micros
|
||||
FROM listed_markets s JOIN markets m ON m.id=s.market
|
||||
LEFT JOIN neg_risk_members n ON n.market=s.market
|
||||
WHERE event=? ORDER BY group_order,s.market"
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=s.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=s.market
|
||||
WHERE event=? AND (a.role IS NULL OR a.role<>'placeholder') ORDER BY group_order,s.market"
|
||||
)?;
|
||||
let volume = crate::volume::Report::read(db, Some(&id), None)?;
|
||||
detail["volume"] = json!(volume.total);
|
||||
let mut rows = stmt.query([id])?;
|
||||
let mut markets = Vec::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
@@ -385,7 +443,7 @@ impl Query {
|
||||
let yes: String = r.get(2)?;
|
||||
let no: String = r.get(3)?;
|
||||
markets.push(
|
||||
json!({"market":market, "outcomes":assets::outcomes(&market,&yes,&no),
|
||||
json!({"market":market, "volume":volume.markets.get(&market), "outcomes":assets::outcomes(&market,&yes,&no),
|
||||
"question":r.get::<_,String>(1)?,
|
||||
"yes_label":yes,
|
||||
"no_label":no,
|
||||
@@ -394,6 +452,11 @@ impl Query {
|
||||
"group_order":r.get::<_,i64>(11)?,
|
||||
"neg_risk_group":r.get::<_,Option<String>>(12)?,
|
||||
"neg_risk_index":r.get::<_,Option<i64>>(13)?,
|
||||
"augmented_role":r.get::<_,Option<String>>(14)?,
|
||||
"clarification":r.get::<_,Option<String>>(15)?,
|
||||
"named_at":r.get::<_,Option<i64>>(16)?,
|
||||
"tick_size":r.get::<_,Option<i64>>(18)?.map(|v|crate::tick_size::TickSize(v).text()),
|
||||
"min_order_size":r.get::<_,Option<i64>>(17)?.map(crate::minimum_size::MinimumSize::format_microshares),
|
||||
"source":r.get::<_,String>(5)?,
|
||||
"resolver":r.get::<_,String>(6)?,
|
||||
"rules_version":r.get::<_,i64>(7)?,
|
||||
@@ -428,7 +491,7 @@ impl Query {
|
||||
Ok(json!({"at_ms":r.get::<_,i64>(0)?,
|
||||
"fill":r.get::<_,i64>(1)?,
|
||||
"price_micros":r.get::<_,i64>(2)?,
|
||||
"quantity":r.get::<_,i64>(3)?}))
|
||||
"quantity":crate::lots::display(r.get::<_,i64>(3)?)}))
|
||||
},
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use crate::{market, validation::phase, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn publish(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
content: &str,
|
||||
clear_book: bool,
|
||||
) -> Result<Value> {
|
||||
phase(tx, market, &["preopen", "continuous", "closed"])?;
|
||||
ensure!(!content.trim().is_empty(), "clarification text required");
|
||||
tx.execute(
|
||||
"INSERT INTO market_clarifications(market,content,clear_book) VALUES(?1,?2,?3)",
|
||||
params![market, content, clear_book],
|
||||
)?;
|
||||
let id = tx.last_insert_rowid();
|
||||
let canceled = if clear_book {
|
||||
market::clear_orders(tx, market)?
|
||||
} else {
|
||||
0
|
||||
};
|
||||
Ok(json!({"id":id,"market":market,"clearBook":clear_book,"canceled_count":canceled}))
|
||||
}
|
||||
|
||||
fn read(
|
||||
db: &Connection,
|
||||
market: Option<&str>,
|
||||
ids: &[i64],
|
||||
event_ids: &[i64],
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> rusqlite::Result<Vec<Value>> {
|
||||
let ids_json = json!(ids).to_string();
|
||||
let events_json = json!(event_ids).to_string();
|
||||
let order = if ascending { "ASC" } else { "DESC" };
|
||||
let sql = format!(
|
||||
"SELECT n.id,d.id,n.content,n.clear_book,n.created_at
|
||||
FROM market_clarifications n JOIN market_directory_ids d ON d.market=n.market
|
||||
LEFT JOIN sports_markets s ON s.market=n.market
|
||||
LEFT JOIN topic_markets t ON t.market=n.market
|
||||
LEFT JOIN event_directory_ids e ON e.event=COALESCE(s.event,t.event)
|
||||
WHERE (?1 IS NULL OR n.market=?1)
|
||||
AND (?2='[]' OR d.id IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3='[]' OR e.id IN (SELECT value FROM json_each(?3)))
|
||||
ORDER BY n.id {order} LIMIT ?4 OFFSET ?5"
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(params![market, ids_json, events_json, limit, offset], |r| {
|
||||
Ok(
|
||||
json!({"id":r.get::<_,i64>(0)?,"marketId":r.get::<_,i64>(1)?,
|
||||
"content":r.get::<_,String>(2)?,"clearBook":r.get::<_,bool>(3)?,
|
||||
"createdAt":r.get::<_,String>(4)?,"showInFrontend":true,
|
||||
"txTimestamp":null,"txHash":null}),
|
||||
)
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn for_resolution(db: &Connection, market: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
read(db, Some(market), &[], &[], -1, 0, true)
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn market_clarifications(
|
||||
&self,
|
||||
ids: &[i64],
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
self.filtered_market_clarifications(ids, &[], limit, offset, ascending)
|
||||
}
|
||||
|
||||
pub fn filtered_market_clarifications(
|
||||
&self,
|
||||
ids: &[i64],
|
||||
event_ids: &[i64],
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
ascending: bool,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
if ids.iter().chain(event_ids).any(|id| *id <= 0) || limit > 100 || offset < 0 {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"invalid clarification filter".into(),
|
||||
));
|
||||
}
|
||||
Ok(read(
|
||||
&self.db,
|
||||
None,
|
||||
ids,
|
||||
event_ids,
|
||||
i64::from(limit),
|
||||
offset,
|
||||
ascending,
|
||||
)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use crate::{
|
||||
assets, inventory, lots, tick_size::TickSize, validation::identifier, Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::OptionalExtension;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
impl Exchange {
|
||||
/// Resolve either outcome to the same market and its stable YES/NO pair.
|
||||
pub fn market_by_token(&self, token: &str) -> Result<Option<Value>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let exists: bool = self
|
||||
.db
|
||||
.prepare_cached("SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)")?
|
||||
.query_row([market], |r| r.get(0))?;
|
||||
Ok(exists.then(|| json!({"condition_id":market,
|
||||
"primary_token_id":assets::id(market,"YES"),"secondary_token_id":assets::id(market,"NO")})))
|
||||
}
|
||||
|
||||
/// Report the configuration used by local execution in a single read snapshot.
|
||||
pub fn clob_market_info(&self, market: &str) -> Result<Option<Value>, MarketDataError> {
|
||||
identifier(market).map_err(|_| MarketDataError::Invalid("Invalid condition id".into()))?;
|
||||
let mut stmt = self.db.prepare_cached(include_str!("clob_market.sql"))?;
|
||||
let info = stmt
|
||||
.query_row([market], |r| {
|
||||
let yes: String = r.get(0)?;
|
||||
let no: String = r.get(1)?;
|
||||
let tick = r
|
||||
.get::<_, Option<i64>>(2)?
|
||||
.map(TickSize)
|
||||
.unwrap_or(TickSize::WHOLE_CENT);
|
||||
let minimum = r.get::<_, Option<i64>>(3)?.unwrap_or(lots::MICROS);
|
||||
let fee: i64 = r.get(4)?;
|
||||
let neg_risk: bool = r.get(5)?;
|
||||
let kickoff: Option<String> = r.get(6)?;
|
||||
let mut info = json!({"gst":kickoff,"t":[
|
||||
{"t":assets::id(market,"YES"),"o":yes},
|
||||
{"t":assets::id(market,"NO"),"o":no}],
|
||||
"mts":tick.number(),"mos":inventory::decimal(minimum.into(),inventory::UNIT),
|
||||
"nr":neg_risk,"rfqe":false,"ibce":false,"oas":0});
|
||||
info["mbf"] = json!(r.get::<_, i64>(7)?);
|
||||
if let Some(base) = r.get::<_, Option<i64>>(8)? {
|
||||
info["tbf"] = json!(base);
|
||||
}
|
||||
if fee != 0 {
|
||||
info["fd"] =
|
||||
json!({"r":inventory::decimal(fee.into(),inventory::UNIT),"e":1,"to":true});
|
||||
}
|
||||
Ok(info)
|
||||
})
|
||||
.optional()?;
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
SELECT w.yes_label, w.no_label, tick.step_micros, minimum.microshares,
|
||||
COALESCE(fee.rate_ppm, 0), member.market IS NOT NULL,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ', event.scheduled_at_ms / 1000.0, 'unixepoch'), fee.maker_bps, fee.taker_bps
|
||||
FROM market_wire_metadata w
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
|
||||
JOIN market_fee_terms fee ON fee.market=w.market
|
||||
LEFT JOIN neg_risk_members member ON member.market=w.market
|
||||
LEFT JOIN sports_markets sport ON sport.market=w.market
|
||||
LEFT JOIN events event ON event.id=sport.event
|
||||
WHERE w.market=?1
|
||||
@@ -5,12 +5,35 @@ use serde::Deserialize;
|
||||
pub(crate) enum Command {
|
||||
Fund {
|
||||
account: String,
|
||||
cents: i64,
|
||||
cents: Option<i64>,
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "bind_polymarket_assets")]
|
||||
BindPolymarketAssets(crate::token_aliases::Bind),
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
previous_ms: i64,
|
||||
scheduled_at_ms: i64,
|
||||
},
|
||||
#[serde(rename = "set_market_visibility")]
|
||||
SetMarketVisibility {
|
||||
market: String,
|
||||
active: bool,
|
||||
archived: bool,
|
||||
},
|
||||
#[serde(rename = "tick_size_change")]
|
||||
TickSizeChange(crate::tick_changes::Change),
|
||||
List {
|
||||
market: String,
|
||||
slug: Option<String>,
|
||||
question: Option<String>,
|
||||
rules: String,
|
||||
taker_fee_rate_ppm: Option<i64>,
|
||||
base_fees: Option<crate::fees::BaseFees>,
|
||||
min_order_size: Option<String>,
|
||||
tick_size: Option<String>,
|
||||
#[serde(default)]
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
@@ -20,30 +43,56 @@ pub(crate) enum Command {
|
||||
group: String,
|
||||
event: String,
|
||||
markets: Vec<String>,
|
||||
augmented: Option<crate::augmented::Config>,
|
||||
conversion_fee: Option<crate::neg_risk::ConversionFee>,
|
||||
},
|
||||
#[serde(rename = "publish_clarification")]
|
||||
PublishClarification {
|
||||
market: String,
|
||||
content: String,
|
||||
clear_book: bool,
|
||||
},
|
||||
Clarify {
|
||||
market: String,
|
||||
name: String,
|
||||
question: String,
|
||||
evidence: String,
|
||||
},
|
||||
#[serde(rename = "finalize_augmented")]
|
||||
FinalizeAugmented {
|
||||
group: String,
|
||||
observed_name: String,
|
||||
evidence: String,
|
||||
},
|
||||
Convert {
|
||||
group: String,
|
||||
account: String,
|
||||
no_markets: Vec<String>,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
},
|
||||
Split {
|
||||
market: String,
|
||||
account: String,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
},
|
||||
Merge {
|
||||
market: String,
|
||||
account: String,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
},
|
||||
Order {
|
||||
market: String,
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
outcome: String,
|
||||
side: String,
|
||||
price: i64,
|
||||
qty: i64,
|
||||
price: Option<i64>,
|
||||
price_micros: Option<i64>,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
#[serde(default)]
|
||||
tif: Option<TimeInForce>,
|
||||
expiration: Option<i64>,
|
||||
@@ -54,9 +103,12 @@ pub(crate) enum Command {
|
||||
MarketSell {
|
||||
market: String,
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
min_price: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
min_price: Option<i64>,
|
||||
min_price_micros: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
#[serde(rename = "market_buy")]
|
||||
@@ -64,8 +116,11 @@ pub(crate) enum Command {
|
||||
market: String,
|
||||
outcome: String,
|
||||
account: String,
|
||||
amount_cents: i64,
|
||||
max_price: i64,
|
||||
key_id: Option<String>,
|
||||
amount_cents: Option<i64>,
|
||||
amount_micros: Option<i64>,
|
||||
max_price: Option<i64>,
|
||||
max_price_micros: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
Cancel {
|
||||
@@ -125,6 +180,8 @@ pub(crate) enum Command {
|
||||
Redeem {
|
||||
market: String,
|
||||
account: String,
|
||||
#[serde(default, deserialize_with = "redeem_amounts")]
|
||||
amounts_micros: Option<[i64; 2]>,
|
||||
},
|
||||
Resolve {
|
||||
market: String,
|
||||
@@ -141,3 +198,10 @@ pub(crate) enum TimeInForce {
|
||||
Fak,
|
||||
Fok,
|
||||
}
|
||||
|
||||
// Only an omitted field selects full redemption. An explicit null must not spend a balance.
|
||||
fn redeem_amounts<'de, D: serde::Deserializer<'de>>(
|
||||
input: D,
|
||||
) -> Result<Option<[i64; 2]>, D::Error> {
|
||||
<[i64; 2]>::deserialize(input).map(Some)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
use crate::{assets, book_snapshot, inventory::decimal, lots, resident::Books, tick_size::PAR};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn flush(tx: &Transaction) -> Result<()> {
|
||||
if tx.query_row("SELECT EXISTS(SELECT 1 FROM depth_pending)", [], |r| {
|
||||
r.get::<_, bool>(0)
|
||||
})? {
|
||||
tx.execute_batch(include_str!("depth_flush.sql"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn price(units: i64) -> String {
|
||||
decimal(units.into(), PAR).to_string()
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
market: String,
|
||||
after: Option<i64>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Batch numbers are local delivery cursors; they are never placed on the wire.
|
||||
pub struct MarketPage {
|
||||
pub cursor: i64,
|
||||
pub frames: Vec<(i64, Value)>,
|
||||
pub has_more: bool,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn read(self, tx: &Transaction, books: &mut Books) -> Result<Value> {
|
||||
let page = self.page(tx, books)?;
|
||||
let events: Vec<_> = page.frames.into_iter().map(|(_, event)| event).collect();
|
||||
Ok(json!({"cursor":page.cursor,"events":events,"has_more":page.has_more}))
|
||||
}
|
||||
|
||||
fn page(self, tx: &Transaction, books: &mut Books) -> Result<MarketPage> {
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!((1..=500).contains(&limit), "invalid book_feed batch limit");
|
||||
let latest: i64 = tx.query_row(
|
||||
"SELECT COALESCE((SELECT MAX(seq) FROM depth_batches WHERE market=?1),0) FROM markets WHERE id=?1",
|
||||
[&self.market], |r| r.get(0))?;
|
||||
let Some(mut cursor) = self.after else {
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
let mut events = Vec::new();
|
||||
for outcome in ["YES", "NO"] {
|
||||
let asset = assets::id(&self.market, outcome);
|
||||
let frame = book_snapshot::event(tx, books, &asset, false)?;
|
||||
events.push((latest, frame));
|
||||
}
|
||||
return Ok(MarketPage {
|
||||
cursor: latest,
|
||||
frames: events,
|
||||
has_more: false,
|
||||
});
|
||||
};
|
||||
ensure!((0..=latest).contains(&cursor), "invalid book_feed cursor");
|
||||
let mut batches = tx.prepare_cached(
|
||||
"SELECT seq,strftime('%Y-%m-%dT%H:%M:%f000Z',at_ms/1000.0,'unixepoch'),best_bid,best_ask
|
||||
FROM depth_batches WHERE market=?1 AND seq>?2 ORDER BY seq LIMIT ?3")?;
|
||||
let mut rows = batches.query(params![self.market, cursor, limit])?;
|
||||
let mut events = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
cursor = row.get(0)?;
|
||||
let stamp: String = row.get(1)?;
|
||||
let bid: Option<i64> = row.get(2)?;
|
||||
let ask: Option<i64> = row.get(3)?;
|
||||
let changes = changes(tx, &self.market, cursor, bid, ask)?;
|
||||
let frame = json!({"topic":"market","type":"price_change","payload":{"condition_id":self.market,
|
||||
"price_changes":changes,"timestamp":stamp}});
|
||||
events.push((cursor, frame));
|
||||
}
|
||||
Ok(MarketPage {
|
||||
cursor,
|
||||
frames: events,
|
||||
has_more: cursor < latest,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn changes(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
batch: i64,
|
||||
bid: Option<i64>,
|
||||
ask: Option<i64>,
|
||||
) -> Result<Vec<Value>> {
|
||||
let mut updates = tx.prepare_cached(
|
||||
"SELECT side,price,size FROM depth_updates WHERE batch=? ORDER BY side,price",
|
||||
)?;
|
||||
let mut levels = updates.query([batch])?;
|
||||
let mut changes = Vec::new();
|
||||
while let Some(level) = levels.next()? {
|
||||
let side: String = level.get(0)?;
|
||||
let p: i64 = level.get(1)?;
|
||||
let size: i64 = level.get(2)?;
|
||||
for (outcome, is_bid, p, bid, ask) in [
|
||||
("YES", side == "buy", p, bid, ask),
|
||||
(
|
||||
"NO",
|
||||
side == "sell",
|
||||
PAR - p,
|
||||
ask.map(|v| PAR - v),
|
||||
bid.map(|v| PAR - v),
|
||||
),
|
||||
] {
|
||||
changes.push(
|
||||
json!({"asset_id":assets::id(market,outcome),"side":if is_bid {"BUY"} else {"SELL"},
|
||||
"price":price(p),"size":decimal(size.into(),lots::PER_SHARE).to_string(),
|
||||
"best_bid":bid.map(price),"best_ask":ask.map(price),"hash":null}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(changes)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
-- Run within the command or expiry transaction. A fully crossed incoming order
|
||||
-- can enter and leave a level in one transaction without changing its depth.
|
||||
DELETE FROM depth_pending WHERE delta=0;
|
||||
INSERT INTO depth_levels SELECT market,side,price,delta FROM depth_pending WHERE true
|
||||
ON CONFLICT(market,side,price) DO UPDATE SET size=size+excluded.size;
|
||||
INSERT INTO depth_batches(market,at_ms,best_bid,best_ask)
|
||||
SELECT p.market,t.at_ms,
|
||||
(SELECT price FROM depth_levels WHERE market=p.market AND side='buy' AND size>0 ORDER BY price DESC LIMIT 1),
|
||||
(SELECT price FROM depth_levels WHERE market=p.market AND side='sell' AND size>0 ORDER BY price LIMIT 1)
|
||||
FROM (SELECT DISTINCT market FROM depth_pending) p JOIN book_snapshot_times t ON t.market=p.market;
|
||||
INSERT INTO depth_updates
|
||||
SELECT (SELECT MAX(seq) FROM depth_batches WHERE market=p.market),p.side,p.price,l.size
|
||||
FROM depth_pending p JOIN depth_levels l USING(market,side,price);
|
||||
DELETE FROM depth_levels WHERE (market,side,price) IN (SELECT market,side,price FROM depth_pending) AND size=0;
|
||||
DELETE FROM depth_pending;
|
||||
@@ -0,0 +1,40 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Both outcomes project from the YES book. Prices use local units and size uses lots.
|
||||
CREATE TABLE IF NOT EXISTS depth_levels(
|
||||
market TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, size INTEGER NOT NULL,
|
||||
PRIMARY KEY(market,side,price)
|
||||
) WITHOUT ROWID;
|
||||
INSERT OR IGNORE INTO depth_levels
|
||||
SELECT market,side,price,SUM(remaining) FROM visible_orders
|
||||
WHERE outcome='YES' AND remaining>0 GROUP BY market,side,price;
|
||||
CREATE TABLE IF NOT EXISTS depth_pending(
|
||||
market TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, delta INTEGER NOT NULL,
|
||||
PRIMARY KEY(market,side,price)
|
||||
) WITHOUT ROWID;
|
||||
CREATE TABLE IF NOT EXISTS depth_batches(
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL, at_ms INTEGER NOT NULL,
|
||||
best_bid INTEGER, best_ask INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS depth_batches_market ON depth_batches(market,seq);
|
||||
CREATE TABLE IF NOT EXISTS depth_updates(
|
||||
batch INTEGER NOT NULL REFERENCES depth_batches, side TEXT NOT NULL,
|
||||
price INTEGER NOT NULL, size INTEGER NOT NULL CHECK(size>=0),
|
||||
PRIMARY KEY(batch,side,price)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE VIEW IF NOT EXISTS depth_delta AS SELECT market,side,price,delta,'' AS outcome FROM depth_pending WHERE 0;
|
||||
CREATE TRIGGER IF NOT EXISTS depth_normalize INSTEAD OF INSERT ON depth_delta WHEN NEW.delta<>0 BEGIN
|
||||
INSERT INTO depth_pending VALUES(NEW.market,
|
||||
CASE WHEN NEW.outcome='YES' THEN NEW.side WHEN NEW.side='buy' THEN 'sell' ELSE 'buy' END,
|
||||
CASE WHEN NEW.outcome='YES' THEN NEW.price ELSE 10000-NEW.price END, NEW.delta)
|
||||
ON CONFLICT(market,side,price) DO UPDATE SET delta=delta+excluded.delta;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS depth_insert AFTER INSERT ON orders WHEN NEW.status='live' BEGIN
|
||||
INSERT INTO depth_delta VALUES(NEW.market,NEW.side,NEW.price,NEW.remaining,NEW.outcome);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS depth_update AFTER UPDATE OF status,remaining ON orders BEGIN
|
||||
INSERT INTO depth_delta VALUES(NEW.market,NEW.side,NEW.price,
|
||||
(CASE WHEN NEW.status='live' THEN NEW.remaining ELSE 0 END) -
|
||||
(CASE WHEN OLD.status='live' THEN OLD.remaining ELSE 0 END),NEW.outcome);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -1,10 +1,4 @@
|
||||
use crate::{
|
||||
assets,
|
||||
book::gross_cents,
|
||||
command::TimeInForce,
|
||||
resident::Books,
|
||||
validation::{amount, phase},
|
||||
};
|
||||
use crate::{assets, book::gross_micros, command::TimeInForce, resident::Books, validation::phase};
|
||||
use anyhow::{ensure, Result};
|
||||
use matching::{Order, Side};
|
||||
use rusqlite::Transaction;
|
||||
@@ -17,15 +11,19 @@ pub(crate) enum Request {
|
||||
Buy {
|
||||
market: String,
|
||||
outcome: String,
|
||||
amount_cents: i64,
|
||||
amount_cents: Option<i64>,
|
||||
amount_micros: Option<i64>,
|
||||
max_price: Option<i64>,
|
||||
max_price_micros: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
Sell {
|
||||
market: String,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
min_price: Option<i64>,
|
||||
min_price_micros: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
}
|
||||
@@ -37,49 +35,71 @@ impl Request {
|
||||
market,
|
||||
outcome,
|
||||
amount_cents,
|
||||
amount_micros,
|
||||
max_price,
|
||||
max_price_micros,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Buy,
|
||||
amount_cents,
|
||||
max_price.unwrap_or(100),
|
||||
crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
|
||||
crate::tick_size::input(max_price, max_price_micros)?,
|
||||
tif,
|
||||
),
|
||||
Self::Sell {
|
||||
market,
|
||||
outcome,
|
||||
qty,
|
||||
size_micros,
|
||||
min_price,
|
||||
min_price_micros,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Sell,
|
||||
qty,
|
||||
min_price.unwrap_or(0),
|
||||
crate::lots::amount(qty, size_micros)?,
|
||||
crate::tick_size::input(min_price, min_price_micros)?,
|
||||
tif,
|
||||
),
|
||||
};
|
||||
let tick = crate::tick_size::TickSize::load(tx, &market)?;
|
||||
let tif = tif.unwrap_or(TimeInForce::Fak);
|
||||
amount(requested)?;
|
||||
ensure!(
|
||||
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
|
||||
"estimate requires FAK or FOK"
|
||||
);
|
||||
ensure!(
|
||||
matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&limit),
|
||||
"invalid outcome or price"
|
||||
);
|
||||
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
|
||||
phase(tx, &market, &["continuous"])?;
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
let protection = books.protection_price(&market, &outcome, side, requested, limit, tif);
|
||||
let amounts = match protection {
|
||||
Some(price) => {
|
||||
crate::market_amounts::Amounts::for_order(tick.as_ref(), side, requested, price)?
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let rate = crate::fees::rate(tx, &market)?;
|
||||
if let Some(minimum) = crate::minimum_size::MinimumSize::load(tx, &market)? {
|
||||
match (side, protection) {
|
||||
(Side::Buy, Some(price)) => minimum.check_budget(requested, price, rate)?,
|
||||
(Side::Sell, _) => minimum.check_microshares(requested * crate::lots::MICROS)?,
|
||||
(Side::Buy, None) => {}
|
||||
}
|
||||
}
|
||||
// A failed FOK estimate still reports how much depth was visible.
|
||||
let limit = protection.unwrap_or(if side == Side::Buy {
|
||||
crate::tick_size::PAR
|
||||
} else {
|
||||
0
|
||||
});
|
||||
// The hypothetical incoming order follows all resting orders in time priority.
|
||||
let fills = books
|
||||
let mut fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| match side {
|
||||
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
|
||||
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested * 10000),
|
||||
Side::Sell => b.match_incoming(&Order {
|
||||
seq: i64::MAX,
|
||||
side,
|
||||
@@ -88,23 +108,44 @@ impl Request {
|
||||
}),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if side == Side::Buy {
|
||||
crate::fees::fit_budget(rate, &mut fills, requested);
|
||||
}
|
||||
let fee = crate::fees::total(rate, &fills);
|
||||
let shares: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
let gross = gross_cents(&fills);
|
||||
let remainder = requested
|
||||
- match side {
|
||||
Side::Buy => gross,
|
||||
Side::Sell => shares,
|
||||
};
|
||||
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":shares,
|
||||
"gross_cents":gross,"best_fill_price":fills.first().map(|f|f.price),
|
||||
"worst_fill_price":fills.last().map(|f|f.price),
|
||||
"average_price_micros":(gross*10000).checked_div(shares),
|
||||
"fully_fillable":remainder==0,"executable":shares>0 && (tif==TimeInForce::Fak || remainder==0)});
|
||||
let key = match side {
|
||||
Side::Buy => "unspent_cents",
|
||||
Side::Sell => "unsold_shares",
|
||||
let gross = gross_micros(&fills);
|
||||
let remaining_cash = if side == Side::Buy {
|
||||
requested * 10000 - gross - fee
|
||||
} else {
|
||||
0
|
||||
};
|
||||
result[key] = json!(remainder);
|
||||
let fully_fillable = protection.is_some()
|
||||
&& match side {
|
||||
Side::Buy => remaining_cash == 0,
|
||||
Side::Sell => requested == shares,
|
||||
};
|
||||
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":crate::lots::display(shares),
|
||||
"gross_cents":crate::inventory::decimal(gross.into(),10000),"best_fill_price":fills.first().map(|f|crate::inventory::decimal(f.price.into(),100)),
|
||||
"worst_fill_price":fills.last().map(|f|crate::inventory::decimal(f.price.into(),100)),
|
||||
"average_price_micros":(i128::from(gross)*100).checked_div(i128::from(shares)),
|
||||
"fee_micros":fee,"taker_fee_rate_ppm":rate,
|
||||
"protection_price_micros":protection.map(|p|p * crate::tick_size::PRICE_MICROS),
|
||||
"fully_fillable":fully_fillable,"executable":protection.is_some() && shares>0 && (tif==TimeInForce::Fak || fully_fillable)});
|
||||
if let Some(amounts) = amounts {
|
||||
result["order_amounts"] = amounts.json();
|
||||
}
|
||||
match side {
|
||||
Side::Buy => {
|
||||
result["total_spent_micros"] = json!(gross + fee);
|
||||
result["unspent_cents"] =
|
||||
json!(crate::inventory::decimal(remaining_cash.into(), 10000));
|
||||
result["unspent_micros"] = json!(remaining_cash);
|
||||
}
|
||||
Side::Sell => {
|
||||
result["net_proceeds_micros"] = json!(gross - fee);
|
||||
result["unsold_shares"] = json!(crate::lots::display(requested - shares));
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS event_directory_ids (
|
||||
id INTEGER PRIMARY KEY, event TEXT NOT NULL UNIQUE
|
||||
);
|
||||
INSERT INTO event_directory_ids(event)
|
||||
SELECT e.id FROM event_directory e
|
||||
WHERE NOT EXISTS (SELECT 1 FROM event_directory_ids d WHERE d.event=e.id)
|
||||
ORDER BY e.id;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS number_sports_event AFTER INSERT ON events BEGIN
|
||||
INSERT INTO event_directory_ids(event) VALUES(NEW.id);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS number_topic_event AFTER INSERT ON topics BEGIN
|
||||
INSERT INTO event_directory_ids(event) VALUES(NEW.id);
|
||||
END;
|
||||
|
||||
CREATE VIEW IF NOT EXISTS numbered_events AS
|
||||
SELECT e.*,d.id AS event_id FROM event_directory e JOIN event_directory_ids d ON d.event=e.id;
|
||||
COMMIT;
|
||||
@@ -12,7 +12,10 @@ pub(crate) fn transaction(
|
||||
let tx = Transaction::new_unchecked(db, behavior)?;
|
||||
let due: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())",
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())
|
||||
OR EXISTS(SELECT 1 FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM sports_kickoffs WHERE cleared_at_ms IS NULL AND due_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !due {
|
||||
@@ -44,6 +47,10 @@ pub(crate) fn transaction(
|
||||
for market in markets {
|
||||
crate::market::close_market(&write, &market)?;
|
||||
}
|
||||
crate::kickoff::clear_due(&write)?;
|
||||
crate::heartbeat::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
crate::depth_feed::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
use crate::{assets, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use matching::Fill;
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct BaseFees {
|
||||
maker_bps: i64,
|
||||
taker_bps: i64,
|
||||
}
|
||||
|
||||
impl BaseFees {
|
||||
pub(crate) fn save(self, tx: &Transaction, market: &str) -> Result<()> {
|
||||
ensure!(
|
||||
self.maker_bps >= 0 && self.taker_bps >= 0,
|
||||
"negative base fee"
|
||||
);
|
||||
tx.execute(
|
||||
"INSERT INTO market_base_fees(market,maker_bps,taker_bps) VALUES(?,?,?)",
|
||||
params![market, self.maker_bps, self.taker_bps],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn base_fee_bps(&self, token: &str) -> Result<Option<i64>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt = self
|
||||
.db
|
||||
.prepare_cached("SELECT taker_bps FROM market_fee_terms WHERE market=?1")?;
|
||||
Ok(stmt
|
||||
.query_row([market], |r| r.get::<_, Option<i64>>(0))
|
||||
.optional()?
|
||||
.flatten())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn rate(db: &Connection, market: &str) -> Result<i64> {
|
||||
Ok(db.query_row("SELECT COALESCE(f.rate_ppm,0) FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id WHERE m.id=?", [market], |r|r.get(0))?)
|
||||
}
|
||||
|
||||
// Price and rate both have six decimals. Round the fee only after the
|
||||
// complete fill, to the nearest ten micros, with the published minimum.
|
||||
#[cfg(test)]
|
||||
fn micros(rate: i64, price_micros: i64, shares: i64) -> i64 {
|
||||
lot_fee(rate, price_micros, shares * 100)
|
||||
}
|
||||
|
||||
pub(crate) fn lot_fee(rate: i64, price_micros: i64, lots: i64) -> i64 {
|
||||
let numerator = i128::from(lots)
|
||||
* i128::from(rate)
|
||||
* i128::from(price_micros)
|
||||
* i128::from(1_000_000 - price_micros);
|
||||
let denominator = 1_000_000_000_000_000;
|
||||
if numerator < denominator {
|
||||
return 0;
|
||||
}
|
||||
(((numerator + denominator / 2) / denominator) * 10) as i64
|
||||
}
|
||||
|
||||
pub(crate) fn total(rate: i64, fills: &[Fill]) -> i64 {
|
||||
fills
|
||||
.iter()
|
||||
.map(|f| lot_fee(rate, f.price * 100, f.quantity))
|
||||
.sum()
|
||||
}
|
||||
|
||||
// match_budget_buy supplies FIFO candidates under the gross cap. Stop at
|
||||
// the first partially affordable maker, including its rounded fee.
|
||||
pub(crate) fn fit_budget(rate: i64, fills: &mut Vec<Fill>, budget: i64) {
|
||||
if rate == 0 {
|
||||
return;
|
||||
}
|
||||
let mut remaining = budget * 10000;
|
||||
let mut count = 0;
|
||||
for f in fills.iter_mut() {
|
||||
let cost = |qty: i64| {
|
||||
i128::from(qty) * i128::from(f.price) + i128::from(lot_fee(rate, f.price * 100, qty))
|
||||
};
|
||||
if cost(f.quantity) <= i128::from(remaining) {
|
||||
remaining -= cost(f.quantity) as i64;
|
||||
count += 1;
|
||||
continue;
|
||||
}
|
||||
let (mut lo, mut hi) = (0, f.quantity);
|
||||
while lo < hi {
|
||||
let mid = lo + (hi - lo + 1) / 2;
|
||||
if cost(mid) <= i128::from(remaining) {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
if lo > 0 {
|
||||
f.quantity = lo;
|
||||
count += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
fills.truncate(count);
|
||||
}
|
||||
|
||||
pub(crate) fn configure(tx: &Transaction, market: &str, rate: i64) -> Result<()> {
|
||||
ensure!((0..=1_000_000).contains(&rate), "invalid taker fee rate");
|
||||
tx.execute(
|
||||
"INSERT INTO market_fee_rates VALUES(?,?)",
|
||||
params![market, rate],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::micros;
|
||||
|
||||
#[test]
|
||||
fn symmetric_taker_curve_matches_published_examples_and_minimum() {
|
||||
assert_eq!(micros(50000, 13000, 5), 3210);
|
||||
assert_eq!(micros(50000, 987000, 5), 3210);
|
||||
for (rate, price, size, expected) in [
|
||||
(50000, 50, 100, 1250000),
|
||||
(50000, 30, 100, 1050000),
|
||||
(10000, 50, 100, 250000),
|
||||
(10000, 30, 100, 210000),
|
||||
(0, 50, 100, 0),
|
||||
(1, 50, 39, 0),
|
||||
(1, 50, 40, 10),
|
||||
(1, 50, 60, 20),
|
||||
(50000, 0, 1, 0),
|
||||
] {
|
||||
assert_eq!(micros(rate, price * 10000, size), expected);
|
||||
assert_eq!(micros(rate, (100 - price) * 10000, size), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use crate::{
|
||||
assets, inventory, lots,
|
||||
quotes::display_price,
|
||||
tick_size::{TickSize, PAR},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, ToSql};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// Slugs and numeric IDs are independent namespaces, including numeric-looking slugs.
|
||||
pub enum DirectoryKey<'a> {
|
||||
Id(i64),
|
||||
Slug(&'a str),
|
||||
}
|
||||
|
||||
pub(super) fn header(row: &Row<'_>) -> rusqlite::Result<(String, Value)> {
|
||||
let key = row.get("id")?;
|
||||
let event = json!({
|
||||
"id":row.get::<_,i64>("event_id")?.to_string(),"slug":row.get::<_,String>("slug")?,
|
||||
"title":row.get::<_,String>("title")?,"category":row.get::<_,String>("category")?,
|
||||
"active":true,"closed":row.get::<_,bool>("closed")?
|
||||
});
|
||||
Ok((key, event))
|
||||
}
|
||||
|
||||
fn event_header(
|
||||
db: &Connection,
|
||||
column: &str,
|
||||
key: &dyn ToSql,
|
||||
) -> rusqlite::Result<Option<(String, Value)>> {
|
||||
let sql = format!("{} WHERE e.{column}=?1", include_str!("gamma_events.sql"));
|
||||
db.prepare_cached(&sql)?.query_row([key], header).optional()
|
||||
}
|
||||
|
||||
pub(super) fn market(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
let key: String = row.get("market")?;
|
||||
let phase: String = row.get("phase")?;
|
||||
let accepts = matches!(phase.as_str(), "preopen" | "continuous");
|
||||
let size = row
|
||||
.get::<_, Option<i64>>("microshares")?
|
||||
.unwrap_or(lots::MICROS);
|
||||
let tick = row
|
||||
.get::<_, Option<i64>>("step_micros")?
|
||||
.map(TickSize)
|
||||
.unwrap_or(TickSize::WHOLE_CENT);
|
||||
let bid: Option<i64> = row.get("yes_bid")?;
|
||||
let ask: Option<i64> = row.get("yes_ask")?;
|
||||
let last: Option<i64> = row.get("yes_last")?;
|
||||
let no_last = row.get("no_last")?;
|
||||
let marks = match row.get::<_, Option<String>>("winner")?.as_deref() {
|
||||
Some("YES") => Some((inventory::UNIT, 0)),
|
||||
Some("NO") => Some((0, inventory::UNIT)),
|
||||
Some("VOID") => Some((inventory::UNIT / 2, inventory::UNIT / 2)),
|
||||
_ => display_price(bid, ask, last, &phase)
|
||||
.zip(display_price(
|
||||
ask.map(|p| PAR - p),
|
||||
bid.map(|p| PAR - p),
|
||||
no_last,
|
||||
&phase,
|
||||
))
|
||||
.map(|(yes, no)| (yes.0, no.0)),
|
||||
};
|
||||
let prices = marks.map(|(yes, no)| {
|
||||
json!([
|
||||
inventory::decimal(yes.into(), inventory::UNIT).to_string(),
|
||||
inventory::decimal(no.into(), inventory::UNIT).to_string()
|
||||
])
|
||||
.to_string()
|
||||
});
|
||||
let dollars = |p: i64| inventory::decimal(p.into(), PAR);
|
||||
Ok(json!({
|
||||
"id":row.get::<_,String>("id")?,"conditionId":key,"slug":row.get::<_,String>("slug")?,
|
||||
"question":row.get::<_,String>("question")?,"description":row.get::<_,String>("rules")?,
|
||||
"resolutionSource":row.get::<_,Option<String>>("source")?,
|
||||
"outcomes":json!([row.get::<_,String>("yes_label")?,row.get::<_,String>("no_label")?]).to_string(),
|
||||
"clobTokenIds":json!([assets::id(&key,"YES"),assets::id(&key,"NO")]).to_string(),
|
||||
"active":row.get::<_,bool>("active")?,"archived":row.get::<_,bool>("archived")?,"enableOrderBook":true,"acceptingOrders":accepts,"closed":!accepts,
|
||||
"orderPriceMinTickSize":tick.number(),"orderMinSize":inventory::decimal(size.into(),inventory::UNIT),
|
||||
"groupItemTitle":row.get::<_,Option<String>>("group_title")?,
|
||||
"bestBid":bid.map(dollars),"bestAsk":ask.map(dollars),"lastTradePrice":last.map(dollars),"outcomePrices":prices,
|
||||
"makerBaseFee":row.get::<_,i64>("maker_bps")?,"takerBaseFee":row.get::<_,Option<i64>>("taker_bps")?,
|
||||
"negRisk":row.get::<_,bool>("neg_risk")?,"feesEnabled":row.get::<_,bool>("fees_enabled")?
|
||||
}))
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_market(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let (column, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("id", id),
|
||||
DirectoryKey::Slug(slug) => ("slug", slug),
|
||||
};
|
||||
let sql = format!(
|
||||
"{} AND w.market=(SELECT market FROM market_directory_ids WHERE {column}=?1)",
|
||||
include_str!("gamma_market.sql")
|
||||
);
|
||||
let record = tx
|
||||
.prepare_cached(&sql)?
|
||||
.query_row([arg], |r| {
|
||||
Ok((market(r)?, r.get::<_, Option<String>>("parent")?))
|
||||
})
|
||||
.optional()?;
|
||||
let Some((mut detail, parent)) = record else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut events = Vec::new();
|
||||
if let Some(parent) = parent {
|
||||
if let Some((_, event)) = event_header(&tx, "id", &parent)? {
|
||||
events.push(event);
|
||||
}
|
||||
}
|
||||
detail["events"] = Value::Array(events);
|
||||
tx.commit()?;
|
||||
Ok(Some(detail))
|
||||
}
|
||||
|
||||
pub fn gamma_event(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let found = match key {
|
||||
DirectoryKey::Id(id) => event_header(&tx, "event_id", &id)?,
|
||||
DirectoryKey::Slug(slug) => event_header(&tx, "slug", &slug)?,
|
||||
};
|
||||
let Some((parent, mut detail)) = found else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut stmt = tx.prepare_cached(concat!(include_str!("gamma_market.sql"),
|
||||
" AND w.market IN (SELECT market FROM sports_markets WHERE event=?1 UNION ALL SELECT market FROM topic_markets WHERE event=?1)
|
||||
ORDER BY COALESCE(t.group_order,0),w.market"))?;
|
||||
let markets = stmt
|
||||
.query_map([parent], market)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
drop(stmt);
|
||||
detail["markets"] = Value::Array(markets);
|
||||
tx.commit()?;
|
||||
Ok(Some(detail))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
SELECT e.id,e.event_id,e.slug,e.title,e.category,
|
||||
COALESCE((
|
||||
SELECT MIN(m.phase NOT IN ('preopen','continuous'))
|
||||
FROM markets m LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
WHERE m.id IN (SELECT market FROM sports_markets WHERE event=e.id
|
||||
UNION ALL SELECT market FROM topic_markets WHERE event=e.id)
|
||||
AND COALESCE(a.role,'')<>'placeholder'
|
||||
),0) AS closed
|
||||
FROM numbered_events e
|
||||
@@ -0,0 +1,250 @@
|
||||
use crate::{
|
||||
assets,
|
||||
gamma_directory::{header, market},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
pub enum DirectoryResource {
|
||||
Events,
|
||||
Markets,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Filters {
|
||||
ids: Vec<i64>,
|
||||
slugs: Vec<String>,
|
||||
conditions: Vec<String>,
|
||||
tokens: Vec<String>,
|
||||
closed: Option<bool>,
|
||||
active: Option<bool>,
|
||||
order: String,
|
||||
ascending: bool,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
fn invalid(field: &str) -> MarketDataError {
|
||||
MarketDataError::Invalid(format!("Invalid directory parameter: {field}"))
|
||||
}
|
||||
|
||||
impl Filters {
|
||||
fn parse(
|
||||
resource: DirectoryResource,
|
||||
fields: &[(String, String)],
|
||||
) -> Result<Self, MarketDataError> {
|
||||
let markets = resource == DirectoryResource::Markets;
|
||||
let mut f = Self {
|
||||
closed: markets.then_some(false),
|
||||
limit: 20,
|
||||
order: "id".into(),
|
||||
..Self::default()
|
||||
};
|
||||
for (key, value) in fields {
|
||||
match key.as_str() {
|
||||
"limit" | "offset" => {
|
||||
let n = value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|n| *n >= 0)
|
||||
.ok_or_else(|| invalid(key))?;
|
||||
if key == "limit" {
|
||||
f.limit = n
|
||||
} else {
|
||||
f.offset = n
|
||||
}
|
||||
}
|
||||
"order" => f.order = value.clone(),
|
||||
"ascending" => f.ascending = value.parse().map_err(|_| invalid(key))?,
|
||||
"active" => f.active = Some(value.parse().map_err(|_| invalid(key))?),
|
||||
"closed" if value.eq_ignore_ascii_case("any") => f.closed = None,
|
||||
"closed" => f.closed = Some(value.parse().map_err(|_| invalid(key))?),
|
||||
"id" => f.ids.push(
|
||||
value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|n| *n > 0)
|
||||
.ok_or_else(|| invalid(key))?,
|
||||
),
|
||||
"slug" if !value.trim().is_empty() => f.slugs.push(value.clone()),
|
||||
"condition_ids" if markets && !value.trim().is_empty() => {
|
||||
f.conditions.push(value.clone())
|
||||
}
|
||||
"clob_token_ids" if markets && !value.trim().is_empty() => {
|
||||
f.tokens.push(value.clone())
|
||||
}
|
||||
_ => return Err(invalid(key)),
|
||||
}
|
||||
}
|
||||
let sizes = [
|
||||
f.ids.len(),
|
||||
f.slugs.len(),
|
||||
f.conditions.len(),
|
||||
f.tokens.len(),
|
||||
];
|
||||
if markets && sizes.iter().any(|n| *n > 100) {
|
||||
return Err(invalid("at most 100 values per identifier filter"));
|
||||
}
|
||||
if markets && f.closed.is_none() && sizes.iter().all(|n| *n == 0) {
|
||||
return Err(invalid("closed=any requires an identifier"));
|
||||
}
|
||||
Ok(f)
|
||||
}
|
||||
|
||||
fn ordering(&self, resource: DirectoryResource) -> Result<String, MarketDataError> {
|
||||
let markets = resource == DirectoryResource::Markets;
|
||||
let id = if markets {
|
||||
"CAST(w.id AS INTEGER)"
|
||||
} else {
|
||||
"e.event_id"
|
||||
};
|
||||
let mut cols = Vec::new();
|
||||
for field in self.order.split(',').map(str::trim) {
|
||||
cols.push(match field {
|
||||
"id" => id,
|
||||
"slug" if markets => "w.slug",
|
||||
"slug" => "e.slug",
|
||||
"question" if markets => "w.question",
|
||||
"title" if !markets => "e.title",
|
||||
_ => return Err(invalid("order")),
|
||||
});
|
||||
}
|
||||
if !cols.contains(&id) {
|
||||
cols.push(id)
|
||||
}
|
||||
let dir = if self.ascending { "ASC" } else { "DESC" };
|
||||
Ok(cols
|
||||
.iter()
|
||||
.map(|col| format!("{col} {dir}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", "))
|
||||
}
|
||||
}
|
||||
|
||||
const MARKET_FILTER: &str = "
|
||||
AND (?1='[]' OR CAST(w.id AS INTEGER) IN (SELECT value FROM json_each(?1)))
|
||||
AND (?2='[]' OR w.slug IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3='[]' OR w.market IN (SELECT value FROM json_each(?3)))
|
||||
AND (?4 IS NULL OR w.market IN (SELECT value FROM json_each(?4)))
|
||||
AND (?5 IS NULL OR (m.phase NOT IN ('preopen','continuous'))=?5)
|
||||
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)";
|
||||
const EVENT_FILTER: &str = "
|
||||
WHERE (?1='[]' OR e.event_id IN (SELECT value FROM json_each(?1)))
|
||||
AND (?2='[]' OR e.slug IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3 IS NULL OR e.closed=?3)";
|
||||
|
||||
fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
// A supplied set containing only foreign tokens must match nothing.
|
||||
let token_markets = (!f.tokens.is_empty()).then(|| {
|
||||
let keys: Vec<_> = f
|
||||
.tokens
|
||||
.iter()
|
||||
.filter_map(|token| assets::parse_id(token).ok().map(|(_, market)| market))
|
||||
.collect();
|
||||
json!(keys).to_string()
|
||||
});
|
||||
let sql = format!(
|
||||
"{}{MARKET_FILTER} ORDER BY {order} LIMIT ?6 OFFSET ?7",
|
||||
include_str!("gamma_market.sql")
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt
|
||||
.query_map(
|
||||
params![
|
||||
json!(f.ids).to_string(),
|
||||
json!(f.slugs).to_string(),
|
||||
json!(f.conditions).to_string(),
|
||||
token_markets,
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset,
|
||||
f.active
|
||||
],
|
||||
|r| Ok((market(r)?, r.get::<_, Option<String>>("parent")?)),
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let parents: Vec<_> = rows.iter().filter_map(|(_, p)| p.as_deref()).collect();
|
||||
let sql = concat!(
|
||||
include_str!("gamma_events.sql"),
|
||||
" WHERE e.id IN (SELECT value FROM json_each(?1))"
|
||||
);
|
||||
let mut headers = db.prepare_cached(sql)?;
|
||||
let events = headers
|
||||
.query_map([json!(parents).to_string()], header)?
|
||||
.collect::<rusqlite::Result<HashMap<_, _>>>()?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(mut row, parent)| {
|
||||
row["events"] = json!(parent
|
||||
.and_then(|key| events.get(&key))
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>());
|
||||
row
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn events(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
let sql = format!(
|
||||
"SELECT * FROM ({}) e {EVENT_FILTER} ORDER BY {order} LIMIT ?4 OFFSET ?5",
|
||||
include_str!("gamma_events.sql")
|
||||
);
|
||||
let mut stmt = db.prepare_cached(&sql)?;
|
||||
let rows = stmt
|
||||
.query_map(
|
||||
params![
|
||||
json!(f.ids).to_string(),
|
||||
json!(f.slugs).to_string(),
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset
|
||||
],
|
||||
header,
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let parents: Vec<_> = rows.iter().map(|(id, _)| id.as_str()).collect();
|
||||
let mut children: HashMap<String, Vec<Value>> = HashMap::new();
|
||||
let mut stmt=db.prepare_cached(concat!(include_str!("gamma_market.sql"),"
|
||||
AND w.market IN (SELECT market FROM sports_markets WHERE event IN (SELECT value FROM json_each(?1))
|
||||
UNION ALL SELECT market FROM topic_markets WHERE event IN (SELECT value FROM json_each(?1)))
|
||||
ORDER BY COALESCE(t.group_order,0),w.market"))?;
|
||||
let mut members = stmt.query([json!(parents).to_string()])?;
|
||||
while let Some(row) = members.next()? {
|
||||
children
|
||||
.entry(row.get("parent")?)
|
||||
.or_default()
|
||||
.push(market(row)?);
|
||||
}
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(id, mut row)| {
|
||||
row["markets"] = Value::Array(children.remove(&id).unwrap_or_default());
|
||||
row
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_list(
|
||||
&self,
|
||||
resource: DirectoryResource,
|
||||
fields: &[(String, String)],
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
let f = Filters::parse(resource, fields)?;
|
||||
let order = f.ordering(resource)?;
|
||||
// Event publication is independent of each child market.
|
||||
if (resource == DirectoryResource::Events && f.active == Some(false)) || f.limit == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let page = match resource {
|
||||
DirectoryResource::Events => events(&tx, &f, &order)?,
|
||||
DirectoryResource::Markets => markets(&tx, &f, &order)?,
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
SELECT w.market, w.id, w.slug, w.question, w.yes_label, w.no_label, m.rules, m.phase, m.winner, quotes.yes_bid, quotes.yes_ask,
|
||||
yes_trade.price AS yes_last, no_trade.price AS no_last,
|
||||
COALESCE(s.source,t.source) AS source, COALESCE(s.event,t.event) AS parent,
|
||||
COALESCE(a.name,t.group_title) AS group_title,
|
||||
tick.step_micros, minimum.microshares, member.market IS NOT NULL AS neg_risk,
|
||||
COALESCE(fee.rate_ppm,0)>0 AS fees_enabled, fee.maker_bps, fee.taker_bps, COALESCE(v.active,1) AS active, COALESCE(v.archived,0) AS archived
|
||||
FROM market_wire_metadata w
|
||||
JOIN markets m ON m.id=w.market
|
||||
LEFT JOIN market_visibility v ON v.market=w.market
|
||||
LEFT JOIN sports_markets s ON s.market=w.market
|
||||
LEFT JOIN topic_markets t ON t.market=w.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=w.market
|
||||
LEFT JOIN market_tick_sizes tick ON tick.market=w.market
|
||||
LEFT JOIN market_minimum_sizes minimum ON minimum.market=w.market
|
||||
LEFT JOIN neg_risk_members member ON member.market=w.market
|
||||
JOIN market_fee_terms fee ON fee.market=w.market
|
||||
LEFT JOIN quote_events quotes ON quotes.seq=(SELECT MAX(seq) FROM quote_events WHERE market=w.market)
|
||||
LEFT JOIN last_asset_trades yes_trade ON yes_trade.market=w.market AND yes_trade.outcome='YES'
|
||||
LEFT JOIN last_asset_trades no_trade ON no_trade.market=w.market AND no_trade.outcome='NO'
|
||||
WHERE COALESCE(a.role,'')<>'placeholder'
|
||||
@@ -0,0 +1,79 @@
|
||||
use crate::{
|
||||
book::{self, CancelReason},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Beat {
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
heartbeat_id: String,
|
||||
}
|
||||
|
||||
impl Beat {
|
||||
pub(crate) fn accept(self, tx: &Transaction) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(key) = &self.key_id {
|
||||
identifier(key)?;
|
||||
}
|
||||
let key = self.key_id.as_deref().unwrap_or("");
|
||||
let expected: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT heartbeat_id FROM order_heartbeats WHERE account=? AND key_id=?",
|
||||
params![self.account, key],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let expected = expected.as_deref().unwrap_or("");
|
||||
if expected != self.heartbeat_id {
|
||||
return Ok(json!({"error_msg":"Invalid Heartbeat ID","heartbeat_id":expected}));
|
||||
}
|
||||
let (id, deadline): (String,i64) = tx.query_row(
|
||||
"INSERT INTO order_heartbeats(account,key_id,heartbeat_id,deadline_ms)
|
||||
VALUES(?1,?2,lower(hex(randomblob(16))),CAST(unixepoch('subsec')*1000 AS INTEGER)+10000)
|
||||
ON CONFLICT(account,key_id) DO UPDATE SET heartbeat_id=excluded.heartbeat_id,deadline_ms=excluded.deadline_ms
|
||||
RETURNING heartbeat_id,deadline_ms",
|
||||
params![self.account,key],
|
||||
|r| Ok((r.get(0)?,r.get(1)?)),
|
||||
)?;
|
||||
Ok(json!({"heartbeat_id":id,"deadline_ms":deadline}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_key(tx: &Transaction, order: i64, key: Option<&str>) -> Result<()> {
|
||||
if let Some(key) = key {
|
||||
identifier(key)?;
|
||||
tx.execute("INSERT INTO order_keys VALUES(?,?)", params![order, key])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn expire(tx: &Transaction) -> Result<()> {
|
||||
// Capture registrations at one instant. A session becoming due during
|
||||
// the refunds stays registered until the next pass.
|
||||
let mut stmt = tx.prepare(
|
||||
"DELETE FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
RETURNING account,key_id",
|
||||
)?;
|
||||
let due = stmt
|
||||
.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for (account, key) in due {
|
||||
let mut orders = tx.prepare_cached(
|
||||
"SELECT o.seq FROM orders o LEFT JOIN order_keys k ON k.order_seq=o.seq
|
||||
WHERE o.account=? AND o.status='live' AND COALESCE(k.key_id,'')=? ORDER BY o.seq",
|
||||
)?;
|
||||
let ids = orders
|
||||
.query_map(params![account, key], |r| r.get::<_, i64>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for order in ids {
|
||||
book::release(tx, order, &account, CancelReason::Cancelled)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use crate::{assets, portfolio, validation::identifier};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Number, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum Basis {
|
||||
#[default]
|
||||
Net,
|
||||
Gross,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Page {
|
||||
markets: Vec<String>,
|
||||
basis: Basis,
|
||||
min_balance: Number,
|
||||
limit: u32,
|
||||
offset: i64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
market: Option<String>,
|
||||
markets: Option<Vec<String>>,
|
||||
basis: Option<Basis>,
|
||||
min_balance: Option<Number>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
// Round the inclusive threshold up to the first representable microshare.
|
||||
// None means that even the largest SQLite position falls below the threshold.
|
||||
fn minimum_units(number: &Number) -> Result<Option<i64>> {
|
||||
let raw = number.to_string();
|
||||
let (base, exponent) = raw.split_once(['e', 'E']).unwrap_or((&raw, "0"));
|
||||
let digits = base.trim_start_matches('-').replace('.', "");
|
||||
let digits = digits.trim_start_matches('0');
|
||||
if digits.is_empty() {
|
||||
return Ok(Some(0));
|
||||
}
|
||||
ensure!(!base.starts_with('-'), "negative holder threshold");
|
||||
let power = exponent
|
||||
.parse::<i64>()
|
||||
.unwrap_or(if exponent.starts_with('-') {
|
||||
i64::MIN
|
||||
} else {
|
||||
i64::MAX
|
||||
});
|
||||
let fraction = base.split_once('.').map_or(0, |(_, f)| f.len()) as i64;
|
||||
let places = (digits.len() as i64)
|
||||
.saturating_sub(fraction)
|
||||
.saturating_add(6)
|
||||
.saturating_add(power);
|
||||
if places <= 0 {
|
||||
return Ok(Some(1));
|
||||
}
|
||||
if places > 19 {
|
||||
return Ok(None);
|
||||
}
|
||||
let places = places as usize;
|
||||
let split = places.min(digits.len());
|
||||
let head = digits[..split].parse::<i128>()? * 10_i128.pow((places - split) as u32);
|
||||
let round_up = digits[split..].bytes().any(|b| b != b'0');
|
||||
Ok(i64::try_from(head + i128::from(round_up)).ok())
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn page(self) -> Result<Page> {
|
||||
let markets = match (self.market, self.markets) {
|
||||
(Some(m), None) => Some(vec![m]),
|
||||
(None, ms) => ms,
|
||||
_ => anyhow::bail!("specify market or markets"),
|
||||
}
|
||||
.map(|mut ms| {
|
||||
ms.sort();
|
||||
ms.dedup();
|
||||
ms
|
||||
});
|
||||
let page = if let Some(cursor) = self.cursor {
|
||||
let page: Page = serde_json::from_str(&cursor).context("invalid holders cursor")?;
|
||||
ensure!(
|
||||
markets.as_ref().map_or(true, |ms| ms == &page.markets)
|
||||
&& self.basis.map_or(true, |v| v == page.basis),
|
||||
"holders cursor filters differ"
|
||||
);
|
||||
if let Some(minimum) = &self.min_balance {
|
||||
ensure!(
|
||||
minimum_units(minimum)? == minimum_units(&page.min_balance)?,
|
||||
"holders cursor filters differ"
|
||||
);
|
||||
}
|
||||
page
|
||||
} else {
|
||||
Page {
|
||||
markets: markets.context("market selector required")?,
|
||||
basis: self.basis.unwrap_or_default(),
|
||||
min_balance: self.min_balance.unwrap_or_else(|| 0.into()),
|
||||
limit: self.limit.unwrap_or(100),
|
||||
offset: 0,
|
||||
}
|
||||
};
|
||||
ensure!(
|
||||
(1..=20).contains(&page.markets.len()) && page.markets.windows(2).all(|w| w[0] < w[1]),
|
||||
"expected 1 to 20 distinct markets"
|
||||
);
|
||||
for m in &page.markets {
|
||||
identifier(m)?;
|
||||
}
|
||||
ensure!(
|
||||
page.offset >= 0 && page.limit <= 1000,
|
||||
"invalid holders window"
|
||||
);
|
||||
if page.basis == Basis::Gross {
|
||||
ensure!(
|
||||
page.markets.len() == 1 && page.limit <= 100,
|
||||
"gross view accepts one market and at most 100 rows per outcome"
|
||||
);
|
||||
}
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let mut page = self.page()?;
|
||||
let minimum = minimum_units(&page.min_balance)?;
|
||||
if page.limit == 0 || minimum.is_none() {
|
||||
return Ok(json!({"basis":page.basis,"data":[],"next_cursor":null}));
|
||||
}
|
||||
let end = page
|
||||
.offset
|
||||
.checked_add(i64::from(page.limit))
|
||||
.context("holders offset overflow")?;
|
||||
let probe = end.checked_add(1).context("holders offset overflow")?;
|
||||
let mut data = Vec::new();
|
||||
let mut more = false;
|
||||
let mut stmt = db.prepare_cached(include_str!("holders.sql"))?;
|
||||
let gross = page.basis == Basis::Gross;
|
||||
for market in &page.markets {
|
||||
let mut rows = stmt.query(params![market, gross, minimum, page.offset, probe])?;
|
||||
let mut groups: BTreeMap<String, Vec<(String, i64, i64)>> = BTreeMap::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
let rank: i64 = r.get(3)?;
|
||||
if rank > end {
|
||||
more = true;
|
||||
continue;
|
||||
}
|
||||
groups
|
||||
.entry(r.get(1)?)
|
||||
.or_default()
|
||||
.push((r.get(0)?, r.get(2)?, rank));
|
||||
}
|
||||
for outcome in ["YES", "NO"] {
|
||||
let Some(entries) = groups.remove(outcome) else {
|
||||
continue;
|
||||
};
|
||||
let mark = if gross {
|
||||
let (phase, payout): (String, Option<i64>) = db.query_row(
|
||||
"SELECT phase,payout_per_share FROM position_units
|
||||
WHERE market=?1 AND account=?2 AND outcome=?3",
|
||||
params![market, &entries[0].0, outcome],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
portfolio::price(db, market, outcome, &phase, payout)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let holders: Vec<_> = entries
|
||||
.into_iter()
|
||||
.map(|(account, amount, rank)| {
|
||||
let mut holder = json!({"account":account,"amount":crate::inventory::decimal(amount.into(),crate::inventory::UNIT),"rank":rank});
|
||||
if gross {
|
||||
let (price, source) = mark.unzip();
|
||||
holder["current_price_micros"] = json!(price);
|
||||
holder["price_source"] = json!(source);
|
||||
holder["current_value_micros"] =
|
||||
json!(portfolio::holding_value(amount, price));
|
||||
}
|
||||
holder
|
||||
})
|
||||
.collect();
|
||||
data.push(json!({"market":market,"asset_id":assets::id(market,outcome),"outcome":outcome,"holders":holders}));
|
||||
}
|
||||
}
|
||||
page.offset = end;
|
||||
let cursor = if more {
|
||||
Some(serde_json::to_string(&page)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"basis":page.basis,"data":data,"next_cursor":cursor}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
WITH balances AS MATERIALIZED (
|
||||
SELECT account,outcome,available+reserved AS size
|
||||
FROM position_units WHERE market=?1
|
||||
), wallets AS (
|
||||
SELECT account,
|
||||
MAX(CASE WHEN outcome='YES' THEN size ELSE 0 END) AS yes,
|
||||
MAX(CASE WHEN outcome='NO' THEN size ELSE 0 END) AS no
|
||||
FROM balances WHERE size>0 AND NOT ?2 GROUP BY account
|
||||
), served AS (
|
||||
SELECT account,CASE WHEN yes>=no THEN 'YES' ELSE 'NO' END AS outcome,ABS(yes-no) AS amount
|
||||
FROM wallets
|
||||
UNION ALL
|
||||
SELECT account,outcome,size FROM balances WHERE ?2 AND size>0
|
||||
), ranked AS (
|
||||
SELECT account,outcome,amount,
|
||||
ROW_NUMBER() OVER (PARTITION BY outcome ORDER BY amount DESC,account) AS ordinal
|
||||
FROM served WHERE amount>=?3
|
||||
)
|
||||
SELECT account,outcome,amount,ordinal FROM ranked
|
||||
WHERE ordinal>?4 AND ordinal<=?5 ORDER BY outcome,ordinal
|
||||
@@ -0,0 +1,153 @@
|
||||
use crate::{
|
||||
ledger,
|
||||
validation::{identifier, phase},
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde_json::{json, Number, Value};
|
||||
|
||||
pub(crate) const UNIT: i64 = 1_000_000;
|
||||
|
||||
// Render a fixed-point amount as a JSON number without passing through f64.
|
||||
// All callers use a power of ten as the scale.
|
||||
pub(crate) fn decimal(value: i128, scale: i64) -> Number {
|
||||
let scale = i128::from(scale);
|
||||
if value % scale == 0 {
|
||||
return Number::from_i128(value / scale).expect("integer JSON number");
|
||||
}
|
||||
let sign = if value < 0 { "-" } else { "" };
|
||||
let value = value.unsigned_abs();
|
||||
let width = scale.ilog10() as usize;
|
||||
let scale = scale as u128;
|
||||
format!("{sign}{}.{:0width$}", value / scale, value % scale)
|
||||
.trim_end_matches('0')
|
||||
.parse()
|
||||
.expect("fixed-point JSON number")
|
||||
}
|
||||
|
||||
pub(crate) fn backing(tx: &Transaction, market: &str, delta: i64) -> Result<()> {
|
||||
let old: i64 = tx.query_row(
|
||||
"SELECT micros FROM market_backing WHERE market=?",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let new = old
|
||||
.checked_add(delta)
|
||||
.filter(|v| *v >= 0)
|
||||
.ok_or_else(|| anyhow::anyhow!("insufficient collateral or balance overflow"))?;
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=? WHERE id=?",
|
||||
params![new / 10000, market],
|
||||
)?;
|
||||
tx.execute("INSERT INTO collateral_remainders VALUES(?,?) ON CONFLICT(market) DO UPDATE SET micros=excluded.micros",params![market,new%10000])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn position(
|
||||
tx: &Transaction,
|
||||
account: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
delta: i64,
|
||||
) -> Result<()> {
|
||||
if delta % UNIT == 0 {
|
||||
return ledger::position(tx, account, market, outcome, delta / UNIT);
|
||||
}
|
||||
let old:i64=tx.query_row("SELECT COALESCE((SELECT micros FROM position_remainders WHERE account=? AND market=? AND outcome=?),0)",
|
||||
params![account,market,outcome],|r|r.get(0))?;
|
||||
let rest = old + delta.rem_euclid(UNIT);
|
||||
ledger::position(
|
||||
tx,
|
||||
account,
|
||||
market,
|
||||
outcome,
|
||||
delta.div_euclid(UNIT) + rest / UNIT,
|
||||
)?;
|
||||
tx.execute("INSERT INTO position_remainders VALUES(?,?,?,?) ON CONFLICT(account,market,outcome) DO UPDATE SET micros=excluded.micros",
|
||||
params![account,market,outcome,rest%UNIT])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn movement(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
account: &str,
|
||||
target: &str,
|
||||
kind: &str,
|
||||
shares: i64,
|
||||
cash: i64,
|
||||
) -> Result<()> {
|
||||
let (market, group_id) = if kind == "CONVERSION" {
|
||||
(None, Some(target))
|
||||
} else {
|
||||
(Some(target), None)
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta,at_ms)
|
||||
VALUES(?,?,?,?,?,?,?,CAST(unixepoch('subsec')*1000 AS INTEGER))",
|
||||
params![request, account, kind, market, group_id, shares / UNIT, cash / 10000],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO precise_movements VALUES(?,?,?,?)",
|
||||
params![request, account, shares, cash],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn quantity_units(qty: Option<i64>, qty_micros: Option<i64>) -> Result<i64> {
|
||||
Ok(match (qty, qty_micros) {
|
||||
(Some(q), None) => {
|
||||
crate::validation::amount(q)?;
|
||||
q * UNIT
|
||||
}
|
||||
(None, Some(u)) if (1..=1_000_000_000 * UNIT).contains(&u) => u,
|
||||
_ => anyhow::bail!(
|
||||
"provide exactly one positive qty or qty_micros within the quantity limit"
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn pairs(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
account: &str,
|
||||
market: &str,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
split: bool,
|
||||
) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
phase(
|
||||
tx,
|
||||
market,
|
||||
if split {
|
||||
&["preopen", "continuous"][..]
|
||||
} else {
|
||||
&["preopen", "continuous", "closed"][..]
|
||||
},
|
||||
)?;
|
||||
let units = quantity_units(qty, qty_micros)?;
|
||||
let delta = if split { units } else { -units };
|
||||
ledger::cash_micros(tx, account, -delta)?;
|
||||
for outcome in ["YES", "NO"] {
|
||||
position(tx, account, market, outcome, delta)?;
|
||||
}
|
||||
backing(tx, market, delta)?;
|
||||
let mut result = json!({"pairs":decimal(i128::from(units),UNIT)});
|
||||
if !split {
|
||||
result["released_cents"] = json!(decimal(i128::from(units), 10000));
|
||||
}
|
||||
if qty_micros.is_some() {
|
||||
movement(
|
||||
tx,
|
||||
request,
|
||||
account,
|
||||
market,
|
||||
if split { "SPLIT" } else { "MERGE" },
|
||||
units,
|
||||
-delta,
|
||||
)?;
|
||||
result["pairs_micros"] = json!(units);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use crate::{
|
||||
book::{self, CancelReason},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn reschedule(
|
||||
tx: &Transaction,
|
||||
event: &str,
|
||||
previous_ms: i64,
|
||||
scheduled_at_ms: i64,
|
||||
) -> Result<Value> {
|
||||
identifier(event)?;
|
||||
ensure!(scheduled_at_ms >= 0, "invalid sports start time");
|
||||
let changed = tx.execute(
|
||||
"UPDATE sports_kickoffs SET due_ms=?1 WHERE event=?2 AND due_ms=?3 AND cleared_at_ms IS NULL",
|
||||
params![scheduled_at_ms, event, previous_ms],
|
||||
)?;
|
||||
ensure!(changed == 1, "no pending kickoff at the specified time");
|
||||
tx.execute(
|
||||
"UPDATE events SET scheduled_at_ms=? WHERE id=?",
|
||||
params![scheduled_at_ms, event],
|
||||
)?;
|
||||
clear_due(tx)?;
|
||||
Ok(json!({"event":event,"scheduled_at_ms":scheduled_at_ms}))
|
||||
}
|
||||
|
||||
pub(crate) fn clear_due(tx: &Transaction) -> Result<()> {
|
||||
let now: i64 = tx.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut pending = tx.prepare(
|
||||
"SELECT event FROM sports_kickoffs WHERE cleared_at_ms IS NULL AND due_ms<=? ORDER BY due_ms,event",
|
||||
)?;
|
||||
let events = pending
|
||||
.query_map([now], |r| r.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for event in events {
|
||||
let mut active = tx.prepare(
|
||||
"SELECT o.seq,o.account FROM sports_markets m JOIN orders o ON o.market=m.market
|
||||
WHERE m.event=? AND o.status='live' ORDER BY o.seq",
|
||||
)?;
|
||||
let orders = active
|
||||
.query_map([&event], |r| {
|
||||
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for (seq, owner) in &orders {
|
||||
book::release(tx, *seq, owner, CancelReason::Cancelled)?;
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE sports_kickoffs SET cleared_at_ms=?,cancelled_orders=? WHERE event=?",
|
||||
params![now, orders.len() as i64, event],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS sports_kickoffs (
|
||||
event TEXT PRIMARY KEY REFERENCES events,
|
||||
due_ms INTEGER NOT NULL,
|
||||
cleared_at_ms INTEGER,
|
||||
cancelled_orders INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pending_kickoffs ON sports_kickoffs(due_ms,event)
|
||||
WHERE cleared_at_ms IS NULL;
|
||||
|
||||
-- Legacy orders have no reliable pre-match/in-play marker. Arm only future fixtures.
|
||||
INSERT OR IGNORE INTO sports_kickoffs(event,due_ms)
|
||||
SELECT id,scheduled_at_ms FROM events WHERE scheduled_at_ms>CAST(unixepoch('subsec')*1000 AS INTEGER);
|
||||
CREATE TRIGGER IF NOT EXISTS register_kickoff AFTER INSERT ON events BEGIN
|
||||
INSERT INTO sports_kickoffs(event,due_ms) VALUES(NEW.id,NEW.scheduled_at_ms);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,50 @@
|
||||
use crate::{assets, inventory, tick_size, Exchange, MarketDataError};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
/// For a paired fill, the other outcome sees the complementary side of the taker.
|
||||
pub(crate) fn taker_side(
|
||||
outcome: &str,
|
||||
taker_outcome: Option<&str>,
|
||||
side: Option<&str>,
|
||||
) -> Option<&'static str> {
|
||||
match (taker_outcome? == outcome, side?) {
|
||||
(true, "buy") | (false, "sell") => Some("BUY"),
|
||||
(true, "sell") | (false, "buy") => Some("SELL"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
/// Return one latest trade per asset, sorted by token ID, from one SQLite snapshot.
|
||||
pub fn last_trade_prices(&self, tokens: &[String]) -> Result<Vec<Value>, MarketDataError> {
|
||||
if tokens.len() > 500 {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"expected at most 500 tokens".into(),
|
||||
));
|
||||
}
|
||||
let mut tokens: Vec<&str> = tokens.iter().map(String::as_str).collect();
|
||||
tokens.sort_unstable();
|
||||
tokens.dedup();
|
||||
let assets = tokens
|
||||
.iter()
|
||||
.map(|token| assets::parse_id(token))
|
||||
.collect::<anyhow::Result<Vec<_>>>()
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let input = serde_json::to_string(&assets).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut stmt = self.db.prepare_cached(include_str!("last_trades.sql"))?;
|
||||
let mut rows = stmt.query([input])?;
|
||||
let mut result = Vec::with_capacity(tokens.len());
|
||||
for (token, (outcome, _)) in tokens.iter().zip(assets) {
|
||||
let row = rows.next()?.ok_or(MarketDataError::Unavailable)?;
|
||||
let Some(price) = row.get::<_, Option<i64>>(0)? else {
|
||||
continue;
|
||||
};
|
||||
let taker: Option<String> = row.get(1)?;
|
||||
let side: Option<String> = row.get(2)?;
|
||||
let price = inventory::decimal(price.into(), tick_size::PAR).to_string();
|
||||
result.push(json!({"token_id":token, "price":price,
|
||||
"side":taker_side(outcome,taker.as_deref(),side.as_deref()).unwrap_or("")}));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
SELECT l.price,t.outcome,t.side
|
||||
FROM json_each(?1) AS asset
|
||||
LEFT JOIN last_asset_trades l ON l.market=json_extract(asset.value,'$[1]')
|
||||
AND l.outcome=json_extract(asset.value,'$[0]')
|
||||
LEFT JOIN execution_context c ON c.execution=l.execution
|
||||
LEFT JOIN orders t ON t.seq=c.taker_order
|
||||
ORDER BY asset.key
|
||||
@@ -1,5 +1,6 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
ensure!(
|
||||
@@ -12,6 +13,41 @@ pub(crate) fn cash(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Keep the legacy whole-cent column and the sub-cent remainder canonical.
|
||||
pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result<()> {
|
||||
if delta % 10000 == 0 {
|
||||
return cash(tx, account, delta / 10000);
|
||||
}
|
||||
let old: i64 = tx.query_row(
|
||||
"SELECT COALESCE((SELECT micros FROM cash_remainders WHERE account=?),0)",
|
||||
[account],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let remainder = old + delta.rem_euclid(10000);
|
||||
cash(tx, account, delta.div_euclid(10000) + remainder / 10000)?;
|
||||
tx.execute("INSERT INTO cash_remainders(account,micros) VALUES(?,?) ON CONFLICT(account) DO UPDATE SET micros=excluded.micros",
|
||||
params![account, remainder % 10000])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
crate::validation::identifier(account)?;
|
||||
let (cash, remainder, reserved): (i64, i64, i64) = db.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0),
|
||||
(SELECT COALESCE(SUM(price*remaining),0) FROM orders
|
||||
WHERE account=a.id AND side='buy' AND status='live')
|
||||
FROM accounts a LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
let available = i128::from(cash) * 10000 + i128::from(remainder);
|
||||
let reserved = i128::from(reserved);
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn position(
|
||||
tx: &Transaction,
|
||||
account: &str,
|
||||
|
||||
+220
-3
@@ -1,21 +1,48 @@
|
||||
mod account_orders;
|
||||
mod account_trades;
|
||||
mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod fees;
|
||||
mod gamma_directory;
|
||||
mod gamma_list;
|
||||
mod heartbeat;
|
||||
mod holders;
|
||||
mod twap;
|
||||
mod validation;
|
||||
mod volume;
|
||||
use validation::identifier;
|
||||
mod book;
|
||||
mod book_snapshot;
|
||||
mod cancellation;
|
||||
mod clarifications;
|
||||
mod clob_market;
|
||||
mod command;
|
||||
mod inventory;
|
||||
mod kickoff;
|
||||
mod last_trades;
|
||||
mod ledger;
|
||||
mod lots;
|
||||
mod market;
|
||||
mod market_amounts;
|
||||
mod market_stream;
|
||||
mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod portfolio;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
mod quotes;
|
||||
mod resident;
|
||||
mod resolution;
|
||||
mod tick_changes;
|
||||
mod tick_size;
|
||||
mod token_aliases;
|
||||
mod token_directory;
|
||||
use resident::Books;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
@@ -23,36 +50,205 @@ use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, Transacti
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
pub use assets::parse_id as parse_asset_id;
|
||||
pub use depth_feed::MarketPage;
|
||||
pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
pub use quotes::{PriceQueryError, PriceRequest, PriceSide};
|
||||
pub use resolution::http::ResolutionQuery;
|
||||
pub use token_directory::TokenDirectoryQuery;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum MarketDataError {
|
||||
Invalid(String),
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
impl From<rusqlite::Error> for MarketDataError {
|
||||
fn from(_: rusqlite::Error) -> Self {
|
||||
Self::Unavailable
|
||||
}
|
||||
}
|
||||
|
||||
pub type HistoryError = MarketDataError;
|
||||
|
||||
pub struct Exchange {
|
||||
db: Connection,
|
||||
books: Books,
|
||||
}
|
||||
impl Exchange {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let db = Connection::open(path)?;
|
||||
let mut db = Connection::open(path)?;
|
||||
db.busy_timeout(Duration::from_secs(10))?;
|
||||
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
||||
db.execute_batch(include_str!("schema.sql"))?;
|
||||
let submissions_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='order_submissions')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !submissions_ready {
|
||||
db.execute_batch(include_str!("order_submission_schema.sql"))?;
|
||||
}
|
||||
let directory_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='event_directory_ids')",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !directory_ready {
|
||||
db.execute_batch(include_str!("event_directory_schema.sql"))?;
|
||||
}
|
||||
let kickoff_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='sports_kickoffs')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !kickoff_ready {
|
||||
db.execute_batch(include_str!("kickoff_schema.sql"))?;
|
||||
}
|
||||
let activity_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='record_wallet_receipt')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !activity_ready {
|
||||
db.execute_batch(include_str!("activity_schema.sql"))?;
|
||||
}
|
||||
let quotes_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='quote_events')",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if !quotes_ready {
|
||||
db.execute_batch(include_str!("quote_schema.sql"))?;
|
||||
}
|
||||
let history_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='chart_market_listed')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !history_ready {
|
||||
db.execute_batch(include_str!("prices_history/chart_schema.sql"))?;
|
||||
}
|
||||
let marks_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='last_asset_trades')",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !marks_ready {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let snapshot_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='book_snapshot_times')", [], |r| r.get(0))?;
|
||||
if !snapshot_ready {
|
||||
db.execute_batch(include_str!("book_snapshot_schema.sql"))?;
|
||||
}
|
||||
let depth_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='depth_batches')", [], |r| r.get(0))?;
|
||||
if !depth_ready {
|
||||
db.execute_batch(include_str!("depth_schema.sql"))?;
|
||||
}
|
||||
let stream_ready:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='market_stream_events')",[],|r|r.get(0))?;
|
||||
if !stream_ready {
|
||||
db.execute_batch(include_str!("market_stream_schema.sql"))?;
|
||||
}
|
||||
let lifecycle_ready:bool=db.query_row("SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='market_lifecycle_frames')",[],|r|r.get(0))?;
|
||||
if !lifecycle_ready {
|
||||
db.execute_batch(include_str!("lifecycle_schema.sql"))?;
|
||||
}
|
||||
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(Self { db, books })
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
/// Run expiry and synchronize the resident book while the transport is idle.
|
||||
pub fn maintain(&mut self) -> Result<()> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Time until the next pending GTD stops trading, measured on the database clock.
|
||||
pub fn next_gtd_expiry(&self) -> Result<Option<Duration>> {
|
||||
let (first, now): (Option<i64>, i64) = self.db.query_row(
|
||||
"SELECT MIN(expiration), CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
FROM order_deadlines WHERE pending=1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
Ok(first.map(|stated| {
|
||||
let cutoff = stated.saturating_sub(60).saturating_mul(1000);
|
||||
Duration::from_millis(cutoff.saturating_sub(now).max(0) as u64)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read requested outcome books in one consistent database and resident-book snapshot.
|
||||
pub fn public_books(&mut self, tokens: &[String]) -> Result<Vec<Value>> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let books = book_snapshot::read_many(&tx, &mut self.books, tokens)?;
|
||||
tx.commit()?;
|
||||
Ok(books)
|
||||
}
|
||||
|
||||
pub fn market_stream_page(&mut self, market: &str, after: Option<i64>) -> Result<MarketPage> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let page = market_stream::page(&tx, &mut self.books, market, after)?;
|
||||
tx.commit()?;
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
/// Start at the current catalog boundary, or read announcements after a saved cursor.
|
||||
pub fn market_discovery_page(&self, after: Option<i64>) -> Result<MarketPage> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let page = market_stream::discovery(&tx, after)?;
|
||||
tx.commit()?;
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, mut payload: Value) -> Result<Value> {
|
||||
if payload["op"].as_str() == Some("heartbeat") {
|
||||
payload
|
||||
.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("op");
|
||||
let beat: heartbeat::Beat = serde_json::from_value(payload)?;
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
||||
let response = beat.accept(&tx)?;
|
||||
tx.commit()?;
|
||||
return Ok(response);
|
||||
}
|
||||
if matches!(
|
||||
payload["op"].as_str(),
|
||||
Some(
|
||||
"assets"
|
||||
| "estimate"
|
||||
| "limit_amounts"
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
| "quote"
|
||||
| "price"
|
||||
| "prices"
|
||||
| "quote_history"
|
||||
| "volume"
|
||||
| "book_feed"
|
||||
| "clob_book"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "holders"
|
||||
| "balance"
|
||||
| "portfolio_value"
|
||||
| "open_interest"
|
||||
| "trades"
|
||||
| "public_trades"
|
||||
| "activity"
|
||||
| "resolution"
|
||||
)
|
||||
) {
|
||||
@@ -69,12 +265,20 @@ impl Exchange {
|
||||
let mut state = Map::new();
|
||||
for table in [
|
||||
"accounts",
|
||||
"cash_remainders",
|
||||
"position_remainders",
|
||||
"collateral_remainders",
|
||||
"settlement_dust",
|
||||
"execution_fees",
|
||||
"markets",
|
||||
"positions",
|
||||
"orders",
|
||||
"fills",
|
||||
"paired_fills",
|
||||
"neg_risk_groups",
|
||||
"neg_risk_conversion_fees",
|
||||
"neg_risk_reserve_remainders",
|
||||
"augmented_results",
|
||||
] {
|
||||
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
|
||||
let names: Vec<String> =
|
||||
@@ -86,6 +290,18 @@ impl Exchange {
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let v = match row.get_ref(i)? {
|
||||
ValueRef::Null => Value::Null,
|
||||
ValueRef::Integer(n)
|
||||
if matches!(table, "orders" | "fills" | "paired_fills")
|
||||
&& matches!(name.as_str(), "quantity" | "remaining") =>
|
||||
{
|
||||
json!(lots::display(n))
|
||||
}
|
||||
ValueRef::Integer(n)
|
||||
if matches!(table, "orders" | "fills" | "paired_fills")
|
||||
&& matches!(name.as_str(), "price" | "yes_price") =>
|
||||
{
|
||||
json!(crate::inventory::decimal(n.into(), 100))
|
||||
}
|
||||
ValueRef::Integer(n) => json!(n),
|
||||
ValueRef::Text(s) => json!(std::str::from_utf8(s)?),
|
||||
_ => anyhow::bail!("unexpected column type"),
|
||||
@@ -124,11 +340,12 @@ impl Exchange {
|
||||
let command = serde_json::from_value(body)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
let result = market::apply(&tx, &self.books, command)?;
|
||||
let result = market::apply(&tx, &self.books, command, id)?;
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
depth_feed::flush(&tx)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS market_directory_ids (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL UNIQUE REFERENCES markets(id), slug TEXT NOT NULL UNIQUE, question TEXT
|
||||
);
|
||||
-- Give old markets stable identities without publishing them as newly listed.
|
||||
INSERT INTO market_directory_ids(market,slug)
|
||||
SELECT m.id,m.id FROM markets m WHERE NOT EXISTS(SELECT 1 FROM market_directory_ids d WHERE d.market=m.id)
|
||||
ORDER BY m.id;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_lifecycle_frames (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id), kind TEXT NOT NULL,
|
||||
payload TEXT NOT NULL, UNIQUE(market,kind)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS lifecycle_discovery ON market_lifecycle_frames(kind,seq);
|
||||
CREATE VIEW IF NOT EXISTS market_wire_metadata AS
|
||||
SELECT d.market,d.slug,CAST(d.id AS TEXT) AS id,COALESCE(a.question,s.question,g.question,d.question,d.market) AS question,
|
||||
COALESCE(s.yes_label,g.yes_label,CASE WHEN t.market IS NULL THEN 'YES' ELSE 'Up' END) AS yes_label,
|
||||
COALESCE(s.no_label,g.no_label,CASE WHEN t.market IS NULL THEN 'NO' ELSE 'Down' END) AS no_label
|
||||
FROM market_directory_ids d LEFT JOIN sports_markets s ON s.market=d.market
|
||||
LEFT JOIN topic_markets g ON g.market=d.market
|
||||
LEFT JOIN augmented_outcomes a ON a.market=d.market LEFT JOIN twap_markets t ON t.market=d.market;
|
||||
CREATE TRIGGER IF NOT EXISTS stream_new_listing AFTER INSERT ON market_directory_ids BEGIN
|
||||
INSERT INTO market_lifecycle_frames(market,kind,payload)
|
||||
SELECT m.market,'new_market',json_object('event_type','new_market','id',m.id,'market',m.market,
|
||||
'slug',m.slug,'question',m.question,'assets_ids',json_array('eb:YES:'||m.market,'eb:NO:'||m.market),
|
||||
'outcomes',json_array(m.yes_label,m.no_label),'timestamp',CAST(t.at_ms AS TEXT))
|
||||
FROM market_wire_metadata m JOIN book_snapshot_times t USING(market) WHERE m.market=NEW.market;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS stream_final_result AFTER INSERT ON price_settlements BEGIN
|
||||
INSERT INTO market_lifecycle_frames(market,kind,payload)
|
||||
SELECT m.market,'market_resolved',json_object('event_type','market_resolved','id',m.id,'market',m.market,
|
||||
'assets_ids',json_array('eb:YES:'||m.market,'eb:NO:'||m.market),
|
||||
'winning_asset_id',CASE WHEN NEW.winner IN ('YES','NO') THEN 'eb:'||NEW.winner||':'||m.market END,
|
||||
'winning_outcome',CASE NEW.winner WHEN 'YES' THEN m.yes_label WHEN 'NO' THEN m.no_label END,
|
||||
'timestamp',CAST(NEW.at_ms AS TEXT))
|
||||
FROM market_wire_metadata m WHERE m.market=NEW.market;
|
||||
INSERT INTO market_stream_events(market,kind,source)
|
||||
SELECT market,'resolved',seq FROM market_lifecycle_frames WHERE market=NEW.market AND kind='market_resolved';
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Caller holds an IMMEDIATE transaction and checks the format marker under the lock.
|
||||
-- Fail the transaction if any integer would be promoted to SQLite REAL.
|
||||
CREATE TABLE order_lot_format (version INTEGER PRIMARY KEY CHECK(version=1));
|
||||
INSERT INTO order_lot_format
|
||||
SELECT CASE WHEN EXISTS(SELECT 1 FROM orders WHERE MAX(quantity,remaining)>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM fills WHERE quantity>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM paired_fills WHERE quantity>92233720368547758)
|
||||
OR EXISTS(SELECT 1 FROM trade_prices WHERE quantity>92233720368547758)
|
||||
THEN 0 ELSE 1 END;
|
||||
UPDATE orders SET quantity=quantity*100,remaining=remaining*100;
|
||||
UPDATE fills SET quantity=quantity*100;
|
||||
UPDATE paired_fills SET quantity=quantity*100;
|
||||
UPDATE trade_prices SET quantity=quantity*100;
|
||||
DROP VIEW position_units;
|
||||
CREATE VIEW position_units AS
|
||||
SELECT p.account,p.market,p.outcome,p.available*1000000+COALESCE(r.micros,0) AS available,
|
||||
p.reserved*10000 AS reserved,p.phase,p.payout_per_share
|
||||
FROM position_sizes p LEFT JOIN position_remainders r USING(account,market,outcome);
|
||||
@@ -0,0 +1,43 @@
|
||||
use anyhow::Result;
|
||||
use rusqlite::{Connection, TransactionBehavior};
|
||||
use serde_json::Number;
|
||||
|
||||
pub(crate) const PER_SHARE: i64 = 100;
|
||||
pub(crate) const MICROS: i64 = 10_000;
|
||||
pub(crate) fn display(lots: i64) -> Number {
|
||||
crate::inventory::decimal(lots.into(), PER_SHARE)
|
||||
}
|
||||
pub(crate) fn amount(qty: Option<i64>, size_micros: Option<i64>) -> Result<i64> {
|
||||
match (qty, size_micros) {
|
||||
(Some(whole), None) => {
|
||||
crate::validation::amount(whole)?;
|
||||
Ok(whole * PER_SHARE)
|
||||
}
|
||||
(None, Some(units)) if (MICROS..=1_000_000_000_000_000).contains(&units) => {
|
||||
Ok(units / MICROS)
|
||||
}
|
||||
_ => anyhow::bail!("provide one positive qty or size_micros within the quantity limit"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn migrate(db: &mut Connection) -> Result<()> {
|
||||
let ready = |c: &Connection, table: &str| {
|
||||
c.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name=?)",
|
||||
[table],
|
||||
|r| r.get::<_, bool>(0),
|
||||
)
|
||||
};
|
||||
if ready(db, "order_price_format")? {
|
||||
return Ok(());
|
||||
}
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if !ready(&tx, "order_lot_format")? {
|
||||
tx.execute_batch(include_str!("lot_migration.sql"))?;
|
||||
}
|
||||
if !ready(&tx, "order_price_format")? {
|
||||
tx.execute_batch(include_str!("price_migration.sql"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
+259
-86
@@ -9,20 +9,72 @@ use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result<Value> {
|
||||
pub(crate) fn apply(
|
||||
tx: &Transaction,
|
||||
books: &Books,
|
||||
command: Command,
|
||||
request_id: &str,
|
||||
) -> Result<Value> {
|
||||
match command {
|
||||
Command::Fund { account, cents } => {
|
||||
Command::BindPolymarketAssets(binding) => binding.register(tx),
|
||||
Command::Fund {
|
||||
account,
|
||||
cents,
|
||||
micros,
|
||||
} => {
|
||||
identifier(&account)?;
|
||||
amount(cents)?;
|
||||
tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?;
|
||||
Ok(json!({"funded":cents}))
|
||||
let value = match (cents, micros) {
|
||||
(Some(c), None) => {
|
||||
amount(c)?;
|
||||
c * 10000
|
||||
}
|
||||
(None, Some(m)) if (1..=10_000_000_000_000).contains(&m) => m,
|
||||
_ => anyhow::bail!("fund requires exactly one valid amount in cents or micros"),
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO accounts VALUES(?,?)",
|
||||
params![account, value / 10000],
|
||||
)?;
|
||||
if value % 10000 != 0 {
|
||||
ledger::cash_micros(tx, &account, value % 10000)?;
|
||||
}
|
||||
let mut receipt = json!({"funded":value/10000});
|
||||
if micros.is_some() {
|
||||
receipt["funded_micros"] = json!(value);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::SetMarketVisibility {
|
||||
market,
|
||||
active,
|
||||
archived,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
tx.execute(
|
||||
"INSERT INTO market_visibility(market,active,archived) VALUES(?,?,?)
|
||||
ON CONFLICT(market) DO UPDATE SET active=excluded.active,archived=excluded.archived",
|
||||
params![market,active,archived],
|
||||
)?;
|
||||
Ok(json!({"market":market,"active":active,"archived":archived}))
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::RescheduleSports {
|
||||
event,
|
||||
previous_ms,
|
||||
scheduled_at_ms,
|
||||
} => crate::kickoff::reschedule(tx, &event, previous_ms, scheduled_at_ms),
|
||||
Command::List {
|
||||
market,
|
||||
slug,
|
||||
question,
|
||||
rules,
|
||||
listing,
|
||||
resolution,
|
||||
taker_fee_rate_ppm,
|
||||
base_fees,
|
||||
min_order_size,
|
||||
tick_size,
|
||||
} => {
|
||||
identifier(&market)?;
|
||||
ensure!(!rules.trim().is_empty(), "rules required");
|
||||
@@ -30,70 +82,105 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
||||
params![market, rules],
|
||||
)?;
|
||||
if let Some(tick) = tick_size {
|
||||
crate::tick_size::TickSize::configure(tx, &market, &tick)?;
|
||||
}
|
||||
if let Some(size) = min_order_size {
|
||||
crate::minimum_size::MinimumSize::configure(tx, &market, &size)?;
|
||||
}
|
||||
if let Some(rate) = taker_fee_rate_ppm {
|
||||
crate::fees::configure(tx, &market, rate)?;
|
||||
}
|
||||
if let Some(base) = base_fees {
|
||||
base.save(tx, &market)?;
|
||||
}
|
||||
if let Some(policy) = resolution {
|
||||
policy.save(tx, &market)?;
|
||||
}
|
||||
if let Some(question) = question.as_deref() {
|
||||
ensure!(!question.trim().is_empty(), "market question is empty");
|
||||
ensure!(
|
||||
listing.is_none(),
|
||||
"use listing.question on event-backed markets"
|
||||
);
|
||||
}
|
||||
if let Some(listing) = listing {
|
||||
listing.save(tx, &market)?;
|
||||
}
|
||||
let slug = slug.as_deref().unwrap_or(&market);
|
||||
identifier(slug)?;
|
||||
tx.execute(
|
||||
"INSERT INTO market_directory_ids(market,slug,question) VALUES(?,?,?)",
|
||||
params![market, slug, question],
|
||||
)?;
|
||||
Ok(json!({"phase":"preopen"}))
|
||||
}
|
||||
Command::DefineNegRisk {
|
||||
group,
|
||||
event,
|
||||
markets,
|
||||
} => crate::neg_risk::define(tx, &group, &event, &markets),
|
||||
augmented,
|
||||
conversion_fee,
|
||||
} => {
|
||||
let result = crate::neg_risk::define(tx, &group, &event, &markets, conversion_fee)?;
|
||||
if let Some(config) = augmented {
|
||||
config.save(tx, &group, &markets)?;
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
Command::PublishClarification {
|
||||
market,
|
||||
content,
|
||||
clear_book,
|
||||
} => crate::clarifications::publish(tx, &market, &content, clear_book),
|
||||
Command::Clarify {
|
||||
market,
|
||||
name,
|
||||
question,
|
||||
evidence,
|
||||
} => crate::augmented::clarify(tx, &market, &name, &question, &evidence),
|
||||
Command::FinalizeAugmented {
|
||||
group,
|
||||
observed_name,
|
||||
evidence,
|
||||
} => crate::augmented::finalize(tx, &group, &observed_name, &evidence),
|
||||
Command::Convert {
|
||||
group,
|
||||
account,
|
||||
no_markets,
|
||||
qty,
|
||||
} => crate::neg_risk::convert(tx, &group, &account, &no_markets, qty),
|
||||
qty_micros,
|
||||
} => crate::neg_risk::convert(
|
||||
tx,
|
||||
request_id,
|
||||
&group,
|
||||
&account,
|
||||
&no_markets,
|
||||
qty,
|
||||
qty_micros,
|
||||
),
|
||||
Command::Split {
|
||||
market,
|
||||
account,
|
||||
qty,
|
||||
} => {
|
||||
identifier(&account)?;
|
||||
amount(qty)?;
|
||||
phase(tx, &market, &["preopen", "continuous"])?;
|
||||
ledger::cash(tx, &account, -100 * qty)?;
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+? WHERE id=?",
|
||||
params![100 * qty, market],
|
||||
)?;
|
||||
for side in ["YES", "NO"] {
|
||||
ledger::position(tx, &account, &market, side, qty)?;
|
||||
}
|
||||
Ok(json!({"pairs":qty}))
|
||||
}
|
||||
qty_micros,
|
||||
} => crate::inventory::pairs(tx, request_id, &account, &market, qty, qty_micros, true),
|
||||
Command::Merge {
|
||||
market,
|
||||
account,
|
||||
qty,
|
||||
} => {
|
||||
identifier(&account)?;
|
||||
amount(qty)?;
|
||||
phase(tx, &market, &["preopen", "continuous", "closed"])?;
|
||||
let cents = 100 * qty;
|
||||
for outcome in ["YES", "NO"] {
|
||||
ledger::position(tx, &account, &market, outcome, -qty)?;
|
||||
}
|
||||
let released = tx.execute(
|
||||
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
||||
params![cents, market],
|
||||
)?;
|
||||
ensure!(released == 1, "insufficient collateral");
|
||||
ledger::cash(tx, &account, cents)?;
|
||||
Ok(json!({"pairs":qty,"released_cents":cents}))
|
||||
}
|
||||
qty_micros,
|
||||
} => crate::inventory::pairs(tx, request_id, &account, &market, qty, qty_micros, false),
|
||||
Command::Order {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
price_micros,
|
||||
qty,
|
||||
size_micros,
|
||||
tif,
|
||||
expiration,
|
||||
post_only,
|
||||
@@ -103,10 +190,11 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
qty,
|
||||
price: crate::tick_size::required(price, price_micros)?,
|
||||
qty: crate::lots::amount(qty, size_micros)?,
|
||||
tif: tif.unwrap_or_else(|| {
|
||||
if expiration.unwrap_or(0) != 0 {
|
||||
crate::command::TimeInForce::Gtd
|
||||
@@ -122,9 +210,12 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
Command::MarketSell {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
min_price_micros,
|
||||
size_micros,
|
||||
tif,
|
||||
} => {
|
||||
let tif = tif.unwrap_or(crate::command::TimeInForce::Fak);
|
||||
@@ -135,15 +226,30 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
),
|
||||
"market sell requires FAK or FOK"
|
||||
);
|
||||
let qty = crate::lots::amount(qty, size_micros)?;
|
||||
let limit = crate::tick_size::input(min_price, min_price_micros)?;
|
||||
let price = books
|
||||
.protection_price(&market, &outcome, matching::Side::Sell, qty, limit, tif)
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!("insufficient opposing depth for market sell protection price")
|
||||
})?;
|
||||
let tick = crate::tick_size::TickSize::load(tx, &market)?;
|
||||
let amounts = crate::market_amounts::Amounts::for_order(
|
||||
tick.as_ref(),
|
||||
matching::Side::Sell,
|
||||
qty,
|
||||
price,
|
||||
)?;
|
||||
let result = book::submit(
|
||||
tx,
|
||||
books,
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side: "sell".to_owned(),
|
||||
price: min_price,
|
||||
price,
|
||||
qty,
|
||||
tif,
|
||||
expiration: None,
|
||||
@@ -151,16 +257,27 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
},
|
||||
)?;
|
||||
let mut receipt = result.receipt();
|
||||
receipt["proceeds_cents"] = json!(result.gross_cents);
|
||||
receipt["unsold_shares"] = json!(qty - result.filled);
|
||||
if let Some(amounts) = amounts {
|
||||
receipt["order_amounts"] = amounts.json();
|
||||
}
|
||||
receipt["protection_price_micros"] = json!(price * crate::tick_size::PRICE_MICROS);
|
||||
receipt["proceeds_cents"] =
|
||||
json!(crate::inventory::decimal(result.gross_micros.into(), 10000));
|
||||
receipt["unsold_shares"] = json!(crate::lots::display(qty - result.filled));
|
||||
if result.fee_micros > 0 {
|
||||
receipt["net_proceeds_micros"] = json!(result.gross_micros - result.fee_micros);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::MarketBuy {
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
key_id,
|
||||
amount_cents,
|
||||
amount_micros,
|
||||
max_price,
|
||||
max_price_micros,
|
||||
tif,
|
||||
} => book::market_buy(
|
||||
tx,
|
||||
@@ -169,15 +286,16 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
amount_cents,
|
||||
max_price,
|
||||
key_id,
|
||||
amount_cents: crate::market_amounts::cash_cents(amount_cents, amount_micros)?,
|
||||
max_price: crate::tick_size::input(max_price, max_price_micros)?,
|
||||
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
|
||||
},
|
||||
),
|
||||
Command::Cancel { order, account } => {
|
||||
identifier(&account)?;
|
||||
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
||||
Ok(json!({"cancelled":qty}))
|
||||
Ok(json!({"cancelled":crate::lots::display(qty)}))
|
||||
}
|
||||
Command::CancelOrders { account, orders } => {
|
||||
crate::cancellation::by_id(tx, &account, &orders)
|
||||
@@ -199,7 +317,11 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
let book = books
|
||||
.get(&market, &outcome)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
|
||||
book::settle(tx, &market, &outcome, book.opening(), None)?;
|
||||
let step = crate::tick_size::TickSize::load(tx, &market)?
|
||||
.map_or(std::num::NonZeroU32::new(100).unwrap(), |tick| {
|
||||
tick.local_step()
|
||||
});
|
||||
book::settle(tx, &market, &outcome, book.opening_with_step(step), None)?;
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
||||
Ok(json!({"phase":"continuous"}))
|
||||
@@ -231,7 +353,9 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
return Ok(json!({"status":"awaiting_proposal","proposal":proposal}));
|
||||
}
|
||||
let backing = finalize(tx, &market, &verdict)?;
|
||||
Ok(json!({"phase":"resolved","winner":verdict,"outstanding_cents":backing}))
|
||||
Ok(
|
||||
json!({"phase":"resolved","winner":verdict,"outstanding_cents":crate::inventory::decimal(i128::from(backing),10000)}),
|
||||
)
|
||||
}
|
||||
Command::Observe {
|
||||
market,
|
||||
@@ -253,84 +377,133 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
.ok_or_else(|| anyhow::anyhow!("no computed outcome available"))?,
|
||||
};
|
||||
let backing = finalize(tx, &market, &winner)?;
|
||||
Ok(json!({"phase":"resolved","winner":winner,"outstanding_cents":backing}))
|
||||
Ok(
|
||||
json!({"phase":"resolved","winner":winner,"outstanding_cents":crate::inventory::decimal(i128::from(backing),10000)}),
|
||||
)
|
||||
}
|
||||
Command::Redeem { market, account } => {
|
||||
Command::Redeem {
|
||||
market,
|
||||
account,
|
||||
amounts_micros,
|
||||
} => {
|
||||
identifier(&account)?;
|
||||
phase(tx, &market, &["resolved"])?;
|
||||
let paid = redeem(tx, &market, &account)?;
|
||||
Ok(json!({"market":market,"account":account,"paid":paid}))
|
||||
let paid = redeem(tx, &market, &account, request_id, amounts_micros)?;
|
||||
let mut receipt = json!({"market":market,"account":account,"paid":crate::inventory::decimal(i128::from(paid),10000)});
|
||||
if let Some(amounts) = amounts_micros {
|
||||
receipt["amounts_micros"] = json!(amounts);
|
||||
receipt["paid_micros"] = json!(paid);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::Resolve { market, winner } => {
|
||||
let backing = finalize(tx, &market, &winner)?;
|
||||
let mut holders =
|
||||
tx.prepare("SELECT DISTINCT account FROM positions WHERE market=? AND quantity>0")?;
|
||||
let mut holders = tx.prepare(
|
||||
"SELECT DISTINCT account FROM position_units WHERE market=? AND available>0",
|
||||
)?;
|
||||
let accounts = holders
|
||||
.query_map([&market], |row| row.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let mut paid = 0;
|
||||
for account in accounts {
|
||||
paid += redeem(tx, &market, &account)?;
|
||||
paid += redeem(tx, &market, &account, request_id, None)?;
|
||||
}
|
||||
ensure!(backing == paid, "collateral mismatch");
|
||||
Ok(json!({"phase":"resolved","paid":paid}))
|
||||
let dust: i64 = tx.query_row(
|
||||
"SELECT COALESCE((SELECT micros FROM settlement_dust WHERE market=?),0)",
|
||||
[&market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(backing == paid + dust, "collateral mismatch");
|
||||
Ok(json!({"phase":"resolved","paid":crate::inventory::decimal(i128::from(paid),10000)}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn close_market(tx: &Transaction, market: &str) -> Result<()> {
|
||||
phase(tx, market, &["preopen", "continuous"])?;
|
||||
clear_orders(tx, market)?;
|
||||
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn clear_orders(tx: &Transaction, market: &str) -> Result<usize> {
|
||||
let mut stmt = tx.prepare("SELECT seq,account FROM orders WHERE market=? AND status='live'")?;
|
||||
let orders = stmt
|
||||
.query_map([market], |r| {
|
||||
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let count = orders.len();
|
||||
for (seq, account) in orders {
|
||||
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
|
||||
Ok(())
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
|
||||
pub(crate) fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
|
||||
phase(tx, market, &["closed"])?;
|
||||
ensure!(matches!(winner, "YES" | "NO" | "VOID"), "invalid winner");
|
||||
resolution::authorize_finalization(tx, market, winner)?;
|
||||
crate::neg_risk::allocate_payout(tx, market, winner)?;
|
||||
// Close releases all outstanding reservations before finality.
|
||||
let changed=tx.execute(
|
||||
"UPDATE markets SET phase='resolved',winner=?1
|
||||
WHERE id=?2 AND collateral=(
|
||||
SELECT COALESCE(SUM(quantity * CASE WHEN ?1='VOID' THEN 50 WHEN outcome=?1 THEN 100 ELSE 0 END),0)
|
||||
FROM positions WHERE market=?2)",
|
||||
params![winner,market])?;
|
||||
ensure!(changed == 1, "collateral mismatch");
|
||||
Ok(tx.query_row(
|
||||
"SELECT collateral FROM markets WHERE id=?",
|
||||
// Each outcome redeems in whole collateral base units. Half-payout rounding
|
||||
// is per outcome balance, including when both balances belong to one wallet.
|
||||
let (payout,odd):(i64,i64)=tx.query_row(
|
||||
"SELECT COALESCE(SUM(CASE WHEN ?1='VOID' THEN available/2 WHEN outcome=?1 THEN available ELSE 0 END),0),
|
||||
COALESCE(SUM(CASE WHEN ?1='VOID' THEN available%2 ELSE 0 END),0)
|
||||
FROM position_units WHERE market=?2",params![winner,market],|r| Ok((r.get(0)?,r.get(1)?)))?;
|
||||
let backing: i64 = tx.query_row(
|
||||
"SELECT micros FROM market_backing WHERE market=?",
|
||||
[market],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
odd % 2 == 0 && backing.checked_sub(odd / 2) == Some(payout),
|
||||
"collateral mismatch"
|
||||
);
|
||||
if odd > 0 {
|
||||
tx.execute(
|
||||
"INSERT INTO settlement_dust VALUES(?,?)",
|
||||
params![market, odd / 2],
|
||||
)?;
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE markets SET phase='resolved',winner=? WHERE id=?",
|
||||
params![winner, market],
|
||||
)?;
|
||||
Ok(backing)
|
||||
}
|
||||
|
||||
fn redeem(tx: &Transaction, market: &str, account: &str) -> Result<i64> {
|
||||
let paid:Option<i64>=tx.query_row(
|
||||
"SELECT SUM(p.quantity * CASE WHEN m.winner='VOID' THEN 50 WHEN p.outcome=m.winner THEN 100 ELSE 0 END)
|
||||
FROM positions p JOIN markets m ON m.id=p.market
|
||||
WHERE p.market=? AND p.account=? AND p.quantity>0",
|
||||
params![market,account],|row|row.get(0))?;
|
||||
fn redeem(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
account: &str,
|
||||
request_id: &str,
|
||||
amounts: Option<[i64; 2]>,
|
||||
) -> Result<i64> {
|
||||
let (shares, paid) = match amounts {
|
||||
Some(amounts) => crate::neg_risk::burn_for_redemption(tx, market, account, amounts)?,
|
||||
None => burn_full_balance(tx, market, account)?,
|
||||
};
|
||||
crate::inventory::movement(tx, request_id, account, market, "REDEEM", shares, paid)?;
|
||||
if paid > 0 {
|
||||
crate::inventory::backing(tx, market, -paid)?;
|
||||
ledger::cash_micros(tx, account, paid)?;
|
||||
}
|
||||
Ok(paid)
|
||||
}
|
||||
|
||||
fn burn_full_balance(tx: &Transaction, market: &str, account: &str) -> Result<(i64, i64)> {
|
||||
let (shares,paid):(Option<i64>,Option<i64>)=tx.query_row(
|
||||
"SELECT SUM(available),SUM(CASE payout_per_share WHEN 50 THEN available/2 WHEN 100 THEN available ELSE 0 END)
|
||||
FROM position_units WHERE market=? AND account=? AND available>0",params![market,account],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
||||
let paid = paid.ok_or_else(|| anyhow::anyhow!("no positions to redeem"))?;
|
||||
tx.execute(
|
||||
"DELETE FROM position_remainders WHERE market=? AND account=?",
|
||||
params![market, account],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE positions SET quantity=0 WHERE market=? AND account=? AND quantity>0",
|
||||
params![market, account],
|
||||
)?;
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
||||
params![paid, market]
|
||||
)? == 1,
|
||||
"insufficient collateral"
|
||||
);
|
||||
ledger::cash(tx, account, paid)?;
|
||||
Ok(paid)
|
||||
Ok((shares.unwrap_or(0), paid))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
use crate::{assets, lots, minimum_size::MinimumSize, tick_size::TickSize};
|
||||
use anyhow::{ensure, Result};
|
||||
use matching::Side;
|
||||
use rusqlite::Connection;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn cash_cents(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
|
||||
let cents = match (cents, micros) {
|
||||
(Some(n), None) => n,
|
||||
(None, Some(n)) if n > 0 => n / 10_000,
|
||||
_ => anyhow::bail!("provide one positive amount_cents or amount_micros"),
|
||||
};
|
||||
crate::validation::amount(cents)?;
|
||||
Ok(cents)
|
||||
}
|
||||
|
||||
pub(crate) struct Amounts {
|
||||
maker: i64,
|
||||
taker: i64,
|
||||
}
|
||||
|
||||
impl Amounts {
|
||||
pub fn for_order(
|
||||
tick: Option<&TickSize>,
|
||||
side: Side,
|
||||
requested: i64,
|
||||
price_units: i64,
|
||||
) -> Result<Option<Self>> {
|
||||
match tick {
|
||||
Some(tick) => Self::encode(
|
||||
tick,
|
||||
side,
|
||||
requested,
|
||||
price_units * crate::tick_size::PRICE_MICROS,
|
||||
)
|
||||
.map(Some),
|
||||
None => {
|
||||
crate::tick_size::validate(None, price_units)?;
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// requested is in whole cents for BUY, 0.01-share lots for SELL.
|
||||
fn encode(tick: &TickSize, side: Side, requested: i64, price: i64) -> Result<Self> {
|
||||
tick.check(price)?;
|
||||
let maker = requested
|
||||
.checked_mul(10_000)
|
||||
.ok_or_else(|| anyhow::anyhow!("order amount overflow"))?;
|
||||
ensure!(maker > 0, "positive order amount required");
|
||||
let scale = 1_000_000_i128;
|
||||
let taker = match side {
|
||||
Side::Buy => {
|
||||
let quantum = match tick.0 {
|
||||
100_000 => 1000,
|
||||
10_000 => 100,
|
||||
5_000 | 1_000 => 10,
|
||||
2_500 | 100 => 1,
|
||||
_ => anyhow::bail!("unsupported market tick"),
|
||||
};
|
||||
let cash = i128::from(maker) * scale;
|
||||
let shares = cash / i128::from(price) / quantum * quantum;
|
||||
ensure!(
|
||||
cash < shares * i128::from(price + 100),
|
||||
"rounded market buy exceeds price protection"
|
||||
);
|
||||
shares
|
||||
}
|
||||
Side::Sell => i128::from(maker) * i128::from(price) / scale,
|
||||
};
|
||||
Ok(Self {
|
||||
maker,
|
||||
taker: i64::try_from(taker)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn json(&self) -> Value {
|
||||
json!({"makerAmount": self.maker.to_string(), "takerAmount": self.taker.to_string()})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)]
|
||||
pub(crate) enum Request {
|
||||
Buy {
|
||||
market: String,
|
||||
outcome: String,
|
||||
price_micros: i64,
|
||||
amount_cents: Option<i64>,
|
||||
amount_micros: Option<i64>,
|
||||
},
|
||||
Sell {
|
||||
market: String,
|
||||
outcome: String,
|
||||
price_micros: i64,
|
||||
qty: Option<i64>,
|
||||
size_micros: Option<i64>,
|
||||
},
|
||||
}
|
||||
impl Request {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let (market, outcome, side, requested, price) = match self {
|
||||
Self::Buy {
|
||||
market,
|
||||
outcome,
|
||||
price_micros,
|
||||
amount_cents,
|
||||
amount_micros,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Buy,
|
||||
cash_cents(amount_cents, amount_micros)?,
|
||||
price_micros,
|
||||
),
|
||||
Self::Sell {
|
||||
market,
|
||||
outcome,
|
||||
price_micros,
|
||||
qty,
|
||||
size_micros,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Sell,
|
||||
lots::amount(qty, size_micros)?,
|
||||
price_micros,
|
||||
),
|
||||
};
|
||||
ensure!(matches!(outcome.as_str(), "YES" | "NO"), "invalid outcome");
|
||||
let tick = TickSize::load(db, &market)?
|
||||
.ok_or_else(|| anyhow::anyhow!("listed market with configured tick_size required"))?;
|
||||
let amounts = Amounts::encode(&tick, side, requested, price)?;
|
||||
if let Some(minimum) = MinimumSize::load(db, &market)? {
|
||||
minimum.check_microshares(match side {
|
||||
Side::Buy => amounts.taker,
|
||||
Side::Sell => amounts.maker,
|
||||
})?;
|
||||
}
|
||||
let mut result = amounts.json();
|
||||
result["asset_id"] = json!(assets::id(&market, &outcome));
|
||||
result["tick_size"] = json!(tick.text());
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::{
|
||||
assets, book_snapshot, depth_feed, inventory::decimal, lots, resident::Books,
|
||||
tick_size::TickSize, MarketPage,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn page(
|
||||
tx: &Transaction,
|
||||
books: &mut Books,
|
||||
market: &str,
|
||||
after: Option<i64>,
|
||||
) -> Result<MarketPage> {
|
||||
let latest:i64=tx.query_row(
|
||||
"SELECT COALESCE((SELECT MAX(seq) FROM market_stream_events WHERE market=?1),0) FROM markets WHERE id=?1",
|
||||
[market], |r|r.get(0))?;
|
||||
let mut frames = Vec::new();
|
||||
let Some(mut cursor) = after else {
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
for outcome in ["YES", "NO"] {
|
||||
frames.push((
|
||||
latest,
|
||||
book_snapshot::event(tx, books, &assets::id(market, outcome), true)?,
|
||||
));
|
||||
}
|
||||
return Ok(MarketPage {
|
||||
cursor: latest,
|
||||
frames,
|
||||
has_more: false,
|
||||
});
|
||||
};
|
||||
ensure!(
|
||||
(0..=latest).contains(&cursor),
|
||||
"invalid market stream cursor"
|
||||
);
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT seq,kind,source,fee_ppm FROM market_stream_events
|
||||
WHERE market=? AND seq>? ORDER BY seq LIMIT 64",
|
||||
)?;
|
||||
let mut records = stmt.query(params![market, cursor])?;
|
||||
while let Some(row) = records.next()? {
|
||||
cursor = row.get(0)?;
|
||||
let kind: String = row.get(1)?;
|
||||
let source: i64 = row.get(2)?;
|
||||
match kind.as_str() {
|
||||
"resolved" => {
|
||||
let payload: String = tx.query_row(
|
||||
"SELECT payload FROM market_lifecycle_frames WHERE seq=?",
|
||||
[source],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
frames.push((cursor, serde_json::from_str(&payload)?));
|
||||
}
|
||||
"depth" => {
|
||||
let (at, bid, ask): (i64, Option<i64>, Option<i64>) = tx.query_row(
|
||||
"SELECT at_ms,best_bid,best_ask FROM depth_batches WHERE seq=?",
|
||||
[source],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
let changes = depth_feed::changes(tx, market, source, bid, ask)?;
|
||||
frames.push((
|
||||
cursor,
|
||||
json!({"event_type":"price_change","market":market,
|
||||
"timestamp":at.to_string(),"price_changes":changes}),
|
||||
));
|
||||
}
|
||||
"tick" => {
|
||||
let (at, old, new): (i64, Option<i64>, i64) = tx.query_row(
|
||||
"SELECT at_ms,old_micros,new_micros FROM tick_changes WHERE seq=?",
|
||||
[source],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
for outcome in ["YES", "NO"] {
|
||||
frames.push((cursor,json!({"event_type":"tick_size_change","market":market,"asset_id":assets::id(market,outcome),
|
||||
"timestamp":at.to_string(),"old_tick_size":TickSize(old.unwrap_or(10000)).text(),"new_tick_size":TickSize(new).text()})));
|
||||
}
|
||||
}
|
||||
"trade" => {
|
||||
for frame in trades(tx, market, source, row.get(3)?)? {
|
||||
frames.push((cursor, frame));
|
||||
}
|
||||
}
|
||||
_ => anyhow::bail!("invalid market stream record"),
|
||||
}
|
||||
}
|
||||
Ok(MarketPage {
|
||||
cursor,
|
||||
frames,
|
||||
has_more: cursor < latest,
|
||||
})
|
||||
}
|
||||
|
||||
fn trades(tx: &Transaction, market: &str, source: i64, fee_ppm: i64) -> Result<Vec<Value>> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT p.outcome,p.at_ms,p.price_micros,p.quantity,
|
||||
t.outcome,t.side
|
||||
FROM outcome_trade_prices p JOIN execution_context c ON c.execution=p.fill
|
||||
LEFT JOIN orders t ON t.seq=c.taker_order WHERE p.fill=? ORDER BY p.outcome DESC",
|
||||
)?;
|
||||
let mut rows = stmt.query([source])?;
|
||||
let mut frames = Vec::new();
|
||||
while let Some(r) = rows.next()? {
|
||||
let outcome: String = r.get(0)?;
|
||||
let stamp: i64 = r.get(1)?;
|
||||
let price: i64 = r.get(2)?;
|
||||
let quantity: i64 = r.get(3)?;
|
||||
let taker_outcome: Option<String> = r.get(4)?;
|
||||
let order_side: Option<String> = r.get(5)?;
|
||||
let side = crate::last_trades::taker_side(
|
||||
&outcome,
|
||||
taker_outcome.as_deref(),
|
||||
order_side.as_deref(),
|
||||
);
|
||||
frames.push(json!({"event_type":"last_trade_price","market":market,"asset_id":assets::id(market,&outcome),
|
||||
"timestamp":stamp.to_string(),"price":decimal(price.into(),1_000_000).to_string(),
|
||||
"size":decimal(quantity.into(),lots::PER_SHARE).to_string(),"side":side,
|
||||
"fee_rate_bps":decimal(fee_ppm.into(),100).to_string(),"transaction_hash":null}));
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
pub(crate) fn discovery(tx: &Transaction, after: Option<i64>) -> Result<MarketPage> {
|
||||
let latest: i64 = tx.query_row(
|
||||
"SELECT COALESCE(MAX(seq),0) FROM market_lifecycle_frames WHERE kind='new_market'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut cursor = after.unwrap_or(latest);
|
||||
ensure!((0..=latest).contains(&cursor), "invalid discovery cursor");
|
||||
let mut frames = Vec::new();
|
||||
if cursor < latest {
|
||||
let mut stmt=tx.prepare_cached("SELECT seq,payload FROM market_lifecycle_frames WHERE kind='new_market' AND seq>? ORDER BY seq LIMIT 64")?;
|
||||
let mut rows = stmt.query([cursor])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
cursor = row.get(0)?;
|
||||
let payload: String = row.get(1)?;
|
||||
frames.push((cursor, serde_json::from_str(&payload)?));
|
||||
}
|
||||
}
|
||||
Ok(MarketPage {
|
||||
cursor,
|
||||
frames,
|
||||
has_more: cursor < latest,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS market_stream_events (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id),
|
||||
kind TEXT NOT NULL, source INTEGER NOT NULL, fee_ppm INTEGER,
|
||||
UNIQUE(kind,source)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS market_stream_cursor ON market_stream_events(market,seq);
|
||||
-- Preserve the original wire depth cursors when installing over a populated database.
|
||||
INSERT OR IGNORE INTO market_stream_events(seq,market,kind,source)
|
||||
SELECT seq,market,'depth',seq FROM depth_batches ORDER BY seq;
|
||||
CREATE TRIGGER IF NOT EXISTS stream_depth AFTER INSERT ON depth_batches BEGIN
|
||||
INSERT INTO market_stream_events(market,kind,source) VALUES(NEW.market,'depth',NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS stream_tick AFTER INSERT ON tick_changes BEGIN
|
||||
INSERT INTO market_stream_events(market,kind,source) VALUES(NEW.market,'tick',NEW.seq);
|
||||
END;
|
||||
-- Settlement writes the taker context after the immutable fill and its prices.
|
||||
CREATE TRIGGER IF NOT EXISTS stream_trade AFTER INSERT ON execution_context BEGIN
|
||||
INSERT INTO market_stream_events(market,kind,source,fee_ppm)
|
||||
SELECT p.market,'trade',NEW.execution,
|
||||
CASE WHEN NEW.taker_order IS NULL THEN 0 ELSE COALESCE(f.rate_ppm,0) END
|
||||
FROM outcome_trade_prices p LEFT JOIN market_fee_rates f ON f.market=p.market
|
||||
WHERE p.fill=NEW.execution LIMIT 1;
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,79 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
|
||||
const SCALE: i64 = 1_000_000;
|
||||
|
||||
pub(crate) struct MinimumSize(i64);
|
||||
|
||||
impl MinimumSize {
|
||||
pub fn configure(tx: &Transaction, market: &str, input: &str) -> Result<()> {
|
||||
let (whole, fraction) = input.split_once('.').unwrap_or((input, ""));
|
||||
ensure!(
|
||||
!whole.is_empty()
|
||||
&& whole.bytes().all(|b| b.is_ascii_digit())
|
||||
&& fraction.bytes().all(|b| b.is_ascii_digit())
|
||||
&& fraction.len() <= 6
|
||||
&& !input.ends_with('.'),
|
||||
"min_order_size must be positive decimal shares with at most six decimals"
|
||||
);
|
||||
let whole: i64 = whole.parse()?;
|
||||
ensure!(
|
||||
whole <= 1_000_000_000,
|
||||
"min_order_size exceeds supported order size"
|
||||
);
|
||||
let fraction = if fraction.is_empty() {
|
||||
0
|
||||
} else {
|
||||
fraction.parse::<i64>()? * 10_i64.pow(6 - fraction.len() as u32)
|
||||
};
|
||||
let micros = whole * SCALE + fraction;
|
||||
ensure!(
|
||||
(1..=1_000_000_000 * SCALE).contains(µs),
|
||||
"min_order_size out of range"
|
||||
);
|
||||
tx.execute(
|
||||
"INSERT INTO market_minimum_sizes(market,microshares) VALUES(?,?)",
|
||||
params![market, micros],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load(db: &Connection, market: &str) -> Result<Option<Self>> {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT microshares FROM market_minimum_sizes WHERE market=?")?
|
||||
.query_row([market], |row| Ok(Self(row.get(0)?)))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
Self::format_microshares(self.0)
|
||||
}
|
||||
|
||||
pub fn format_microshares(micros: i64) -> String {
|
||||
let digits = format!("{}.{:06}", micros / SCALE, micros % SCALE);
|
||||
digits
|
||||
.trim_end_matches('0')
|
||||
.trim_end_matches('.')
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
pub fn check_microshares(&self, shares: i64) -> Result<()> {
|
||||
ensure!(
|
||||
shares >= self.0,
|
||||
"order is below min_order_size of {} shares",
|
||||
self.text()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn check_budget(&self, cents: i64, max_price: i64, fee_rate: i64) -> Result<()> {
|
||||
let lots = (self.0 + crate::lots::MICROS - 1) / crate::lots::MICROS;
|
||||
let required = lots * max_price + crate::fees::lot_fee(fee_rate, max_price * 100, lots);
|
||||
ensure!(
|
||||
cents * 10000 >= required,
|
||||
"cash budget at protection price is below min_order_size of {} shares",
|
||||
self.text()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+161
-42
@@ -1,17 +1,33 @@
|
||||
use crate::{
|
||||
ledger,
|
||||
validation::{amount, identifier},
|
||||
};
|
||||
use crate::{assets, inventory, ledger, validation::identifier, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
impl Exchange {
|
||||
pub fn token_neg_risk(&self, token: &str) -> Result<Option<bool>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt=self.db.prepare_cached(
|
||||
"SELECT EXISTS(SELECT 1 FROM neg_risk_members WHERE market=m.id) FROM markets m WHERE m.id=?1"
|
||||
)?;
|
||||
Ok(stmt.query_row([market], |row| row.get(0)).optional()?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct ConversionFee {
|
||||
bps: i64,
|
||||
vault: String,
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
tx: &Transaction,
|
||||
group: &str,
|
||||
event: &str,
|
||||
markets: &[String],
|
||||
fee: Option<ConversionFee>,
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(event)?;
|
||||
@@ -36,87 +52,190 @@ pub(crate) fn define(
|
||||
"members must be unused preopen markets of this event with manual resolution"
|
||||
);
|
||||
}
|
||||
Ok(json!({"group":group,"markets":markets}))
|
||||
let mut receipt = json!({"group":group,"markets":markets});
|
||||
if let Some(fee) = fee {
|
||||
identifier(&fee.vault)?;
|
||||
ensure!(
|
||||
(0..=10000).contains(&fee.bps),
|
||||
"conversion fee must be 0 to 10000 bps"
|
||||
);
|
||||
tx.execute(
|
||||
"INSERT INTO accounts(id,cash) VALUES(?,0) ON CONFLICT(id) DO NOTHING",
|
||||
[&fee.vault],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO neg_risk_conversion_fees(group_id,bps,vault) VALUES(?,?,?)",
|
||||
params![group, fee.bps, fee.vault],
|
||||
)?;
|
||||
receipt["conversion_fee"] = json!(fee);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub(crate) fn convert(
|
||||
tx: &Transaction,
|
||||
request: &str,
|
||||
group: &str,
|
||||
account: &str,
|
||||
no_markets: &[String],
|
||||
qty: i64,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(account)?;
|
||||
amount(qty)?;
|
||||
let units = match (qty, qty_micros) {
|
||||
(Some(0), None) | (None, Some(0)) => 0,
|
||||
_ => inventory::quantity_units(qty, qty_micros)?,
|
||||
};
|
||||
let selected: BTreeSet<&str> = no_markets.iter().map(String::as_str).collect();
|
||||
ensure!(
|
||||
!selected.is_empty() && selected.len() == no_markets.len(),
|
||||
"provide distinct NO markets"
|
||||
);
|
||||
let mut stmt = tx.prepare(
|
||||
"SELECT n.market,m.phase FROM neg_risk_members n JOIN markets m ON m.id=n.market
|
||||
WHERE n.group_id=? ORDER BY n.ordinal",
|
||||
)?;
|
||||
let mut stmt =
|
||||
tx.prepare("SELECT market FROM neg_risk_members WHERE group_id=? ORDER BY ordinal")?;
|
||||
let members = stmt
|
||||
.query_map([group], |r| {
|
||||
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
|
||||
})?
|
||||
.query_map([group], |r| r.get::<_, String>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(
|
||||
selected
|
||||
.iter()
|
||||
.all(|id| members.iter().any(|(market, _)| market.as_str() == *id)),
|
||||
.all(|id| members.iter().any(|market| market.as_str() == *id)),
|
||||
"NO market outside group"
|
||||
);
|
||||
ensure!(
|
||||
members.iter().all(|(_, phase)| phase != "resolved"),
|
||||
"group already resolving"
|
||||
);
|
||||
let cents = qty * 100;
|
||||
if units == 0 {
|
||||
return Ok(
|
||||
json!({"group":group,"no_markets":no_markets,"yes_markets":[],
|
||||
"qty":0,"qty_micros":0,"released_cents":0,"released_micros":0,"noop":true}),
|
||||
);
|
||||
}
|
||||
let (winner, reserve): (Option<String>, i64) = tx.query_row(
|
||||
"SELECT winner,micros FROM neg_risk_reserves WHERE id=?",
|
||||
[group],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let policy = tx
|
||||
.query_row(
|
||||
"SELECT bps,vault FROM neg_risk_conversion_fees WHERE group_id=?",
|
||||
[group],
|
||||
|row| {
|
||||
Ok(ConversionFee {
|
||||
bps: row.get(0)?,
|
||||
vault: row.get(1)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()?;
|
||||
// The adapter rounds each output before multiplying by the number of cash legs.
|
||||
let bps = policy.as_ref().map_or(0, |fee| fee.bps);
|
||||
let fee_units = i64::try_from(i128::from(units) * i128::from(bps) / 10_000)?;
|
||||
let net_units = units - fee_units;
|
||||
let mut yes_markets = Vec::new();
|
||||
for (market, _) in &members {
|
||||
for market in &members {
|
||||
let is_winner = winner.as_deref() == Some(market.as_str());
|
||||
if selected.contains(market.as_str()) {
|
||||
ledger::position(tx, account, market, "NO", -qty)?;
|
||||
ensure!(
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
||||
params![cents, market]
|
||||
)? == 1,
|
||||
"insufficient market backing"
|
||||
);
|
||||
inventory::position(tx, account, market, "NO", -units)?;
|
||||
// A determined winner's NO has no claim on that market's backing.
|
||||
if !is_winner {
|
||||
inventory::backing(tx, market, -units)?;
|
||||
}
|
||||
} else {
|
||||
ledger::position(tx, account, market, "YES", qty)?;
|
||||
if is_winner {
|
||||
inventory::backing(tx, market, units)?;
|
||||
}
|
||||
if net_units > 0 {
|
||||
inventory::position(tx, account, market, "YES", net_units)?;
|
||||
}
|
||||
if let Some(fee) = policy.as_ref().filter(|_| fee_units > 0) {
|
||||
inventory::position(tx, &fee.vault, market, "YES", fee_units)?;
|
||||
}
|
||||
yes_markets.push(market);
|
||||
}
|
||||
}
|
||||
let released = (selected.len() as i64 - 1) * cents;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=reserve_cents+?1 WHERE id=?2",
|
||||
params![cents, group],
|
||||
)?;
|
||||
ledger::cash(tx, account, released)?;
|
||||
Ok(
|
||||
json!({"group":group,"qty":qty,"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":released}),
|
||||
)
|
||||
let cash_legs = selected.len() as i64 - 1;
|
||||
let released = cash_legs * net_units;
|
||||
let cash_fee = cash_legs * fee_units;
|
||||
if winner.is_none() {
|
||||
let reserve = reserve
|
||||
.checked_add(units)
|
||||
.ok_or_else(|| anyhow::anyhow!("group reserve overflow"))?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET reserve_cents=? WHERE id=?",
|
||||
params![reserve / 10000, group],
|
||||
)?;
|
||||
tx.execute("INSERT INTO neg_risk_reserve_remainders(group_id,micros) VALUES(?,?) ON CONFLICT(group_id) DO UPDATE SET micros=excluded.micros",params![group,reserve%10000])?;
|
||||
}
|
||||
ledger::cash_micros(tx, account, released)?;
|
||||
let mut receipt = json!({"group":group,"qty":inventory::decimal(units.into(),inventory::UNIT),
|
||||
"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":inventory::decimal(released.into(),10000)});
|
||||
if let Some(fee) = &policy {
|
||||
if cash_fee > 0 {
|
||||
ledger::cash_micros(tx, &fee.vault, cash_fee)?;
|
||||
}
|
||||
receipt["conversion_fee"] = json!({"bps":bps,"vault":fee.vault,
|
||||
"cash_micros":cash_fee,"yes_micros_per_market":fee_units});
|
||||
}
|
||||
if qty_micros.is_some() || policy.is_some() {
|
||||
inventory::movement(tx, request, account, group, "CONVERSION", units, released)?;
|
||||
receipt["qty_micros"] = json!(units);
|
||||
receipt["released_micros"] = json!(released);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
/// Burn the YES/NO amounts transferred by a negative-risk adapter caller.
|
||||
/// The caller settles the returned (burned shares, collateral payout) in this transaction.
|
||||
pub(crate) fn burn_for_redemption(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
account: &str,
|
||||
amounts: [i64; 2],
|
||||
) -> Result<(i64, i64)> {
|
||||
let winner: Option<String> = tx.query_row(
|
||||
"SELECT m.winner FROM neg_risk_members n JOIN markets m ON m.id=n.market WHERE n.market=? AND m.phase='resolved'",
|
||||
[market], |row| row.get(0),
|
||||
).optional()?;
|
||||
let [yes, no] = amounts;
|
||||
let paid = match winner.as_deref() {
|
||||
Some("YES") => yes,
|
||||
Some("NO") => no,
|
||||
_ => anyhow::bail!("explicit redemption amounts require a resolved negative-risk market"),
|
||||
};
|
||||
ensure!(yes >= 0 && no >= 0, "negative redemption amount");
|
||||
let burned = yes
|
||||
.checked_add(no)
|
||||
.ok_or_else(|| anyhow::anyhow!("redemption share total overflow"))?;
|
||||
for (outcome, units) in [("YES", yes), ("NO", no)] {
|
||||
if units > 0 {
|
||||
inventory::position(tx, account, market, outcome, -units)?;
|
||||
}
|
||||
}
|
||||
Ok((burned, paid))
|
||||
}
|
||||
|
||||
// Run in the same transaction as the binary payout check. A failing verdict
|
||||
// rolls back the transfer as well as any optimistic-resolution state change.
|
||||
pub(crate) fn allocate_payout(tx: &Transaction, market: &str, outcome: &str) -> Result<()> {
|
||||
let group: Option<(String, Option<String>, i64)> = tx.query_row(
|
||||
"SELECT g.id,g.winner,g.reserve_cents FROM neg_risk_members n JOIN neg_risk_groups g ON g.id=n.group_id WHERE n.market=?",
|
||||
"SELECT g.id,g.winner,g.micros FROM neg_risk_members n JOIN neg_risk_reserves g ON g.id=n.group_id WHERE n.market=?",
|
||||
[market], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
).optional()?;
|
||||
let Some((group, winner, reserve)) = group else {
|
||||
return Ok(());
|
||||
};
|
||||
let valid: bool = tx.query_row(
|
||||
"SELECT NOT EXISTS (SELECT 1 FROM augmented_outcomes a
|
||||
LEFT JOIN augmented_results r ON r.group_id=a.group_id
|
||||
WHERE a.market=?1 AND (r.winner IS NULL OR ?2<>CASE WHEN r.winner=?1 THEN 'YES' ELSE 'NO' END))",
|
||||
params![market,outcome], |r|r.get(0))?;
|
||||
ensure!(valid, "resolve the observed winner with finalize_augmented");
|
||||
match outcome {
|
||||
"YES" => {
|
||||
ensure!(winner.is_none(), "group already has a winner");
|
||||
inventory::backing(tx, market, reserve)?;
|
||||
tx.execute(
|
||||
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2",
|
||||
params![reserve, market],
|
||||
"DELETE FROM neg_risk_reserve_remainders WHERE group_id=?",
|
||||
[&group],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE neg_risk_groups SET winner=?1,reserve_cents=0 WHERE id=?2",
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
portfolio,
|
||||
validation::{condition_filter, IdSelector},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, Connection, TransactionBehavior};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Number, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
#[serde(alias = "markets")]
|
||||
market: Option<IdSelector>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Interest {
|
||||
shares: i128,
|
||||
unpriced_shares: i128,
|
||||
priced_submicros: i128,
|
||||
}
|
||||
|
||||
impl Interest {
|
||||
fn add(&mut self, shares: i64, value: Option<i128>) {
|
||||
self.shares += i128::from(shares);
|
||||
if let Some(value) = value {
|
||||
self.priced_submicros += value;
|
||||
} else {
|
||||
self.unpriced_shares += i128::from(shares);
|
||||
}
|
||||
}
|
||||
|
||||
fn row(&self, market: Option<&str>) -> Result<Value> {
|
||||
let priced_micros = self.priced_submicros / i128::from(crate::inventory::UNIT);
|
||||
let micros = (self.unpriced_shares == 0).then_some(priced_micros);
|
||||
let value = micros
|
||||
.map(|n| format!("{}.{:06}", n / 1_000_000, n % 1_000_000).parse::<Number>())
|
||||
.transpose()?;
|
||||
Ok(
|
||||
json!({"scope":if market.is_some() {"market"} else {"global"},
|
||||
"condition_id":market.unwrap_or("GLOBAL"),"value":value,"value_micros":micros,
|
||||
"gross_shares":crate::inventory::decimal(self.shares,crate::inventory::UNIT),"unpriced_shares":crate::inventory::decimal(self.unpriced_shares,crate::inventory::UNIT),
|
||||
"priced_value_micros":priced_micros}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let selected = self.market.as_ref().map(IdSelector::ids).transpose()?;
|
||||
let ids = selected.as_ref().map(serde_json::to_string).transpose()?;
|
||||
let data = aggregate(db, ids.as_deref(), false)?
|
||||
.into_iter()
|
||||
.map(|(market, interest)| interest.row(selected.as_ref().map(|_| market.as_str())))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
|
||||
fn aggregate(
|
||||
db: &Connection,
|
||||
ids: Option<&str>,
|
||||
public: bool,
|
||||
) -> Result<BTreeMap<String, Interest>> {
|
||||
let mut stmt = db.prepare_cached(include_str!("open_interest.sql"))?;
|
||||
let mut rows = stmt.query(params![ids, public])?;
|
||||
let mut totals = BTreeMap::<String, Interest>::new();
|
||||
if ids.is_none() {
|
||||
totals.entry("GLOBAL".into()).or_default();
|
||||
}
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let key = if ids.is_some() {
|
||||
market.as_str()
|
||||
} else {
|
||||
"GLOBAL"
|
||||
};
|
||||
let interest = totals.entry(key.to_owned()).or_default();
|
||||
let Some(shares) = row.get::<_, Option<i64>>(3)? else {
|
||||
continue;
|
||||
};
|
||||
if shares == 0 {
|
||||
continue;
|
||||
}
|
||||
let outcome: String = row.get(2)?;
|
||||
let phase: String = row.get(1)?;
|
||||
let price = portfolio::price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
|
||||
let value = price.map(|p| i128::from(p) * i128::from(shares));
|
||||
interest.add(shares, value);
|
||||
}
|
||||
Ok(totals)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct InterestQuery {
|
||||
#[serde(alias = "conditionId", alias = "condition_id")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_open_interest(&self, query: InterestQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
let ids = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let totals =
|
||||
aggregate(&tx, ids.as_deref(), true).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = Vec::with_capacity(totals.len());
|
||||
for (market, interest) in totals {
|
||||
if interest.unpriced_shares > 0 {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
data.push(json!({"condition_id":market,"value":decimal(interest.priced_submicros,1_000_000_000_000)}));
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
WITH requested(id) AS (
|
||||
SELECT value FROM json_each(?1)
|
||||
), candidates AS (
|
||||
SELECT id,phase FROM markets WHERE ?1 IS NULL
|
||||
UNION ALL
|
||||
SELECT id,phase FROM markets WHERE id IN (
|
||||
SELECT id FROM requested
|
||||
UNION ALL
|
||||
SELECT m.id FROM requested r JOIN markets m ON m.id=r.id COLLATE NOCASE
|
||||
WHERE ?2 AND length(r.id)=66 AND r.id GLOB '0x*' AND substr(r.id,3) NOT GLOB '*[^0-9a-fA-F]*'
|
||||
)
|
||||
), selected AS MATERIALIZED (
|
||||
SELECT m.id,m.phase FROM candidates m
|
||||
LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
LEFT JOIN market_visibility v ON v.market=m.id
|
||||
WHERE (a.role IS NULL OR a.role<>'placeholder')
|
||||
AND (NOT ?2 OR (COALESCE(v.active,1) AND NOT COALESCE(v.archived,0)))
|
||||
), balances AS (
|
||||
SELECT s.id,p.outcome,SUM(p.available+p.reserved) AS shares,p.payout_per_share
|
||||
FROM selected s CROSS JOIN position_units p ON p.market=s.id
|
||||
GROUP BY s.id,p.outcome,p.payout_per_share
|
||||
)
|
||||
SELECT s.id,s.phase,b.outcome,b.shares,b.payout_per_share
|
||||
FROM selected s LEFT JOIN balances b ON b.id=s.id
|
||||
ORDER BY s.id,b.outcome
|
||||
@@ -0,0 +1,20 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS order_submissions (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq),
|
||||
order_type TEXT NOT NULL,
|
||||
post_only INTEGER NOT NULL CHECK(post_only IN (0,1)),
|
||||
created_at INTEGER DEFAULT (unixepoch())
|
||||
);
|
||||
|
||||
-- Old receipts preserve the accepted instruction but do not record when it was submitted.
|
||||
INSERT INTO order_submissions(order_seq,order_type,post_only,created_at)
|
||||
SELECT o.seq, COALESCE(json_extract(r.payload,'$.tif'),
|
||||
CASE WHEN json_extract(r.payload,'$.op') IN ('market_buy','market_sell') THEN 'FAK'
|
||||
WHEN d.seq IS NOT NULL THEN 'GTD' ELSE 'GTC' END),
|
||||
COALESCE(json_extract(r.payload,'$.post_only'),0), NULL
|
||||
FROM requests r JOIN orders o ON o.seq=json_extract(r.response,'$.order')
|
||||
LEFT JOIN order_deadlines d ON d.seq=o.seq
|
||||
WHERE json_extract(r.payload,'$.op') IN ('order','market_buy','market_sell')
|
||||
AND json_type(r.response,'$.order')='integer'
|
||||
ON CONFLICT(order_seq) DO NOTHING;
|
||||
COMMIT;
|
||||
@@ -1,4 +1,10 @@
|
||||
use crate::validation::identifier;
|
||||
pub(crate) mod http;
|
||||
mod protocol;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
@@ -10,10 +16,29 @@ pub(crate) struct Filter {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
status: Option<String>,
|
||||
after: Option<(i64, String, String)>,
|
||||
after: Option<(SortKey, String, String)>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
enum SortKey {
|
||||
Legacy(i64),
|
||||
Fraction { micros: i64 },
|
||||
}
|
||||
impl SortKey {
|
||||
fn units(&self, status: &str) -> Result<i64> {
|
||||
match self {
|
||||
Self::Legacy(key) if status == "MERGEABLE" => key
|
||||
.checked_mul(UNIT)
|
||||
.ok_or_else(|| anyhow::anyhow!("position cursor overflow")),
|
||||
Self::Legacy(key) => Ok(*key),
|
||||
Self::Fraction { micros } if status == "MERGEABLE" => Ok(*micros),
|
||||
_ => anyhow::bail!("invalid position cursor"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
@@ -36,7 +61,7 @@ impl Filter {
|
||||
self.account,
|
||||
self.market,
|
||||
status,
|
||||
cursor.map(|c| c.0),
|
||||
cursor.map(|c| c.0.units(status)).transpose()?,
|
||||
cursor.map(|c| c.1.as_str()),
|
||||
cursor.map(|c| c.2.as_str()),
|
||||
limit + 1
|
||||
@@ -52,18 +77,89 @@ impl Filter {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let status: String = row.get(5)?;
|
||||
let row_status: String = row.get(5)?;
|
||||
let payout: Option<i64> = row.get(6)?;
|
||||
let pairs: i64 = row.get(7)?;
|
||||
let phase: String = row.get(13)?;
|
||||
let (mark, source) = price(db, &market, &outcome, &phase, payout)?.unzip();
|
||||
positions.push(json!({
|
||||
"asset_id":crate::assets::id(&market,&outcome),"market":market, "outcome":outcome, "status":status, "size":size,
|
||||
"current_price_micros":mark,"price_source":source,"current_value_micros":holding_value(size,mark),
|
||||
"asset_id":crate::assets::id(&market,&outcome),"market":market, "outcome":outcome, "status":row_status, "size":decimal(size.into(),UNIT),
|
||||
"neg_risk_group":row.get::<_,Option<String>>(10)?,
|
||||
"available_size":row.get::<_,i64>(3)?, "reserved_size":row.get::<_,i64>(4)?,
|
||||
"redeemable":status=="REDEEMABLE", "payout_cents":payout.map(|p|p*size),
|
||||
"mergeable":pairs>0, "available_pairs":row.get::<_,i64>(8)?
|
||||
"augmented_role":row.get::<_,Option<String>>(11)?,"outcome_name":row.get::<_,Option<String>>(12)?,
|
||||
"available_size":decimal(row.get::<_,i64>(3)?.into(),UNIT), "reserved_size":decimal(row.get::<_,i64>(4)?.into(),UNIT),
|
||||
"redeemable":row_status=="REDEEMABLE", "payout_cents":payout.map(|p|decimal(i128::from(p)*i128::from(size)/100,10000)),
|
||||
"mergeable":pairs>0, "available_pairs":decimal(row.get::<_,i64>(8)?.into(),UNIT)
|
||||
}));
|
||||
last = Some((row.get::<_, i64>(9)?, market, outcome));
|
||||
let key: i64 = row.get(9)?;
|
||||
let sort = if status != "MERGEABLE" {
|
||||
SortKey::Legacy(key)
|
||||
} else if key % UNIT == 0 {
|
||||
SortKey::Legacy(key / UNIT)
|
||||
} else {
|
||||
SortKey::Fraction { micros: key }
|
||||
};
|
||||
last = Some((sort, market, outcome));
|
||||
}
|
||||
Ok(json!({"positions":positions,"next_after":next_after}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn price(
|
||||
db: &Connection,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
phase: &str,
|
||||
payout: Option<i64>,
|
||||
) -> Result<Option<(i64, &'static str)>> {
|
||||
if let Some(p) = payout {
|
||||
return Ok(Some((p * 10000, "settlement")));
|
||||
}
|
||||
Ok(crate::quotes::Quote::current(db, market, outcome)?.mark(phase))
|
||||
}
|
||||
|
||||
pub(crate) fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
|
||||
if size == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
mark.map(|p| i128::from(p) * i128::from(size) / i128::from(UNIT))
|
||||
}
|
||||
|
||||
/// Total in units of (micro-share × micro-dollar per share), before final rounding.
|
||||
fn marked_holdings(
|
||||
db: &Connection,
|
||||
account: &str,
|
||||
conditions: Option<&str>,
|
||||
wallet_address: bool,
|
||||
) -> Result<(i128, u64)> {
|
||||
let mut stmt = db.prepare_cached(include_str!("portfolio/value.sql"))?;
|
||||
let mut rows = stmt.query(params![account, conditions, wallet_address])?;
|
||||
let mut priced = 0i128;
|
||||
let mut missing = 0u64;
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let phase: String = row.get(3)?;
|
||||
let mark = price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
|
||||
let size: i64 = row.get(2)?;
|
||||
match mark.map(|price| i128::from(price) * i128::from(size)) {
|
||||
Some(amount) => {
|
||||
priced = priced
|
||||
.checked_add(amount)
|
||||
.ok_or_else(|| anyhow::anyhow!("portfolio value overflow"))?
|
||||
}
|
||||
None => missing += 1,
|
||||
}
|
||||
}
|
||||
Ok((priced, missing))
|
||||
}
|
||||
|
||||
pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
let (priced, missing) = marked_holdings(db, account, None, false)?;
|
||||
let priced = priced / i128::from(UNIT);
|
||||
Ok(
|
||||
json!({"account":account,"value_micros":(missing==0).then_some(priced),
|
||||
"priced_value_micros":priced,"unpriced_positions":missing}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
WITH reserved AS (
|
||||
SELECT market,outcome,SUM(remaining) AS qty
|
||||
FROM orders
|
||||
WHERE account=?1 AND status='live' AND side='sell' AND (?2 IS NULL OR market=?2)
|
||||
GROUP BY market,outcome
|
||||
), balances AS (
|
||||
SELECT p.market,p.outcome,p.quantity AS available,COALESCE(r.qty,0) AS reserved,
|
||||
p.quantity+COALESCE(r.qty,0) AS size
|
||||
FROM positions p LEFT JOIN reserved r USING (market,outcome)
|
||||
WHERE p.account=?1 AND (?2 IS NULL OR p.market=?2)
|
||||
WITH balances AS (
|
||||
SELECT market,outcome,available,reserved,available+reserved AS size,phase,payout_per_share
|
||||
FROM position_units WHERE account=?1 AND (?2 IS NULL OR market=?2)
|
||||
), holdings AS (
|
||||
SELECT b.*,m.phase,
|
||||
CASE WHEN m.phase='resolved' THEN
|
||||
CASE WHEN m.winner='VOID' THEN 50 WHEN b.outcome=m.winner THEN 100 ELSE 0 END
|
||||
END AS payout_per_share,
|
||||
CASE WHEN m.phase<>'resolved' THEN MIN(b.size,COALESCE(other.size,0)) ELSE 0 END AS pairs,
|
||||
CASE WHEN m.phase<>'resolved' THEN MIN(b.available,COALESCE(other.available,0)) ELSE 0 END AS free_pairs
|
||||
FROM balances b JOIN markets m ON m.id=b.market
|
||||
SELECT b.*,
|
||||
CASE WHEN b.phase<>'resolved' THEN MIN(b.size,COALESCE(other.size,0)) ELSE 0 END AS pairs,
|
||||
CASE WHEN b.phase<>'resolved' THEN MIN(b.available,COALESCE(other.available,0)) ELSE 0 END AS free_pairs
|
||||
FROM balances b
|
||||
LEFT JOIN balances other ON other.market=b.market AND other.outcome<>b.outcome
|
||||
), filtered AS (
|
||||
SELECT *,CASE WHEN size=0 THEN 'CLOSED' WHEN phase='resolved' THEN 'REDEEMABLE' ELSE 'OPEN' END AS row_status,
|
||||
@@ -30,7 +20,7 @@ WITH reserved AS (
|
||||
WHEN 'MERGEABLE' THEN pairs>0
|
||||
END
|
||||
)
|
||||
SELECT market,outcome,size,available,reserved,row_status,payout_per_share,pairs,free_pairs,sort_key,n.group_id
|
||||
FROM filtered LEFT JOIN neg_risk_members n USING(market)
|
||||
SELECT market,outcome,size,available,reserved,row_status,payout_per_share,pairs,free_pairs,sort_key,n.group_id,a.role,a.name,phase
|
||||
FROM filtered LEFT JOIN neg_risk_members n USING(market) LEFT JOIN augmented_outcomes a USING(market)
|
||||
WHERE ?4 IS NULL OR (sort_key,market,outcome)>(?4,?5,?6)
|
||||
ORDER BY sort_key,market,outcome LIMIT ?7
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
use super::{marked_holdings, protocol::CONTRACTS};
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use rusqlite::TransactionBehavior;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ValueQuery {
|
||||
user: String,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_portfolio_value(&self, query: ValueQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
let user = &query.user;
|
||||
let wallet = hex_id(user, 40);
|
||||
if wallet {
|
||||
if CONTRACTS.iter().any(|c| c.eq_ignore_ascii_case(user)) {
|
||||
return Err(MarketDataError::Invalid(
|
||||
"protocol contract is not a user".into(),
|
||||
));
|
||||
}
|
||||
} else if user.trim().is_empty()
|
||||
|| !tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM accounts WHERE id=?)",
|
||||
[user],
|
||||
|r| r.get::<_, bool>(0),
|
||||
)?
|
||||
{
|
||||
return Err(MarketDataError::Invalid("invalid user".into()));
|
||||
}
|
||||
let conditions = condition_filter(query.condition.as_deref(), &tx)?;
|
||||
let (priced, missing) = marked_holdings(&tx, user, conditions.as_deref(), wallet)
|
||||
.map_err(|_| MarketDataError::Unavailable)?;
|
||||
if missing != 0 {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
// Four decimal places per dollar. Round once, after summing every holding.
|
||||
const QUANTUM: i128 = 100_000_000;
|
||||
let rounded = priced / QUANTUM + i128::from(priced % QUANTUM >= QUANTUM / 2);
|
||||
let proxy_wallet = if wallet {
|
||||
user.to_ascii_lowercase()
|
||||
} else {
|
||||
user.clone()
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":{"proxy_wallet":proxy_wallet,"value":decimal(rounded,10_000)}}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Polygon deployments listed at https://docs.polymarket.com/resources/contracts.
|
||||
// For upgradeable contracts, use the public proxy address.
|
||||
pub(super) const CONTRACTS: &[&str] = &[
|
||||
"0xE111180000d2663C0091e4f400237545B87B996B", // CTF Exchange
|
||||
"0xe2222d279d744050d28e00520010520000310F59", // Neg Risk CTF Exchange
|
||||
"0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296", // Neg Risk Adapter (CTF negative-risk approvals)
|
||||
"0x4D97DCd97eC945f40cF65F87097ACe5EA0476045", // Conditional Tokens (CTF)
|
||||
"0x006F54F7f9A22e0000CC2AB60031000000ae9fEF", // PositionManager Poly v2
|
||||
"0x12121212006e4CD160D18e3f00711DA5c3372600", // Router Poly v2
|
||||
"0x1000008dD9001B968442c1000017eaE6E0dA00Ba", // BinaryModule Poly v2
|
||||
"0x200000900045e3B6259600682756002200028933", // NegRiskModule Poly v2
|
||||
"0x30000034706C7d8e12009DAB006Be20000c031A8", // CombinatorialModule Poly v2
|
||||
"0xe3333700cA9d93003F00f0F71f8515005F6c00Aa", // ExchangeV3 Poly v2
|
||||
"0xa1200000d0002264C9a1698e001292D00E1b00af", // AutoRedeemer Poly v2
|
||||
"0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB", // pUSD — CollateralToken Poly v2
|
||||
"0x93070a847efEf7F70739046A929D47a521F5B8ee", // CollateralOnramp Poly v2
|
||||
"0x2957922Eb93258b93368531d39fAcCA3B4dC5854", // CollateralOfframp Poly v2
|
||||
"0xebC2459Ec962869ca4c0bd1E06368272732BCb08", // PermissionedRamp Poly v2
|
||||
"0xAdA100Db00Ca00073811820692005400218FcE1f", // CtfCollateralAdapter
|
||||
"0xadA2005600Dec949baf300f4C6120000bDB6eAab", // NegRiskCtfCollateralAdapter
|
||||
"0xCe84E053301A82937F90ee2C2c1889cAb1db25dE", // pUSD CollateralToken implementation
|
||||
"0x00000000000Fb5C9ADea0298D729A0CB3823Cc07", // Deposit Wallet Factory
|
||||
"0x7A18EDfe055488A3128f01F563e5B479D92ffc3a", // Deposit Wallet Beacon
|
||||
"0xaacfeea03eb1561c4e67d661e40682bd20e3541b", // Gnosis Safe Factory
|
||||
"0xaB45c5A4B0c941a2F231C04C3f49182e1A254052", // Polymarket Proxy Factory
|
||||
"0x6A9D222616C90FcA5754cd1333cFD9b7fb6a4F74", // UMA Adapter
|
||||
"0xCB1822859cEF82Cd2Eb4E6276C7916e692995130", // UMA Optimistic Oracle
|
||||
"0x0A0a0A0A8B00C51b7D810501b03F230028C04a87", // OracleAggregator Poly v2
|
||||
"0x000012e0009c84078c4924fba808A41b9f67527f", // OOReporterModule Poly v2
|
||||
"0xc12EC12E0000326890Ca5560dEf5EB5C22b16814", // ChainlinkReporterModule Poly v2
|
||||
"0x8Ef9D6d668798b1f363b305D916F30739d2b0419", // EOAReporterModule Poly v2
|
||||
"0x157Ce2d672854c848c9b79C49a8Cc6cc89176a49", // UmaCtfAdapter v3.1.0
|
||||
];
|
||||
@@ -0,0 +1,11 @@
|
||||
WITH owners(id) AS (
|
||||
SELECT ?1 WHERE NOT ?3
|
||||
UNION ALL
|
||||
SELECT id FROM accounts WHERE ?3 AND id=?1 COLLATE NOCASE
|
||||
)
|
||||
SELECT market,outcome,available+reserved AS size,phase,payout_per_share
|
||||
FROM position_units
|
||||
WHERE account IN (SELECT id FROM owners) AND available+reserved>0
|
||||
AND (?2 IS NULL OR
|
||||
CASE WHEN length(market)=66 AND market GLOB '0x*' AND substr(market,3) NOT GLOB '*[^0-9a-fA-F]*'
|
||||
THEN lower(market) ELSE market END IN (SELECT value FROM json_each(?2)))
|
||||
@@ -0,0 +1,94 @@
|
||||
-- Run once under the same write lock as the format check. Monetary history
|
||||
-- in trade_prices is already in micros and retains its original timestamps.
|
||||
CREATE TABLE order_price_format(version INTEGER PRIMARY KEY CHECK(version=1));
|
||||
INSERT INTO order_price_format
|
||||
SELECT CASE WHEN EXISTS(SELECT 1 FROM orders WHERE price NOT BETWEEN 0 AND 100)
|
||||
OR EXISTS(SELECT 1 FROM fills WHERE price NOT BETWEEN 0 AND 100)
|
||||
THEN 0 ELSE 1 END;
|
||||
UPDATE orders SET price=price*100;
|
||||
UPDATE fills SET price=price*100;
|
||||
UPDATE quote_events SET yes_bid=yes_bid*100,yes_ask=yes_ask*100;
|
||||
UPDATE last_asset_trades SET price=price*100;
|
||||
|
||||
-- Replace the historical 0..100 check. No foreign key references this table.
|
||||
CREATE TEMP TABLE migrate_paired_prices AS SELECT * FROM paired_fills;
|
||||
DROP TABLE paired_fills;
|
||||
CREATE TABLE IF NOT EXISTS paired_fills (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
|
||||
kind TEXT NOT NULL CHECK(kind IN ('mint','merge')),
|
||||
yes_order INTEGER NOT NULL REFERENCES orders, no_order INTEGER NOT NULL REFERENCES orders,
|
||||
yes_price INTEGER NOT NULL CHECK(yes_price BETWEEN 0 AND 10000),
|
||||
quantity INTEGER NOT NULL CHECK(quantity>0),
|
||||
at_ms INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
);
|
||||
INSERT INTO paired_fills(seq,market,kind,yes_order,no_order,yes_price,quantity,at_ms)
|
||||
SELECT seq,market,kind,yes_order,no_order,yes_price*100,quantity,at_ms FROM migrate_paired_prices;
|
||||
DROP TABLE temp.migrate_paired_prices;
|
||||
CREATE INDEX IF NOT EXISTS public_paired_time ON paired_fills(at_ms,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_history ON paired_fills(market,at_ms,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_yes ON paired_fills(yes_order,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_no ON paired_fills(no_order,seq);
|
||||
|
||||
DROP TRIGGER IF EXISTS record_trade_price;
|
||||
CREATE TRIGGER IF NOT EXISTS record_trade_price AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO trade_prices(fill,market,outcome,at_ms,price_micros,quantity)
|
||||
SELECT NEW.seq,market,outcome,CAST(unixepoch('subsec')*1000 AS INTEGER),
|
||||
NEW.price*100,NEW.quantity FROM orders WHERE seq=NEW.bid;
|
||||
END;
|
||||
|
||||
DROP VIEW IF EXISTS visible_orders;
|
||||
CREATE VIEW IF NOT EXISTS visible_orders AS
|
||||
SELECT market,outcome,side,price,remaining FROM orders WHERE status='live'
|
||||
UNION ALL
|
||||
SELECT market,CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,
|
||||
CASE side WHEN 'buy' THEN 'sell' ELSE 'buy' END,10000-price,remaining
|
||||
FROM orders WHERE status='live';
|
||||
|
||||
DROP VIEW IF EXISTS outcome_trade_prices;
|
||||
CREATE VIEW IF NOT EXISTS outcome_trade_prices AS
|
||||
SELECT fill,market,outcome,at_ms,price_micros,quantity FROM trade_prices
|
||||
UNION ALL SELECT seq,market,'YES',at_ms,yes_price*100,quantity FROM paired_fills
|
||||
UNION ALL SELECT seq,market,'NO',at_ms,(10000-yes_price)*100,quantity FROM paired_fills;
|
||||
|
||||
DROP VIEW IF EXISTS wallet_trade_legs;
|
||||
CREATE VIEW IF NOT EXISTS wallet_trade_legs AS
|
||||
SELECT f.seq AS execution,o.seq AS order_seq,o.account,o.market,o.outcome,o.side,
|
||||
'transfer' AS kind,f.price,f.quantity,t.at_ms
|
||||
FROM fills f JOIN orders o ON o.seq=f.bid LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,o.account,o.market,o.outcome,o.side,'transfer',f.price,f.quantity,t.at_ms
|
||||
FROM fills f JOIN orders o ON o.seq=f.ask LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,o.account,o.market,o.outcome,o.side,f.kind,f.yes_price,f.quantity,f.at_ms
|
||||
FROM paired_fills f JOIN orders o ON o.seq=f.yes_order
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,o.account,o.market,o.outcome,o.side,f.kind,10000-f.yes_price,f.quantity,f.at_ms
|
||||
FROM paired_fills f JOIN orders o ON o.seq=f.no_order;
|
||||
|
||||
DROP VIEW IF EXISTS changed_quotes;
|
||||
CREATE VIEW IF NOT EXISTS changed_quotes AS
|
||||
WITH edges AS MATERIALIZED (
|
||||
SELECT p.market,
|
||||
(SELECT MAX(price) FROM orders WHERE market=p.market AND outcome='YES' AND side='buy' AND status='live') AS direct_bid,
|
||||
(SELECT MIN(price) FROM orders WHERE market=p.market AND outcome='YES' AND side='sell' AND status='live') AS direct_ask,
|
||||
10000-(SELECT MIN(price) FROM orders WHERE market=p.market AND outcome='NO' AND side='sell' AND status='live') AS reflected_bid,
|
||||
10000-(SELECT MAX(price) FROM orders WHERE market=p.market AND outcome='NO' AND side='buy' AND status='live') AS reflected_ask,
|
||||
(SELECT MAX(seq) FROM quote_events WHERE market=p.market) AS previous
|
||||
FROM quote_pending p
|
||||
), best AS (
|
||||
SELECT market,previous,
|
||||
COALESCE(MAX(direct_bid,reflected_bid),direct_bid,reflected_bid) AS bid,
|
||||
COALESCE(MIN(direct_ask,reflected_ask),direct_ask,reflected_ask) AS ask
|
||||
FROM edges
|
||||
)
|
||||
SELECT b.market,b.bid,b.ask,CAST(unixepoch('subsec')*1000 AS INTEGER) AS at_ms
|
||||
FROM best b LEFT JOIN quote_events old ON old.seq=b.previous
|
||||
WHERE b.bid IS NOT old.yes_bid OR b.ask IS NOT old.yes_ask;
|
||||
|
||||
DROP TRIGGER IF EXISTS last_asset_paired;
|
||||
CREATE TRIGGER IF NOT EXISTS last_asset_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO last_asset_trades VALUES
|
||||
(NEW.market,'YES',NEW.seq,NEW.yes_price),(NEW.market,'NO',NEW.seq,10000-NEW.yes_price)
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
END;
|
||||
@@ -0,0 +1,194 @@
|
||||
pub(crate) mod http;
|
||||
pub(crate) mod legacy;
|
||||
use anyhow::{bail, ensure, Result};
|
||||
use rusqlite::{params, Connection, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const DAY: i64 = 86400;
|
||||
const MAX_SECONDS: i64 = i64::MAX / 1000;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
market: String,
|
||||
outcome: String,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
interval: Option<String>,
|
||||
as_of: Option<i64>,
|
||||
bucket_seconds: Option<i64>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<Cursor>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Cursor {
|
||||
market: String,
|
||||
outcome: String,
|
||||
start: i64,
|
||||
end: i64,
|
||||
width: i64,
|
||||
limit: u32,
|
||||
last: i64,
|
||||
fill_cap: i64,
|
||||
settlement_cap: i64,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
fn window(&self, now: i64) -> Result<(i64, i64, i64)> {
|
||||
if let Some(width) = self.bucket_seconds {
|
||||
ensure!((60..=DAY).contains(&width), "invalid bucket_seconds");
|
||||
}
|
||||
if let Some(interval) = self.interval.as_deref() {
|
||||
ensure!(
|
||||
self.start.is_none() && self.end.is_none(),
|
||||
"interval conflicts with absolute range"
|
||||
);
|
||||
let (span, default, floor) = match interval {
|
||||
"1h" => (3600, 60, 60),
|
||||
"6h" => (21600, 60, 60),
|
||||
"1d" => (DAY, 60, 60),
|
||||
"1w" => (7 * DAY, 300, 300),
|
||||
"1m" => (30 * DAY, 1800, 600),
|
||||
"max" | "all" => (0, 43200, 600),
|
||||
_ => bail!("unknown interval"),
|
||||
};
|
||||
let width = self.bucket_seconds.unwrap_or(default).max(floor);
|
||||
let start = if span > 0 {
|
||||
(now - span).max(0)
|
||||
} else if width < 43200 && width != 10800 {
|
||||
(now - 30 * DAY).max(0)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
return Ok((start, now, width));
|
||||
}
|
||||
let start = self
|
||||
.start
|
||||
.ok_or_else(|| anyhow::anyhow!("start, interval or as_of required"))?;
|
||||
let end = self.end.unwrap_or(now);
|
||||
ensure!(
|
||||
start >= 0 && end <= MAX_SECONDS && start < end && end - start <= 15 * DAY,
|
||||
"invalid explicit range"
|
||||
);
|
||||
let span = end - start;
|
||||
let default = if span <= 12 * 3600 {
|
||||
60
|
||||
} else if span <= 2500 * 300 {
|
||||
300
|
||||
} else {
|
||||
1800
|
||||
};
|
||||
Ok((start, end, self.bucket_seconds.unwrap_or(default)))
|
||||
}
|
||||
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
crate::validation::identifier(&self.market)?;
|
||||
let exists: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(exists, "unknown market");
|
||||
if let Some(t) = self.as_of {
|
||||
ensure!(
|
||||
(0..=MAX_SECONDS).contains(&t)
|
||||
&& self.start.is_none()
|
||||
&& self.end.is_none()
|
||||
&& self.interval.is_none()
|
||||
&& self.bucket_seconds.is_none()
|
||||
&& self.limit.is_none()
|
||||
&& self.cursor.is_none(),
|
||||
"invalid as_of parameters"
|
||||
);
|
||||
let mut stmt=db.prepare(
|
||||
"SELECT at_ms/1000,price,0,source FROM (
|
||||
SELECT at_ms,fill AS seq,0 AS priority,price_micros AS price,'trade' AS source
|
||||
FROM outcome_trade_prices WHERE market=?1 AND outcome=?2 AND at_ms<=?3
|
||||
UNION ALL SELECT at_ms,id,1,CASE WHEN winner='VOID' THEN 500000 WHEN winner=?2 THEN 1000000 ELSE 0 END,'local_settlement'
|
||||
FROM price_settlements WHERE market=?1 AND at_ms<=?3
|
||||
) ORDER BY at_ms DESC,priority DESC,seq DESC LIMIT 1")?;
|
||||
let data = stmt
|
||||
.query_map(params![self.market, self.outcome, t * 1000], point)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
return Ok(json!({"data":data,"pagination":{"has_more":false,"next_cursor":null}}));
|
||||
}
|
||||
let mut page = if let Some(cursor) = self.cursor.as_ref() {
|
||||
ensure!(
|
||||
self.start.is_none()
|
||||
&& self.end.is_none()
|
||||
&& self.interval.is_none()
|
||||
&& self.bucket_seconds.is_none()
|
||||
&& self.limit.is_none()
|
||||
&& cursor.fill_cap >= 0
|
||||
&& cursor.settlement_cap >= 0
|
||||
&& cursor.market == self.market
|
||||
&& cursor.outcome == self.outcome
|
||||
&& cursor.start >= 0
|
||||
&& cursor.end <= MAX_SECONDS
|
||||
&& cursor.start < cursor.end
|
||||
&& (cursor.start..=cursor.end).contains(&cursor.last)
|
||||
&& (60..=DAY).contains(&cursor.width)
|
||||
&& (1..=10000).contains(&cursor.limit),
|
||||
"invalid continuation"
|
||||
);
|
||||
cursor.clone()
|
||||
} else {
|
||||
let now: i64 = db.query_row("SELECT unixepoch()+1", [], |r| r.get(0))?;
|
||||
let (start, end, width) = self.window(now)?;
|
||||
let limit = self.limit.unwrap_or(10000);
|
||||
ensure!((1..=10000).contains(&limit), "invalid limit");
|
||||
let (fill_cap,settlement_cap)=db.query_row("SELECT id-1,(SELECT COALESCE(MAX(id),0) FROM price_settlements) FROM next_execution",[],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
||||
Cursor {
|
||||
market: self.market,
|
||||
outcome: self.outcome,
|
||||
start,
|
||||
end,
|
||||
width,
|
||||
limit,
|
||||
last: -1,
|
||||
fill_cap,
|
||||
settlement_cap,
|
||||
}
|
||||
};
|
||||
let mut stmt = db.prepare(include_str!("prices_history.sql"))?;
|
||||
let mut rows = stmt.query(params![
|
||||
page.market,
|
||||
page.outcome,
|
||||
page.start,
|
||||
page.end,
|
||||
page.width,
|
||||
page.fill_cap,
|
||||
page.settlement_cap,
|
||||
page.last,
|
||||
page.limit + 1
|
||||
])?;
|
||||
let mut data = Vec::new();
|
||||
let mut more = false;
|
||||
while let Some(r) = rows.next()? {
|
||||
if data.len() == page.limit as usize {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
page.last = r.get(0)?;
|
||||
data.push(point(r)?);
|
||||
}
|
||||
Ok(
|
||||
json!({"data":data,"pagination":{"limit":page.limit,"has_more":more,"next_cursor":more.then_some(&page)}}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn point(r: &Row) -> rusqlite::Result<Value> {
|
||||
let micros: i64 = r.get(1)?;
|
||||
Ok(
|
||||
json!({"timestamp":r.get::<_,i64>(0)?,"price":micros as f64/1_000_000.0,
|
||||
"resolution_seconds":r.get::<_,i64>(2)?,"source":r.get::<_,String>(3)?}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Choose the last actual fill in each UTC bucket. The exact last trade
|
||||
-- and simulated payout are separate points; exact data wins a timestamp tie.
|
||||
WITH ticks AS (
|
||||
SELECT at_ms,fill,price_micros,at_ms/1000/?5*?5 AS bucket
|
||||
FROM outcome_trade_prices WHERE market=?1 AND outcome=?2
|
||||
AND at_ms>=?3*1000 AND at_ms<?4*1000 AND fill<=?6
|
||||
), ranked AS (
|
||||
SELECT *,ROW_NUMBER() OVER (PARTITION BY bucket ORDER BY at_ms DESC,fill DESC) AS rank
|
||||
FROM ticks
|
||||
), terminal AS (
|
||||
SELECT * FROM ticks ORDER BY at_ms DESC,fill DESC LIMIT 1
|
||||
), points(ts,price,width,source,priority) AS (
|
||||
SELECT MAX(?3,bucket),price_micros,?5,'trade',0 FROM ranked WHERE rank=1
|
||||
UNION ALL
|
||||
SELECT at_ms/1000,price_micros,0,'trade',1 FROM terminal
|
||||
UNION ALL
|
||||
SELECT MIN(?4,COALESCE((SELECT bucket+?5 FROM terminal),s.at_ms/1000)),
|
||||
CASE WHEN s.winner='VOID' THEN 500000 WHEN s.winner=?2 THEN 1000000 ELSE 0 END,
|
||||
0,'local_settlement',2
|
||||
FROM price_settlements s WHERE s.market=?1 AND s.at_ms>=?3*1000 AND s.at_ms<?4*1000 AND s.id<=?7
|
||||
), distinct_points AS (
|
||||
SELECT *,ROW_NUMBER() OVER(PARTITION BY ts ORDER BY priority DESC) AS preferred FROM points
|
||||
)
|
||||
SELECT ts,price,width,source FROM distinct_points
|
||||
WHERE preferred=1 AND ts>?8 ORDER BY ts LIMIT ?9
|
||||
@@ -0,0 +1,15 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE INDEX IF NOT EXISTS quote_market_time ON quote_events(market,at_ms,seq);
|
||||
CREATE TABLE IF NOT EXISTS chart_origins (
|
||||
market TEXT PRIMARY KEY REFERENCES markets,
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS chart_market_listed AFTER INSERT ON markets BEGIN
|
||||
INSERT INTO chart_origins VALUES(NEW.id,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
-- Existing books have reliable history from their first recorded quote. For
|
||||
-- markets without one, recording starts at the migration's observation time.
|
||||
INSERT OR IGNORE INTO chart_origins
|
||||
SELECT id,COALESCE((SELECT MIN(at_ms) FROM quote_events WHERE market=m.id),
|
||||
CAST(unixepoch('subsec')*1000 AS INTEGER)) FROM markets m;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,136 @@
|
||||
use super::{Cursor, Request};
|
||||
use crate::{assets, Exchange, HistoryError};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct HistoryQuery {
|
||||
#[serde(alias = "tokenId")]
|
||||
token_id: String,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
interval: Option<String>,
|
||||
#[serde(alias = "bucketSeconds")]
|
||||
bucket_seconds: Option<i64>,
|
||||
#[serde(alias = "asOf")]
|
||||
as_of: Option<i64>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
struct Continuation {
|
||||
page: Cursor,
|
||||
offset: u64,
|
||||
// Clients may resend the original window with their cursor.
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
interval: Option<String>,
|
||||
bucket_seconds: Option<i64>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_price_history(&self, query: HistoryQuery) -> Result<Value, HistoryError> {
|
||||
let tx = self
|
||||
.db
|
||||
.unchecked_transaction()
|
||||
.map_err(|_| HistoryError::Unavailable)?;
|
||||
let response = query.read(&tx).map_err(|err| {
|
||||
if err.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
HistoryError::Unavailable
|
||||
} else {
|
||||
HistoryError::Invalid(err.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit().map_err(|_| HistoryError::Unavailable)?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryQuery {
|
||||
fn read(mut self, db: &rusqlite::Connection) -> Result<Value> {
|
||||
let (outcome, market) = assets::parse_id(&self.token_id)?;
|
||||
let mut offset: u64 = 0;
|
||||
let mut page_size = self.limit.unwrap_or(10000);
|
||||
let mut request = Request {
|
||||
market: market.to_owned(),
|
||||
outcome: outcome.to_owned(),
|
||||
start: self.start,
|
||||
end: self.end,
|
||||
interval: self.interval.clone(),
|
||||
bucket_seconds: self.bucket_seconds,
|
||||
as_of: self.as_of,
|
||||
limit: self.limit,
|
||||
cursor: None,
|
||||
};
|
||||
if let Some(encoded) = self.cursor {
|
||||
let unpack = || -> Option<Continuation> {
|
||||
serde_json::from_slice(&BASE64URL_NOPAD.decode(encoded.as_bytes()).ok()?).ok()
|
||||
};
|
||||
let prior = unpack().context("invalid cursor")?;
|
||||
ensure!(
|
||||
self.as_of.is_none()
|
||||
&& self.start.is_none_or(|n| Some(n) == prior.start)
|
||||
&& self.end.is_none_or(|n| Some(n) == prior.end)
|
||||
&& self
|
||||
.interval
|
||||
.as_ref()
|
||||
.is_none_or(|s| Some(s) == prior.interval.as_ref())
|
||||
&& self
|
||||
.bucket_seconds
|
||||
.is_none_or(|n| Some(n) == prior.bucket_seconds),
|
||||
"window differs from cursor"
|
||||
);
|
||||
offset = prior.offset;
|
||||
page_size = prior.page.limit;
|
||||
self.start = prior.start;
|
||||
self.end = prior.end;
|
||||
self.interval = prior.interval;
|
||||
self.bucket_seconds = prior.bucket_seconds;
|
||||
request.start = None;
|
||||
request.end = None;
|
||||
request.interval = None;
|
||||
request.bucket_seconds = None;
|
||||
request.limit = None;
|
||||
request.cursor = Some(prior.page);
|
||||
} else if page_size == 0 {
|
||||
// A zero-sized first page cannot advance a cursor. Validate the window first.
|
||||
request.limit = if self.as_of.is_some() { None } else { Some(1) };
|
||||
} else if self.as_of.is_some() {
|
||||
ensure!(page_size <= 10000, "invalid limit");
|
||||
request.limit = None;
|
||||
}
|
||||
let mut result = request.read(db)?;
|
||||
let data = result["data"]
|
||||
.as_array_mut()
|
||||
.context("invalid history page")?;
|
||||
for point in data.iter_mut() {
|
||||
if let Some(fields) = point.as_object_mut() {
|
||||
fields.remove("source");
|
||||
}
|
||||
}
|
||||
if page_size == 0 {
|
||||
data.clear();
|
||||
}
|
||||
let count = data.len() as u64;
|
||||
let next = &result["pagination"]["next_cursor"];
|
||||
let cursor = if next.is_null() || page_size == 0 {
|
||||
None
|
||||
} else {
|
||||
let carry = Continuation {
|
||||
page: serde_json::from_value(next.clone())?,
|
||||
offset: offset.checked_add(count).context("invalid cursor offset")?,
|
||||
start: self.start,
|
||||
end: self.end,
|
||||
interval: self.interval,
|
||||
bucket_seconds: self.bucket_seconds,
|
||||
};
|
||||
Some(BASE64URL_NOPAD.encode(&serde_json::to_vec(&carry)?))
|
||||
};
|
||||
Ok(json!({"data":result["data"].take(),"pagination":{
|
||||
"has_more":cursor.is_some(),"next_cursor":cursor,"limit":page_size,"offset":offset
|
||||
}}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
use crate::{assets, inventory, Exchange, HistoryError};
|
||||
use rusqlite::params;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ClobHistoryQuery {
|
||||
market: String,
|
||||
#[serde(rename = "startTs")]
|
||||
start: Option<f64>,
|
||||
#[serde(rename = "endTs")]
|
||||
end: Option<f64>,
|
||||
interval: Option<String>,
|
||||
fidelity: Option<i64>,
|
||||
}
|
||||
|
||||
impl ClobHistoryQuery {
|
||||
fn window(&self, now: i64) -> Result<(i64, i64, i64), HistoryError> {
|
||||
let invalid = |reason: &str| HistoryError::Invalid(format!("invalid filters: {reason}"));
|
||||
for n in [self.start, self.end].into_iter().flatten() {
|
||||
if !n.is_finite() || !(0.0..=f64::from(u32::MAX)).contains(&n) {
|
||||
return Err(invalid("invalid timestamp"));
|
||||
}
|
||||
}
|
||||
let start = self.start.unwrap_or(0.0);
|
||||
let end = self.end.unwrap_or(0.0);
|
||||
if end > 0.0 {
|
||||
if start > end {
|
||||
return Err(invalid(
|
||||
"invalid time component, 'startTs' can't be older than 'endTs'",
|
||||
));
|
||||
}
|
||||
if end - start > (15 * super::DAY) as f64 {
|
||||
return Err(invalid("'startTs' and 'endTs' interval is too long"));
|
||||
}
|
||||
}
|
||||
let minutes = self.fidelity.unwrap_or(1).max(1);
|
||||
let width = minutes.min(i64::from(u32::MAX)) * 60_000;
|
||||
if let Some(interval) = self.interval.as_deref() {
|
||||
let (span, minimum) = match interval {
|
||||
"1h" => (3600, 1),
|
||||
"6h" => (21600, 1),
|
||||
"1d" => (super::DAY, 1),
|
||||
"1w" => (7 * super::DAY, 5),
|
||||
"1m" => (30 * super::DAY, 10),
|
||||
"max" | "all" => return Ok((0, now, width)),
|
||||
_ => return Err(invalid(
|
||||
"the 'interval' value is unknown. Known values: '1m', '1w', '1d', '6h', '1h'",
|
||||
)),
|
||||
};
|
||||
if minutes < minimum {
|
||||
return Err(invalid(&format!(
|
||||
"minimum 'fidelity' for '{interval}' range is {minimum}"
|
||||
)));
|
||||
}
|
||||
return Ok(((now - span * 1000).max(0), now, width));
|
||||
}
|
||||
if start == 0.0 && end == 0.0 {
|
||||
return Err(invalid(
|
||||
"the time component is mandatory, please use 'startTs' and 'endTs' or 'interval'",
|
||||
));
|
||||
}
|
||||
Ok((
|
||||
boundary_ms(start, f64::ceil),
|
||||
if end == 0.0 {
|
||||
now
|
||||
} else {
|
||||
boundary_ms(end, f64::floor)
|
||||
},
|
||||
width,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
// Multiplying a decimal timestamp such as 1.001 by 1000 can land below its
|
||||
// exact millisecond. Preserve that point before rounding sub-ms boundaries.
|
||||
fn boundary_ms(seconds: f64, round: fn(f64) -> f64) -> i64 {
|
||||
let ms = seconds * 1000.0;
|
||||
let nearest = ms.round() as i64;
|
||||
if nearest as f64 / 1000.0 == seconds {
|
||||
nearest
|
||||
} else {
|
||||
round(ms) as i64
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn clob_price_history(&self, query: ClobHistoryQuery) -> Result<Value, HistoryError> {
|
||||
let (outcome, market) = assets::parse_id(&query.market)
|
||||
.map_err(|_| HistoryError::Invalid("invalid market asset id".into()))?;
|
||||
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)
|
||||
.map_err(|_| HistoryError::Unavailable)?;
|
||||
let now: i64 = tx.query_row(
|
||||
"SELECT CAST(unixepoch('subsec') * 1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let (start, end, width) = query.window(now)?;
|
||||
let points = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("legacy.sql"))?;
|
||||
let rows = stmt.query_map(params![market, outcome, start, end, width, now], |r| {
|
||||
let timestamp: i64 = r.get(0)?;
|
||||
let micros: i64 = r.get(1)?;
|
||||
Ok(json!({"t":timestamp,"p":inventory::decimal(micros.into(), inventory::UNIT)}))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
tx.commit()?;
|
||||
Ok(json!({"history":points}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
-- Reconstruct public midpoint observations from committed book changes.
|
||||
-- The local sampler uses a UTC minute grid. The venue's collector has clock jitter.
|
||||
WITH RECURSIVE horizon AS (
|
||||
SELECT (SELECT at_ms FROM chart_origins WHERE market=?1) AS first_ms,
|
||||
(SELECT at_ms FROM price_settlements WHERE market=?1) AS resolved_ms,
|
||||
(SELECT winner FROM price_settlements WHERE market=?1) AS winner,
|
||||
(SELECT phase FROM markets WHERE id=?1) AS phase
|
||||
), bounds AS (
|
||||
SELECT first_ms, resolved_ms, winner,
|
||||
CASE WHEN phase='resolved' THEN COALESCE(resolved_ms,
|
||||
(SELECT MAX(at_ms) FROM quote_events WHERE market=?1))
|
||||
ELSE ?6/60000*60000 END AS last_ms
|
||||
FROM horizon
|
||||
), grid(ms) AS (
|
||||
SELECT ((MAX(?3,first_ms)+?5-1)/?5)*?5 FROM bounds
|
||||
WHERE ((MAX(?3,first_ms)+?5-1)/?5)*?5 <= MIN(?4,last_ms)
|
||||
UNION ALL
|
||||
SELECT ms+?5 FROM grid,bounds WHERE ms+?5 <= MIN(?4,last_ms)
|
||||
), points(ms,tail) AS (
|
||||
SELECT ms,0 FROM grid
|
||||
UNION ALL
|
||||
SELECT last_ms,1 FROM bounds WHERE resolved_ms IS NOT NULL OR first_ms<=last_ms
|
||||
)
|
||||
SELECT points.ms/1000,
|
||||
CASE WHEN points.ms=b.resolved_ms THEN
|
||||
CASE WHEN b.winner='VOID' THEN 500000 WHEN b.winner=?2 THEN 1000000 ELSE 0 END
|
||||
WHEN ?2='YES' THEN (COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50
|
||||
ELSE 1000000-(COALESCE(q.yes_bid,0)+COALESCE(q.yes_ask,10000))*50 END
|
||||
FROM points CROSS JOIN bounds b
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=?1 AND at_ms<=points.ms
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
)
|
||||
ORDER BY points.ms,points.tail
|
||||
@@ -0,0 +1,174 @@
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::{assets, validation::IdSelector};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{named_params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Filters {
|
||||
market: Option<IdSelector>,
|
||||
event: Option<IdSelector>,
|
||||
side: Option<String>,
|
||||
taker_only: Option<bool>,
|
||||
filter_type: Option<String>,
|
||||
filter_amount: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Page {
|
||||
filters: Filters,
|
||||
limit: u32,
|
||||
before: (i64, i64, i64),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
market: Option<IdSelector>,
|
||||
event: Option<IdSelector>,
|
||||
side: Option<String>,
|
||||
taker_only: Option<bool>,
|
||||
filter_type: Option<String>,
|
||||
filter_amount: Option<f64>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
let now: i64 = db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let filters = Filters {
|
||||
market: self.market,
|
||||
event: self.event,
|
||||
side: self.side,
|
||||
taker_only: self.taker_only,
|
||||
filter_type: self.filter_type,
|
||||
filter_amount: self.filter_amount,
|
||||
};
|
||||
let mut page = if let Some(cursor) = self.cursor {
|
||||
let page: Page =
|
||||
serde_json::from_str(&cursor).context("invalid public trades cursor")?;
|
||||
ensure!(
|
||||
filters == Filters::default() || filters == page.filters,
|
||||
"cursor filters differ"
|
||||
);
|
||||
page
|
||||
} else {
|
||||
Page {
|
||||
filters,
|
||||
limit: self.limit.unwrap_or(100),
|
||||
before: (now, i64::MAX, i64::MAX),
|
||||
}
|
||||
};
|
||||
let (at, execution, order) = page.before;
|
||||
ensure!(
|
||||
page.limit <= 1000 && at >= 0 && at <= now && execution > 0 && order > 0,
|
||||
"invalid trade page"
|
||||
);
|
||||
let scoped = page.filters.market.is_some() || page.filters.event.is_some();
|
||||
let start: i64 = db.query_row(
|
||||
"SELECT CASE WHEN ?1 THEN CAST(unixepoch(?2/1000.0,'unixepoch','-3 years','subsec')*1000 AS INTEGER)
|
||||
ELSE unixepoch(?2/1000.0,'unixepoch','start of month','-1 month')*1000 END",
|
||||
rusqlite::params![scoped, now],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let scan = Scan {
|
||||
start,
|
||||
end: at,
|
||||
before: page.before,
|
||||
limit: page.limit,
|
||||
user: None,
|
||||
numeric_events: false,
|
||||
};
|
||||
let (data,next) = scan.read(db,&page.filters, |r| {
|
||||
let market: String = r.get(4)?;
|
||||
let outcome: String = r.get(5)?;
|
||||
let price: i64 = r.get(8)?;
|
||||
let size: i64 = r.get(9)?;
|
||||
Ok(json!({"at_ms":r.get::<_,i64>(0)?,"execution":r.get::<_,i64>(1)?,"account":r.get::<_,String>(3)?,"market":market,
|
||||
"outcome":outcome,"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(6)?,
|
||||
"kind":r.get::<_,String>(7)?,"price_micros":price*100,"size":crate::lots::display(size),"gross_cents":crate::inventory::decimal(i128::from(price)*i128::from(size),10000),
|
||||
"role":r.get::<_,Option<String>>(10)?}))
|
||||
})?;
|
||||
let next = if let Some(anchor) = next {
|
||||
page.before = anchor;
|
||||
Some(serde_json::to_string(&page)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({"data":data,"next_cursor":next}))
|
||||
}
|
||||
}
|
||||
|
||||
type Anchor = (i64, i64, i64);
|
||||
|
||||
struct Scan<'a> {
|
||||
start: i64,
|
||||
end: i64,
|
||||
before: Anchor,
|
||||
limit: u32,
|
||||
user: Option<&'a str>,
|
||||
numeric_events: bool,
|
||||
}
|
||||
impl Scan<'_> {
|
||||
fn read(
|
||||
&self,
|
||||
db: &Connection,
|
||||
f: &Filters,
|
||||
render: impl Fn(&rusqlite::Row<'_>) -> rusqlite::Result<Value>,
|
||||
) -> Result<(Vec<Value>, Option<Anchor>)> {
|
||||
let side = match f.side.as_deref() {
|
||||
None => None,
|
||||
Some("BUY" | "buy") => Some("buy"),
|
||||
Some("SELL" | "sell") => Some("sell"),
|
||||
_ => anyhow::bail!("invalid side"),
|
||||
};
|
||||
let cash = match f.filter_type.as_deref().unwrap_or("TOKENS") {
|
||||
"CASH" => true,
|
||||
"TOKENS" => false,
|
||||
_ => anyhow::bail!("expected CASH or TOKENS"),
|
||||
};
|
||||
let threshold = f.filter_amount.unwrap_or(0.01);
|
||||
ensure!(
|
||||
threshold.is_finite() && threshold >= 0.0,
|
||||
"invalid minimum trade size"
|
||||
);
|
||||
let minimum = if threshold == 0.0 { 0.01 } else { threshold };
|
||||
let (at, execution, order) = self.before;
|
||||
let fetch_limit = if self.limit == 0 { 0 } else { self.limit + 1 };
|
||||
let mut stmt = db.prepare_cached(include_str!("public_trades.sql"))?;
|
||||
let mut rows=stmt.query(named_params!{
|
||||
":markets":selector_json(f.market.as_ref())?, ":events":selector_json(f.event.as_ref())?,
|
||||
":numeric_events":self.numeric_events, ":user":self.user, ":side":side,
|
||||
":taker_only":f.taker_only.unwrap_or(true), ":cash":cash, ":minimum":minimum,
|
||||
":start":self.start, ":end":self.end, ":before_ms":at, ":before_execution":execution, ":before_order":order, ":limit":fetch_limit,
|
||||
})?;
|
||||
let mut data = Vec::new();
|
||||
let mut anchor = None;
|
||||
while let Some(r) = rows.next()? {
|
||||
if data.len() == self.limit as usize {
|
||||
return Ok((data, anchor));
|
||||
}
|
||||
data.push(render(r)?);
|
||||
anchor = Some((r.get(0)?, r.get(1)?, r.get(2)?));
|
||||
}
|
||||
Ok((data, None))
|
||||
}
|
||||
}
|
||||
|
||||
fn selector_json(selector: Option<&IdSelector>) -> Result<Option<String>> {
|
||||
selector
|
||||
.map(|selector| {
|
||||
let ids = selector.ids()?;
|
||||
Ok(serde_json::to_string(&ids)?)
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
WITH selected_events AS (
|
||||
SELECT s.market FROM listed_markets s
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
WHERE ((NOT :numeric_events AND s.event IN (SELECT value FROM json_each(:events)))
|
||||
OR (:numeric_events AND s.event IN (SELECT event FROM event_directory_ids WHERE id IN (SELECT value FROM json_each(:events)))))
|
||||
AND (a.role IS NULL OR a.role<>'placeholder')
|
||||
), executions AS (
|
||||
SELECT p.at_ms,p.fill AS execution,p.market,f.bid AS first_order,f.ask AS second_order,
|
||||
f.price,f.quantity,'transfer' AS kind
|
||||
FROM trade_prices p JOIN fills f ON f.seq=p.fill
|
||||
WHERE p.at_ms BETWEEN :start AND MIN(:end,:before_ms) AND (p.at_ms,p.fill)<=(:before_ms,:before_execution)
|
||||
UNION ALL
|
||||
SELECT at_ms,seq,market,yes_order,no_order,yes_price,quantity,kind FROM paired_fills
|
||||
WHERE at_ms BETWEEN :start AND MIN(:end,:before_ms) AND (at_ms,seq)<=(:before_ms,:before_execution)
|
||||
), legs AS (
|
||||
SELECT e.at_ms,e.execution,e.market,o.seq AS order_seq,o.account,o.outcome,o.side,e.kind,
|
||||
CASE WHEN e.kind<>'transfer' AND o.seq=e.second_order THEN 10000-e.price ELSE e.price END AS price,
|
||||
e.quantity,
|
||||
CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction'
|
||||
WHEN c.taker_order=o.seq THEN 'taker' ELSE 'maker' END AS role
|
||||
FROM executions e JOIN orders o ON o.seq IN (e.first_order,e.second_order)
|
||||
LEFT JOIN execution_context c ON c.execution=e.execution
|
||||
WHERE (:markets IS NULL OR e.market IN (SELECT value FROM json_each(:markets)))
|
||||
AND (:events IS NULL OR e.market IN (SELECT market FROM selected_events))
|
||||
AND (:user IS NULL OR o.account=:user)
|
||||
AND (:side IS NULL OR o.side=:side)
|
||||
AND (NOT :taker_only OR c.taker_order=o.seq)
|
||||
AND (e.at_ms,e.execution,o.seq)<(:before_ms,:before_execution,:before_order)
|
||||
), page AS (
|
||||
SELECT * FROM legs WHERE CASE WHEN :cash THEN price*quantity/1000000.0 ELSE quantity/100.0 END >= :minimum
|
||||
ORDER BY at_ms DESC,execution DESC,order_seq DESC LIMIT :limit
|
||||
)
|
||||
SELECT p.at_ms,p.execution,p.order_seq,p.account,p.market,p.outcome,p.side,p.kind,p.price,p.quantity,p.role,
|
||||
w.question,w.slug,w.yes_label,w.no_label,COALESCE(t.slug,s.event,'') AS event_slug
|
||||
FROM page p JOIN market_wire_metadata w ON w.market=p.market
|
||||
LEFT JOIN topic_markets tm ON tm.market=p.market LEFT JOIN topics t ON t.id=tm.event
|
||||
LEFT JOIN sports_markets s ON s.market=p.market
|
||||
ORDER BY p.at_ms DESC,p.execution DESC,p.order_seq DESC
|
||||
@@ -0,0 +1,181 @@
|
||||
use super::{Anchor, Filters, Scan};
|
||||
use crate::{
|
||||
assets, inventory, lots,
|
||||
validation::{directory_selector, identifier},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{Connection, Row};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TradeQuery {
|
||||
user: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
#[serde(alias = "eventId")]
|
||||
event_id: Option<String>,
|
||||
side: Option<String>,
|
||||
#[serde(alias = "takerOnly")]
|
||||
taker_only: Option<bool>,
|
||||
#[serde(alias = "filterType")]
|
||||
filter_type: Option<String>,
|
||||
#[serde(alias = "filterAmount")]
|
||||
filter_amount: Option<f64>,
|
||||
start: Option<i64>,
|
||||
end: Option<i64>,
|
||||
limit: Option<u32>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Cursor {
|
||||
before: Anchor,
|
||||
limit: u32,
|
||||
offset: u64,
|
||||
}
|
||||
|
||||
impl Cursor {
|
||||
fn mac(db: &Connection) -> Result<Hmac<Sha256>> {
|
||||
let key: Vec<u8> = db.query_row(
|
||||
"SELECT secret FROM trade_cursor_key WHERE singleton=1",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut mac =
|
||||
Hmac::<Sha256>::new_from_slice(&key).expect("HMAC accepts arbitrary key lengths");
|
||||
mac.update(b"eventbook:/v2/trades:v1\0");
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
fn encode(&self, db: &Connection) -> Result<String> {
|
||||
let mut bytes = serde_json::to_vec(self)?;
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(&bytes);
|
||||
bytes.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&bytes))
|
||||
}
|
||||
|
||||
fn decode(db: &Connection, token: &str) -> Result<Self> {
|
||||
ensure!(token.len() <= 512, "invalid trade cursor");
|
||||
let bytes = BASE64URL_NOPAD
|
||||
.decode(token.as_bytes())
|
||||
.context("invalid trade cursor")?;
|
||||
let split = bytes
|
||||
.len()
|
||||
.checked_sub(32)
|
||||
.context("invalid trade cursor")?;
|
||||
let (payload, signature) = bytes.split_at(split);
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(payload);
|
||||
mac.verify_slice(signature)
|
||||
.map_err(|_| anyhow::anyhow!("invalid trade cursor"))?;
|
||||
Ok(serde_json::from_slice(payload)?)
|
||||
}
|
||||
}
|
||||
|
||||
fn trade(row: &Row<'_>) -> rusqlite::Result<Value> {
|
||||
let market: String = row.get(4)?;
|
||||
let outcome: String = row.get(5)?;
|
||||
let price: i64 = row.get(8)?;
|
||||
let yes = outcome == "YES";
|
||||
Ok(
|
||||
json!({"proxy_wallet":row.get::<_,String>(3)?,"side":row.get::<_,String>(6)?.to_ascii_uppercase(),
|
||||
"token_id":assets::id(&market,&outcome),"condition_id":market,"size":lots::display(row.get(9)?),
|
||||
"price":inventory::decimal(price.into(),crate::tick_size::PAR),"timestamp":row.get::<_,i64>(0)?/1000,
|
||||
"title":row.get::<_,String>(11)?,"slug":row.get::<_,String>(12)?,"icon":"","event_slug":row.get::<_,String>(15)?,
|
||||
"outcome":row.get::<_,String>(if yes {13} else {14})?,"outcome_index":if yes {0} else {1},
|
||||
"name":"","pseudonym":"","bio":"","profile_image":"","profile_image_optimized":"","transaction_hash":""}),
|
||||
)
|
||||
}
|
||||
|
||||
impl TradeQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value> {
|
||||
if let Some(user) = &self.user {
|
||||
identifier(user)?;
|
||||
}
|
||||
let market = directory_selector(db, self.condition.as_deref(), false)?;
|
||||
let event = directory_selector(db, self.event_id.as_deref(), true)?;
|
||||
let scoped = self.user.is_some() || market.is_some() || event.is_some();
|
||||
let (now,default_start):(i64,i64)=db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER),CASE WHEN ?1 THEN CAST(unixepoch('now','-3 years','subsec')*1000 AS INTEGER) ELSE unixepoch('now','start of month','-1 month')*1000 END",
|
||||
[scoped],|r|Ok((r.get(0)?,r.get(1)?)))?;
|
||||
let (start, end) = if self.user.is_some() {
|
||||
let millis = |v: i64| -> Result<i64> {
|
||||
ensure!(v >= 0, "negative timestamp");
|
||||
v.checked_mul(1000).context("timestamp too large")
|
||||
};
|
||||
let start = match self.start.unwrap_or(0) {
|
||||
0 => default_start,
|
||||
n => millis(n)?,
|
||||
};
|
||||
let end = match self.end.unwrap_or(0) {
|
||||
0 => now + 86_400_000,
|
||||
n => millis(n)?.checked_add(999).context("timestamp too large")?,
|
||||
};
|
||||
ensure!(start <= end, "invalid trade window");
|
||||
(start, end)
|
||||
} else {
|
||||
(default_start, now)
|
||||
};
|
||||
let page = match self.cursor {
|
||||
Some(token) => Cursor::decode(db, &token)?,
|
||||
None => Cursor {
|
||||
before: (i64::MAX, i64::MAX, i64::MAX),
|
||||
limit: self.limit.unwrap_or(100),
|
||||
offset: 0,
|
||||
},
|
||||
};
|
||||
ensure!(page.limit <= 1000, "invalid limit");
|
||||
let filters = Filters {
|
||||
market,
|
||||
event,
|
||||
side: self.side,
|
||||
taker_only: self.taker_only,
|
||||
filter_type: self.filter_type,
|
||||
filter_amount: self.filter_amount,
|
||||
};
|
||||
let scan = Scan {
|
||||
start,
|
||||
end,
|
||||
before: page.before,
|
||||
limit: page.limit,
|
||||
user: self.user.as_deref(),
|
||||
numeric_events: true,
|
||||
};
|
||||
let (data, next) = scan.read(db, &filters, trade)?;
|
||||
let cursor = next
|
||||
.map(|before| {
|
||||
Cursor {
|
||||
before,
|
||||
limit: page.limit,
|
||||
offset: page.offset + data.len() as u64,
|
||||
}
|
||||
.encode(db)
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(
|
||||
json!({"data":data,"pagination":{"limit":page.limit,"offset":page.offset,"has_more":cursor.is_some(),"next_cursor":cursor}}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_trade_feed(&self, query: TradeQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let result = query.read(&tx).map_err(|err| {
|
||||
if err.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
MarketDataError::Unavailable
|
||||
} else {
|
||||
MarketDataError::Invalid(err.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS quote_events (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
|
||||
yes_bid INTEGER, yes_ask INTEGER, at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS quote_market_seq ON quote_events(market,seq);
|
||||
CREATE INDEX IF NOT EXISTS live_order_price ON orders(market,outcome,side,price) WHERE status='live';
|
||||
CREATE TABLE IF NOT EXISTS quote_pending (market TEXT PRIMARY KEY);
|
||||
CREATE TRIGGER IF NOT EXISTS mark_quote_insert AFTER INSERT ON orders WHEN NEW.status='live' BEGIN
|
||||
INSERT OR IGNORE INTO quote_pending VALUES(NEW.market);
|
||||
END;
|
||||
-- Order market, side, outcome and price are immutable. Only entering or
|
||||
-- leaving the live set can change the best price of an existing order.
|
||||
CREATE TRIGGER IF NOT EXISTS mark_quote_status AFTER UPDATE OF status ON orders
|
||||
WHEN (OLD.status='live')<>(NEW.status='live') BEGIN
|
||||
INSERT OR IGNORE INTO quote_pending VALUES(NEW.market);
|
||||
END;
|
||||
|
||||
-- Capture the final book of a successful command in its receipt transaction.
|
||||
CREATE TRIGGER IF NOT EXISTS record_quote_on_receipt AFTER INSERT ON requests
|
||||
WHEN EXISTS(SELECT 1 FROM quote_pending) BEGIN
|
||||
INSERT INTO quote_events(market,yes_bid,yes_ask,at_ms) SELECT * FROM changed_quotes;
|
||||
DELETE FROM quote_pending;
|
||||
END;
|
||||
|
||||
-- On first install, observe the current live book, without dating it to the
|
||||
-- original order time. Concurrent installers can only enqueue another diff.
|
||||
INSERT OR IGNORE INTO quote_pending SELECT DISTINCT market FROM orders WHERE status='live';
|
||||
COMMIT;
|
||||
@@ -0,0 +1,355 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Row, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(crate) fn flush(tx: &Transaction) -> Result<()> {
|
||||
tx.execute_batch(
|
||||
"INSERT INTO quote_events(market,yes_bid,yes_ask,at_ms) SELECT * FROM changed_quotes;
|
||||
DELETE FROM quote_pending;",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Quote {
|
||||
pub seq: i64,
|
||||
pub bid: Option<i64>,
|
||||
pub ask: Option<i64>,
|
||||
at_ms: Option<i64>,
|
||||
pub last: Option<i64>,
|
||||
}
|
||||
impl Quote {
|
||||
fn read(row: &Row, outcome: &str) -> rusqlite::Result<Self> {
|
||||
let bid: Option<i64> = row.get(1)?;
|
||||
let ask: Option<i64> = row.get(2)?;
|
||||
let (bid, ask) = if outcome == "YES" {
|
||||
(bid, ask)
|
||||
} else {
|
||||
(
|
||||
ask.map(|p| crate::tick_size::PAR - p),
|
||||
bid.map(|p| crate::tick_size::PAR - p),
|
||||
)
|
||||
};
|
||||
Ok(Self {
|
||||
seq: row.get(0)?,
|
||||
bid,
|
||||
ask,
|
||||
at_ms: row.get(3)?,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn current(db: &Connection, market: &str, outcome: &str) -> Result<Self> {
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,t.price
|
||||
FROM (SELECT ?1 AS market) s LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT MAX(seq) FROM quote_events WHERE market=s.market)
|
||||
LEFT JOIN last_asset_trades t ON t.market=s.market AND t.outcome=?2",
|
||||
)?;
|
||||
Ok(stmt.query_row(params![market, outcome], |r| {
|
||||
let mut quote = Self::read(r, outcome)?;
|
||||
quote.last = r.get(4)?;
|
||||
Ok(quote)
|
||||
})?)
|
||||
}
|
||||
|
||||
pub fn mark(&self, phase: &str) -> Option<(i64, &'static str)> {
|
||||
display_price(self.bid, self.ask, self.last, phase)
|
||||
}
|
||||
|
||||
fn public_sides(&self) -> (i64, i64) {
|
||||
(
|
||||
self.bid.unwrap_or(0),
|
||||
self.ask.unwrap_or(crate::tick_size::PAR),
|
||||
)
|
||||
}
|
||||
|
||||
fn spread_micros(&self) -> Option<i64> {
|
||||
Some((self.ask? - self.bid?) * 100)
|
||||
}
|
||||
|
||||
fn midpoint_micros(&self) -> Option<i64> {
|
||||
Some((self.ask? + self.bid?) * 50)
|
||||
}
|
||||
|
||||
fn event(&self) -> Value {
|
||||
json!({"seq":self.seq,"at_ms":self.at_ms,"best_bid_micros":self.bid.map(|p|p*100),
|
||||
"best_ask_micros":self.ask.map(|p|p*100),"spread_micros":self.spread_micros(),
|
||||
"midpoint_micros":self.midpoint_micros()})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn display_price(
|
||||
bid: Option<i64>,
|
||||
ask: Option<i64>,
|
||||
last: Option<i64>,
|
||||
phase: &str,
|
||||
) -> Option<(i64, &'static str)> {
|
||||
if phase == "continuous" {
|
||||
if let (Some(b), Some(a)) = (bid, ask) {
|
||||
if (0..=1000).contains(&(a - b)) {
|
||||
return Some(((a + b) * 50, "midpoint"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(phase, "continuous" | "closed") {
|
||||
return last.map(|p| (p * 100, "last_trade"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
market: String,
|
||||
outcome: String,
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
ensure!(
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
[&self.market],
|
||||
|r| r.get::<_, bool>(0)
|
||||
)?,
|
||||
"unknown market"
|
||||
);
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
(1..=1000).contains(&limit) && self.after >= 0,
|
||||
"invalid quote history pagination"
|
||||
);
|
||||
let mut stmt=db.prepare("SELECT seq,yes_bid,yes_ask,at_ms FROM quote_events WHERE market=?1 AND seq>?2 ORDER BY seq LIMIT ?3")?;
|
||||
let mut rows = stmt.query(params![self.market, self.after, limit + 1])?;
|
||||
let mut points = Vec::new();
|
||||
let mut cursor = self.after;
|
||||
let mut more = false;
|
||||
while let Some(row) = rows.next()? {
|
||||
if points.len() == limit as usize {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
let q = Quote::read(row, &self.outcome)?;
|
||||
cursor = q.seq;
|
||||
points.push(q.event());
|
||||
}
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&self.market,&self.outcome),"points":points,"cursor":cursor,"has_more":more}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum PriceSide {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PriceRequest {
|
||||
pub token_id: String,
|
||||
pub side: PriceSide,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PriceQueryError {
|
||||
RequestCount,
|
||||
InvalidToken,
|
||||
MissingBook,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PriceQueryError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(match self {
|
||||
Self::RequestCount => "expected 1 to 500 price requests",
|
||||
Self::InvalidToken => "invalid Eventbook asset_id",
|
||||
Self::MissingBook => "unknown Eventbook asset_id",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for PriceQueryError {}
|
||||
|
||||
impl PriceRequest {
|
||||
fn label(&self) -> &'static str {
|
||||
match self.side {
|
||||
PriceSide::Buy => "BUY",
|
||||
PriceSide::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn single(&self, db: &Connection) -> Result<Value> {
|
||||
let mut rows = price_rows(db, std::slice::from_ref(self))?;
|
||||
Ok(json!({"price": rows.pop().flatten()}))
|
||||
}
|
||||
}
|
||||
|
||||
// Use the last committed top of book, even when only one side has liquidity.
|
||||
// All requested markets share the caller's read snapshot.
|
||||
fn price_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<String>>> {
|
||||
quote_rows(db, requests)?
|
||||
.into_iter()
|
||||
.zip(requests)
|
||||
.map(|(quote, request)| {
|
||||
let quote = quote.ok_or(PriceQueryError::MissingBook)?;
|
||||
let price = match request.side {
|
||||
PriceSide::Buy => quote.ask,
|
||||
PriceSide::Sell => quote.bid,
|
||||
};
|
||||
Ok(price.map(|p| {
|
||||
let mut text = format!("{}.{:04}", p / 10000, p % 10000);
|
||||
while text.len() > 4 && text.ends_with('0') {
|
||||
text.pop();
|
||||
}
|
||||
text
|
||||
}))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn quote_rows(db: &Connection, requests: &[PriceRequest]) -> Result<Vec<Option<Quote>>> {
|
||||
if !(1..=500).contains(&requests.len()) {
|
||||
return Err(PriceQueryError::RequestCount.into());
|
||||
}
|
||||
let mut markets = Vec::with_capacity(requests.len());
|
||||
let mut outcomes = Vec::with_capacity(requests.len());
|
||||
for request in requests {
|
||||
let (outcome, market) =
|
||||
assets::parse_id(&request.token_id).map_err(|_| PriceQueryError::InvalidToken)?;
|
||||
markets.push(market);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,m.id,j.key
|
||||
FROM json_each(?1) j LEFT JOIN markets m ON m.id=j.value
|
||||
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)
|
||||
ORDER BY j.key",
|
||||
)?;
|
||||
let mut rows = stmt.query([serde_json::to_string(&markets)?])?;
|
||||
let mut quotes = Vec::with_capacity(requests.len());
|
||||
while let Some(row) = rows.next()? {
|
||||
let index: usize = row.get(5)?;
|
||||
let exists = row.get::<_, Option<String>>(4)?.is_some();
|
||||
quotes.push(
|
||||
exists
|
||||
.then(|| Quote::read(row, outcomes[index]))
|
||||
.transpose()?,
|
||||
);
|
||||
}
|
||||
Ok(quotes)
|
||||
}
|
||||
|
||||
pub(crate) fn prices(db: &Connection, requests: &[PriceRequest]) -> Result<Value> {
|
||||
price_map(db, requests, true)
|
||||
}
|
||||
|
||||
fn price_map(db: &Connection, requests: &[PriceRequest], include_empty: bool) -> Result<Value> {
|
||||
let mut result = json!({});
|
||||
for (request, price) in requests.iter().zip(price_rows(db, requests)?) {
|
||||
if price.is_none() && !include_empty {
|
||||
continue;
|
||||
}
|
||||
let number = price
|
||||
.as_deref()
|
||||
.map(str::parse::<serde_json::Number>)
|
||||
.transpose()?;
|
||||
result[request.token_id.as_str()][request.label()] = json!(number);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
impl crate::Exchange {
|
||||
pub fn execution_price(&self, request: &PriceRequest) -> Result<Value> {
|
||||
request.single(&self.db)
|
||||
}
|
||||
|
||||
pub fn execution_prices(&self, requests: &[PriceRequest]) -> Result<Value> {
|
||||
price_map(&self.db, requests, false)
|
||||
}
|
||||
|
||||
/// Public CLOB side prices refer to resting orders on the named side.
|
||||
pub fn public_book_prices(&self, requests: &[PriceRequest]) -> Result<Value> {
|
||||
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)?;
|
||||
let mut result = json!({});
|
||||
for (request, quote) in requests.iter().zip(quote_rows(&tx, requests)?) {
|
||||
if let Some(quote) = quote {
|
||||
let (bid, ask) = quote.public_sides();
|
||||
let ticks = match request.side {
|
||||
PriceSide::Buy => bid,
|
||||
PriceSide::Sell => ask,
|
||||
};
|
||||
let text = format!("{}.{:04}", ticks / 10000, ticks % 10000);
|
||||
result[request.token_id.as_str()][request.label()] =
|
||||
json!(text.trim_end_matches('0').trim_end_matches('.'));
|
||||
}
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub fn spreads(
|
||||
&self,
|
||||
tokens: &[String],
|
||||
) -> Result<BTreeMap<String, Option<String>>, crate::MarketDataError> {
|
||||
self.quote_values(tokens, |bid, ask| (ask - bid) * 100)
|
||||
}
|
||||
|
||||
pub fn midpoints(
|
||||
&self,
|
||||
tokens: &[String],
|
||||
) -> Result<BTreeMap<String, Option<String>>, crate::MarketDataError> {
|
||||
self.quote_values(tokens, |bid, ask| (ask + bid) * 50)
|
||||
}
|
||||
|
||||
fn quote_values(
|
||||
&self,
|
||||
tokens: &[String],
|
||||
measure: fn(i64, i64) -> i64,
|
||||
) -> Result<BTreeMap<String, Option<String>>, crate::MarketDataError> {
|
||||
if tokens.len() > 500 {
|
||||
return Err(crate::MarketDataError::Invalid("too many tokens".into()));
|
||||
}
|
||||
let assets = tokens
|
||||
.iter()
|
||||
.map(|token| assets::parse_id(token))
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map_err(|_| crate::MarketDataError::Invalid("invalid token id".into()))?;
|
||||
let input =
|
||||
serde_json::to_string(&assets).map_err(|_| crate::MarketDataError::Unavailable)?;
|
||||
let tx = crate::expiry::transaction(&self.db, rusqlite::TransactionBehavior::Deferred)
|
||||
.map_err(|_| crate::MarketDataError::Unavailable)?;
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,j.key FROM json_each(?1) j
|
||||
JOIN markets m ON m.id=json_extract(j.value,'$[1]')
|
||||
LEFT JOIN quote_events q ON q.seq=(SELECT MAX(seq) FROM quote_events WHERE market=m.id)"
|
||||
)?;
|
||||
let mut rows = stmt.query([input])?;
|
||||
let mut result = BTreeMap::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let index: usize = row.get(4)?;
|
||||
let quote = Quote::read(row, assets[index].0)?;
|
||||
let (bid, ask) = quote.public_sides();
|
||||
let micros = measure(bid, ask);
|
||||
let value =
|
||||
crate::inventory::decimal(micros.into(), crate::inventory::UNIT).to_string();
|
||||
result.insert(tokens[index].clone(), Some(value));
|
||||
}
|
||||
drop(rows);
|
||||
drop(stmt);
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,42 @@ impl Books {
|
||||
self.markets.get(market)?.get(outcome)
|
||||
}
|
||||
|
||||
/// The cash input to an exchange command is in cents, the share input in lots.
|
||||
pub fn protection_price(
|
||||
&self,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
side: Side,
|
||||
requested: i64,
|
||||
limit: Option<i64>,
|
||||
tif: crate::command::TimeInForce,
|
||||
) -> Option<i64> {
|
||||
limit.or_else(|| {
|
||||
// The reference Python SDK sums one binary64 value per public
|
||||
// price level, in dollars (BUY) or shares (SELL). Match its limit
|
||||
// selection here; all execution and settlement use integer units.
|
||||
let target = requested as f64 / 100.0;
|
||||
let mut depth = 0.0;
|
||||
let mut last = None;
|
||||
for (price, lots) in self.get(market, outcome)?.opposing_levels(side) {
|
||||
let shares = lots as f64 / crate::lots::PER_SHARE as f64;
|
||||
depth += match side {
|
||||
Side::Buy => shares * (price as f64 / crate::tick_size::PAR as f64),
|
||||
Side::Sell => shares,
|
||||
};
|
||||
last = Some(price);
|
||||
if depth >= target {
|
||||
return last;
|
||||
}
|
||||
}
|
||||
if tif == crate::command::TimeInForce::Fak {
|
||||
last
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn recover(tx: &Transaction) -> Result<Self> {
|
||||
let mut books = Self::default();
|
||||
let mut stmt = tx.prepare(
|
||||
@@ -91,7 +127,7 @@ impl Books {
|
||||
let reflected = Order {
|
||||
seq: order.seq,
|
||||
remaining: order.remaining,
|
||||
price: 100 - order.price,
|
||||
price: crate::tick_size::PAR - order.price,
|
||||
side: match order.side {
|
||||
Side::Buy => Side::Sell,
|
||||
Side::Sell => Side::Buy,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
|
||||
use crate::validation::identifier;
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction};
|
||||
@@ -9,6 +11,7 @@ use serde_json::{json, Value};
|
||||
pub(crate) enum Policy {
|
||||
Optimistic {
|
||||
eligible_at: i64,
|
||||
question_id: Option<String>,
|
||||
},
|
||||
Twap {
|
||||
stream: String,
|
||||
@@ -19,8 +22,11 @@ pub(crate) enum Policy {
|
||||
|
||||
impl Policy {
|
||||
pub fn save(self, tx: &Transaction, market: &str) -> Result<()> {
|
||||
let eligible_at = match self {
|
||||
Self::Optimistic { eligible_at } => eligible_at,
|
||||
let (eligible_at, question_id) = match self {
|
||||
Self::Optimistic {
|
||||
eligible_at,
|
||||
question_id,
|
||||
} => (eligible_at, question_id),
|
||||
Self::Twap {
|
||||
stream,
|
||||
start_at,
|
||||
@@ -32,10 +38,21 @@ impl Policy {
|
||||
"INSERT INTO optimistic_markets(market,eligible_at) VALUES(?,?)",
|
||||
params![market, eligible_at],
|
||||
)?;
|
||||
if let Some(id) = question_id {
|
||||
tx.execute(
|
||||
"INSERT INTO resolution_questions(market,question_id) VALUES(?,?)",
|
||||
params![market, question_key(&id)?],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn question_key(raw: &str) -> Result<String> {
|
||||
ensure!(crate::validation::hex_id(raw, 64), "invalid question_id");
|
||||
Ok(raw.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
pub(crate) fn propose(
|
||||
tx: &Transaction,
|
||||
market: &str,
|
||||
@@ -50,7 +67,7 @@ pub(crate) fn propose(
|
||||
);
|
||||
let changed=tx.execute(
|
||||
"INSERT INTO resolution_proposals(market,round,result,proposer,evidence,proposed_at)
|
||||
SELECT market,CASE status WHEN 'awaiting_second_proposal' THEN 2 ELSE 1 END,?2,?3,?4,unixepoch()
|
||||
SELECT market,CASE WHEN status='awaiting_second_proposal' OR verdict='TOO_EARLY' THEN 2 ELSE 1 END,?2,?3,?4,unixepoch()
|
||||
FROM market_resolution WHERE market=?1 AND status IN ('awaiting_proposal','awaiting_second_proposal')",
|
||||
params![market,winner,proposer,evidence])?;
|
||||
ensure!(changed == 1, "market is not accepting proposals");
|
||||
@@ -110,6 +127,25 @@ pub(crate) fn authorize_finalization(tx: &Transaction, market: &str, winner: &st
|
||||
}
|
||||
|
||||
pub(crate) fn read(db: &Connection, market: &str) -> Result<Value> {
|
||||
let mut state = policy_state(db, market)?;
|
||||
let (rules, resolved_at): (String, Option<i64>) = db.query_row(
|
||||
"SELECT m.rules,s.at_ms FROM markets m LEFT JOIN price_settlements s ON s.market=m.id WHERE m.id=?",
|
||||
[market], |row| Ok((row.get(0)?,row.get(1)?))
|
||||
)?;
|
||||
state["rules"] = json!(rules);
|
||||
state["resolved_at_ms"] = json!(resolved_at);
|
||||
// YES, NO token order from the binary CTF adapter. Only finalized markets have a winner.
|
||||
state["payouts"] = match state["winner"].as_str() {
|
||||
Some("YES") => json!([1, 0]),
|
||||
Some("NO") => json!([0, 1]),
|
||||
Some("VOID") => json!([1, 1]),
|
||||
_ => Value::Null,
|
||||
};
|
||||
state["clarifications"] = json!(crate::clarifications::for_resolution(db, market)?);
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn policy_state(db: &Connection, market: &str) -> Result<Value> {
|
||||
if let Some(data) = crate::twap::read(db, market)? {
|
||||
return Ok(data);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use super::question_key;
|
||||
use crate::{validation::directory_selector, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{named_params, Connection, Row};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResolutionQuery {
|
||||
#[serde(alias = "questionId")]
|
||||
question_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
#[serde(alias = "eventId")]
|
||||
event_id: Option<String>,
|
||||
}
|
||||
|
||||
fn oracle_price(result: Option<&str>) -> &'static str {
|
||||
match result {
|
||||
Some("YES") => "1000000000000000000",
|
||||
Some("NO") => "0",
|
||||
Some("VOID") => "500000000000000000",
|
||||
_ => "69",
|
||||
}
|
||||
}
|
||||
|
||||
fn resolution(row: &Row<'_>, by_question: bool) -> rusqlite::Result<Value> {
|
||||
let value = |key: &str| row.get::<_, Option<String>>(key);
|
||||
let winner = value("winner")?;
|
||||
let updated = if by_question {
|
||||
row.get::<_, Option<i64>>("updated_ms")?
|
||||
.map(|ms| (ms / 1000).to_string())
|
||||
} else {
|
||||
value("updated_at")?
|
||||
};
|
||||
let mut entry = json!({
|
||||
"status": row.get::<_,String>("status")?, "last_update_timestamp": updated.unwrap_or_default(),
|
||||
"was_disputed": row.get::<_,bool>("disputed")?, "was_arbitrated": row.get::<_,bool>("arbitrated")?,
|
||||
"extended_review": false, "new_version_q": false, "transaction_hash": "", "log_index": ""
|
||||
});
|
||||
if let Some(id) = value("question_id")? {
|
||||
entry["question_id"] = json!(id);
|
||||
}
|
||||
if let Some(expiry) = value("expires")? {
|
||||
entry["expected_settlement_time"] = json!(expiry);
|
||||
entry["settlement_time_basis"] = json!("proposal_expiration");
|
||||
}
|
||||
if by_question {
|
||||
entry["proposed_price"] = json!(oracle_price(value("first_price")?.as_deref()));
|
||||
entry["reproposed_price"] = json!(oracle_price(value("second_price")?.as_deref()));
|
||||
entry["price"] = json!(oracle_price(winner.as_deref()));
|
||||
} else {
|
||||
entry["condition_id"] = json!(row.get::<_, String>("market")?);
|
||||
if let Some(kind) = value("market_type")? {
|
||||
entry["market_type"] = json!(kind);
|
||||
}
|
||||
if let Some(time) = value("settled")? {
|
||||
entry["resolved_at"] = json!(time);
|
||||
}
|
||||
if let Some(result) = winner {
|
||||
entry["payouts"] = match result.as_str() {
|
||||
"YES" => json!([1_000_000, 0]),
|
||||
"NO" => json!([0, 1_000_000]),
|
||||
"VOID" => json!([500_000, 500_000]),
|
||||
_ => return Err(rusqlite::Error::InvalidQuery),
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
|
||||
impl ResolutionQuery {
|
||||
fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
[
|
||||
self.question_id.is_some(),
|
||||
self.condition.is_some(),
|
||||
self.event_id.is_some()
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|set| *set)
|
||||
.count()
|
||||
== 1,
|
||||
"supply exactly one of question_id, condition, event_id"
|
||||
);
|
||||
let question = self.question_id.as_deref().map(question_key).transpose()?;
|
||||
let ids = |raw: Option<&str>, numeric| -> Result<Option<String>> {
|
||||
directory_selector(db, raw, numeric)?
|
||||
.map(|s| Ok(serde_json::to_string(&s.ids()?)?))
|
||||
.transpose()
|
||||
};
|
||||
let mut stmt = db.prepare(include_str!("state.sql"))?;
|
||||
let data = stmt
|
||||
.query_map(
|
||||
named_params! {
|
||||
":question": question, ":conditions": ids(self.condition.as_deref(),false)?,
|
||||
":events": ids(self.event_id.as_deref(),true)?,
|
||||
},
|
||||
|row| resolution(row, question.is_some()),
|
||||
)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_resolutions(&self, query: ResolutionQuery) -> Result<Value, MarketDataError> {
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let page = query.read(&tx).map_err(|err| {
|
||||
if err.downcast_ref::<rusqlite::Error>().is_some() {
|
||||
MarketDataError::Unavailable
|
||||
} else {
|
||||
MarketDataError::Invalid(err.to_string())
|
||||
}
|
||||
})?;
|
||||
tx.commit()?;
|
||||
Ok(page)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
WITH selected(market) AS (
|
||||
SELECT value FROM json_each(:conditions)
|
||||
UNION SELECT market FROM resolution_questions WHERE question_id=:question
|
||||
UNION SELECT l.market FROM listed_markets l JOIN event_directory_ids d ON d.event=l.event
|
||||
WHERE d.id IN (SELECT value FROM json_each(:events))
|
||||
), lifecycle AS (
|
||||
SELECT m.market,m.winner,q.question_id,
|
||||
CASE WHEN m.phase='resolved' THEN 'resolved'
|
||||
WHEN p.verdict='TOO_EARLY' THEN 'challenged'
|
||||
WHEN p.challenged_at IS NOT NULL THEN CASE p.round WHEN 1 THEN 'challenged' ELSE 'disputed' END
|
||||
WHEN p.id IS NOT NULL THEN CASE p.round WHEN 1 THEN 'proposed' ELSE 'reproposed' END
|
||||
WHEN m.eligible_at IS NOT NULL THEN 'posed' ELSE 'active' END AS status,
|
||||
(SELECT EXISTS(SELECT 1 FROM resolution_proposals d WHERE d.market=m.market AND d.challenged_at IS NOT NULL)) AS disputed,
|
||||
(SELECT EXISTS(SELECT 1 FROM resolution_proposals d WHERE d.market=m.market AND d.round=2 AND d.challenged_at IS NOT NULL)) AS arbitrated,
|
||||
CASE WHEN p.round=1 OR p.verdict='TOO_EARLY' THEN p.result ELSE prev.result END AS first_price,
|
||||
CASE WHEN p.round=2 AND p.verdict IS NOT 'TOO_EARLY' THEN p.result END AS second_price,
|
||||
CASE WHEN m.winner IS NULL AND p.challenged_at IS NULL AND unixepoch()<p.proposed_at+7200
|
||||
THEN strftime('%Y-%m-%dT%H:%M:%SZ',p.proposed_at+7200,'unixepoch') END AS expires,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ',s.at_ms/1000.0,'unixepoch') AS settled,
|
||||
COALESCE(s.at_ms,1000*COALESCE(p.decided_at,p.challenged_at,p.proposed_at),
|
||||
CAST(json_extract(f.payload,'$.timestamp') AS INTEGER)) AS updated_ms,
|
||||
CASE WHEN g.market IS NULL THEN 'BINARY' END AS market_type
|
||||
FROM market_resolution m
|
||||
LEFT JOIN resolution_questions q ON q.market=m.market
|
||||
LEFT JOIN resolution_proposals p ON p.id=m.proposal
|
||||
LEFT JOIN resolution_proposals prev ON prev.id=(
|
||||
SELECT id FROM resolution_proposals WHERE market=m.market AND id<p.id ORDER BY id DESC LIMIT 1)
|
||||
LEFT JOIN price_settlements s ON s.market=m.market
|
||||
LEFT JOIN market_lifecycle_frames f ON f.market=m.market AND f.kind='new_market'
|
||||
LEFT JOIN augmented_outcomes a ON a.market=m.market
|
||||
LEFT JOIN neg_risk_members g ON g.market=m.market
|
||||
WHERE m.market IN (SELECT market FROM selected) AND (a.role IS NULL OR a.role<>'placeholder')
|
||||
)
|
||||
SELECT lifecycle.*,strftime('%Y-%m-%dT%H:%M:%fZ',updated_ms/1000.0,'unixepoch') AS updated_at
|
||||
FROM lifecycle ORDER BY market
|
||||
+173
-20
@@ -1,14 +1,28 @@
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id TEXT PRIMARY KEY, cash INTEGER NOT NULL CHECK(cash >= 0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS accounts_by_wallet ON accounts(id COLLATE NOCASE);
|
||||
CREATE TABLE IF NOT EXISTS markets (
|
||||
id TEXT PRIMARY KEY, rules TEXT NOT NULL, phase TEXT NOT NULL,
|
||||
collateral INTEGER NOT NULL DEFAULT 0 CHECK(collateral >= 0), winner TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_visibility (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
active INTEGER NOT NULL CHECK(active IN (0,1)), archived INTEGER NOT NULL CHECK(archived IN (0,1))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS market_condition_case ON markets(id COLLATE NOCASE);
|
||||
CREATE TABLE IF NOT EXISTS market_clarifications (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets(id),
|
||||
content TEXT NOT NULL CHECK(length(trim(content))>0),
|
||||
clear_book INTEGER NOT NULL CHECK(clear_book IN (0,1)),
|
||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS clarifications_by_market ON market_clarifications(market,id);
|
||||
CREATE TABLE IF NOT EXISTS positions (
|
||||
account TEXT REFERENCES accounts, market TEXT REFERENCES markets, outcome TEXT,
|
||||
quantity INTEGER NOT NULL CHECK(quantity >= 0), PRIMARY KEY(account,market,outcome)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS positions_by_market ON positions(market,account,outcome);
|
||||
CREATE TABLE IF NOT EXISTS orders (
|
||||
seq INTEGER PRIMARY KEY, account TEXT REFERENCES accounts, market TEXT REFERENCES markets,
|
||||
outcome TEXT NOT NULL, side TEXT NOT NULL, price INTEGER NOT NULL, quantity INTEGER NOT NULL,
|
||||
@@ -80,11 +94,6 @@ CREATE TABLE IF NOT EXISTS trade_prices (
|
||||
outcome TEXT NOT NULL, at_ms INTEGER NOT NULL, price_micros INTEGER NOT NULL, quantity INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS trade_series ON trade_prices(market,outcome,at_ms,fill);
|
||||
CREATE TRIGGER IF NOT EXISTS record_trade_price AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO trade_prices(fill,market,outcome,at_ms,price_micros,quantity)
|
||||
SELECT NEW.seq,market,outcome,CAST(unixepoch('subsec')*1000 AS INTEGER),
|
||||
NEW.price*10000,NEW.quantity FROM orders WHERE seq=NEW.bid;
|
||||
END;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS paired_fills (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES markets,
|
||||
@@ -94,22 +103,11 @@ CREATE TABLE IF NOT EXISTS paired_fills (
|
||||
quantity INTEGER NOT NULL CHECK(quantity>0),
|
||||
at_ms INTEGER NOT NULL DEFAULT (CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS paired_history ON paired_fills(market,at_ms,seq);
|
||||
CREATE INDEX IF NOT EXISTS public_direct_time ON trade_prices(at_ms,fill);
|
||||
|
||||
CREATE VIEW IF NOT EXISTS next_execution AS
|
||||
SELECT 1+MAX(COALESCE((SELECT MAX(seq) FROM fills),0),
|
||||
COALESCE((SELECT MAX(seq) FROM paired_fills),0)) AS id;
|
||||
CREATE VIEW IF NOT EXISTS outcome_trade_prices AS
|
||||
SELECT fill,market,outcome,at_ms,price_micros,quantity FROM trade_prices
|
||||
UNION ALL SELECT seq,market,'YES',at_ms,yes_price*10000,quantity FROM paired_fills
|
||||
UNION ALL SELECT seq,market,'NO',at_ms,(100-yes_price)*10000,quantity FROM paired_fills;
|
||||
|
||||
-- Each live binary order contributes once to each outcome's depth.
|
||||
CREATE VIEW IF NOT EXISTS visible_orders AS
|
||||
SELECT market,outcome,side,price,remaining FROM orders WHERE status='live'
|
||||
UNION ALL
|
||||
SELECT market,CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,
|
||||
CASE side WHEN 'buy' THEN 'sell' ELSE 'buy' END,100-price,remaining
|
||||
FROM orders WHERE status='live';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_deadlines (
|
||||
seq INTEGER PRIMARY KEY REFERENCES orders,
|
||||
@@ -128,14 +126,16 @@ CREATE TABLE IF NOT EXISTS execution_context (
|
||||
execution INTEGER PRIMARY KEY, taker_order INTEGER REFERENCES orders(seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS account_orders_history ON orders(account,seq);
|
||||
CREATE INDEX IF NOT EXISTS market_buy_orders ON orders(market,seq) WHERE side='buy';
|
||||
CREATE INDEX IF NOT EXISTS fills_by_bid ON fills(bid,seq);
|
||||
CREATE INDEX IF NOT EXISTS fills_by_ask ON fills(ask,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_yes ON paired_fills(yes_order,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_no ON paired_fills(no_order,seq);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS optimistic_markets (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), eligible_at INTEGER NOT NULL CHECK(eligible_at>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS resolution_questions (
|
||||
market TEXT PRIMARY KEY REFERENCES optimistic_markets(market), question_id TEXT NOT NULL UNIQUE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS resolution_proposals (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES optimistic_markets(market),
|
||||
round INTEGER NOT NULL CHECK(round IN (1,2)),
|
||||
@@ -196,7 +196,160 @@ CREATE TABLE IF NOT EXISTS neg_risk_groups (
|
||||
id TEXT PRIMARY KEY, reserve_cents INTEGER NOT NULL DEFAULT 0 CHECK(reserve_cents>=0),
|
||||
winner TEXT REFERENCES markets
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_conversion_fees (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id),
|
||||
bps INTEGER NOT NULL CHECK(bps BETWEEN 0 AND 10000),
|
||||
vault TEXT NOT NULL REFERENCES accounts(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_reserve_remainders (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS neg_risk_reserves AS
|
||||
SELECT g.id,g.winner,g.reserve_cents*10000+COALESCE(r.micros,0) AS micros
|
||||
FROM neg_risk_groups g LEFT JOIN neg_risk_reserve_remainders r ON r.group_id=g.id;
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_members (
|
||||
market TEXT PRIMARY KEY REFERENCES markets, group_id TEXT NOT NULL REFERENCES neg_risk_groups,
|
||||
ordinal INTEGER NOT NULL, UNIQUE(group_id,ordinal)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS augmented_outcomes (
|
||||
market TEXT PRIMARY KEY REFERENCES neg_risk_members(market),
|
||||
group_id TEXT NOT NULL REFERENCES neg_risk_groups(id),
|
||||
role TEXT NOT NULL CHECK(role IN ('named','placeholder','other')),
|
||||
name TEXT, question TEXT, clarification TEXT, named_at INTEGER,
|
||||
CHECK ((role='placeholder')=(name IS NULL)),
|
||||
UNIQUE(group_id,name)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS augmented_other ON augmented_outcomes(group_id) WHERE role='other';
|
||||
CREATE TABLE IF NOT EXISTS augmented_results (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id),
|
||||
observed_name TEXT NOT NULL, winner TEXT NOT NULL REFERENCES augmented_outcomes(market),
|
||||
evidence TEXT NOT NULL
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS reject_placeholder_orders BEFORE INSERT ON orders
|
||||
WHEN EXISTS(SELECT 1 FROM augmented_outcomes WHERE market=NEW.market AND role='placeholder')
|
||||
BEGIN SELECT RAISE(ABORT,'outcome has not been named'); END;
|
||||
|
||||
-- Existing resolved rows have no trustworthy settlement timestamp to backfill.
|
||||
CREATE TABLE IF NOT EXISTS price_settlements (
|
||||
id INTEGER PRIMARY KEY, market TEXT NOT NULL UNIQUE REFERENCES markets,
|
||||
winner TEXT NOT NULL, at_ms INTEGER NOT NULL
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS record_price_settlement AFTER UPDATE OF phase ON markets
|
||||
WHEN NEW.phase='resolved' AND OLD.phase<>'resolved' BEGIN
|
||||
INSERT INTO price_settlements(market,winner,at_ms)
|
||||
VALUES(NEW.id,NEW.winner,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
END;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_fee_rates (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), rate_ppm INTEGER NOT NULL CHECK(rate_ppm BETWEEN 0 AND 1000000)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_base_fees (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), maker_bps INTEGER NOT NULL CHECK(maker_bps>=0),
|
||||
taker_bps INTEGER NOT NULL CHECK(taker_bps>=0)
|
||||
);
|
||||
-- Older editions stored only the execution curve. Publish its coefficient as an
|
||||
-- integer basis-point default only when that conversion is exact.
|
||||
CREATE VIEW IF NOT EXISTS market_fee_terms AS
|
||||
SELECT m.id AS market, COALESCE(f.rate_ppm,0) AS rate_ppm, COALESCE(b.maker_bps,0) AS maker_bps,
|
||||
COALESCE(b.taker_bps,CASE WHEN COALESCE(f.rate_ppm,0)%100=0 THEN COALESCE(f.rate_ppm,0)/100 END) AS taker_bps
|
||||
FROM markets m LEFT JOIN market_fee_rates f ON f.market=m.id LEFT JOIN market_base_fees b ON b.market=m.id;
|
||||
CREATE TABLE IF NOT EXISTS cash_remainders (
|
||||
account TEXT PRIMARY KEY REFERENCES accounts(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS execution_fees (
|
||||
execution INTEGER PRIMARY KEY REFERENCES execution_context(execution),
|
||||
taker_order INTEGER NOT NULL REFERENCES orders(seq), fee_micros INTEGER NOT NULL CHECK(fee_micros>0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS fees_by_order ON execution_fees(taker_order);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_keys (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq), key_id TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS order_heartbeats (
|
||||
account TEXT NOT NULL REFERENCES accounts(id), key_id TEXT NOT NULL,
|
||||
heartbeat_id TEXT NOT NULL, deadline_ms INTEGER NOT NULL,
|
||||
PRIMARY KEY(account,key_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS heartbeat_deadlines ON order_heartbeats(deadline_ms);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_minimum_sizes (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
microshares INTEGER NOT NULL CHECK(microshares BETWEEN 1 AND 1000000000000000)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS market_tick_sizes (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id),
|
||||
step_micros INTEGER NOT NULL CHECK(step_micros IN (100000,10000,5000,2500,1000,100))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS tick_changes (
|
||||
seq INTEGER PRIMARY KEY, market TEXT NOT NULL REFERENCES market_tick_sizes(market),
|
||||
at_ms INTEGER NOT NULL CHECK(at_ms>=0), old_micros INTEGER, new_micros INTEGER NOT NULL,
|
||||
request_id TEXT NOT NULL REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
UNIQUE(market,at_ms)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS tick_changes_by_seq ON tick_changes(market,seq);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS position_remainders (
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 999999),
|
||||
PRIMARY KEY(account,market,outcome),
|
||||
FOREIGN KEY(account,market,outcome) REFERENCES positions(account,market,outcome)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS collateral_remainders (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS settlement_dust (
|
||||
market TEXT PRIMARY KEY REFERENCES markets(id), micros INTEGER NOT NULL CHECK(micros>0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS precise_movements (
|
||||
request_id TEXT NOT NULL, account TEXT NOT NULL, shares_micros INTEGER NOT NULL, cash_micros INTEGER NOT NULL,
|
||||
PRIMARY KEY(request_id,account),
|
||||
FOREIGN KEY(request_id,account) REFERENCES wallet_movements(request_id,account) DEFERRABLE INITIALLY DEFERRED
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS position_units AS
|
||||
SELECT p.account,p.market,p.outcome,p.available*1000000+COALESCE(r.micros,0) AS available,
|
||||
p.reserved*10000 AS reserved,p.phase,p.payout_per_share
|
||||
FROM position_sizes p LEFT JOIN position_remainders r USING(account,market,outcome);
|
||||
CREATE VIEW IF NOT EXISTS market_backing AS
|
||||
SELECT m.id AS market,m.collateral*10000+COALESCE(r.micros,0) AS micros
|
||||
FROM markets m LEFT JOIN collateral_remainders r ON r.market=m.id;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS budget_spend_micros (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES budget_buys(order_seq),
|
||||
micros INTEGER NOT NULL CHECK(micros>=0)
|
||||
);
|
||||
|
||||
-- Keep issued public trade cursors valid after a restart, scoped to this database.
|
||||
CREATE TABLE IF NOT EXISTS trade_cursor_key (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1), secret BLOB NOT NULL CHECK(length(secret)=32)
|
||||
);
|
||||
INSERT INTO trade_cursor_key(singleton,secret)
|
||||
SELECT 1,randomblob(32) WHERE NOT EXISTS(SELECT 1 FROM trade_cursor_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_market_aliases (
|
||||
condition_id TEXT PRIMARY KEY,
|
||||
market TEXT NOT NULL UNIQUE REFERENCES markets(id),
|
||||
zero_outcome TEXT NOT NULL CHECK(zero_outcome IN ('YES','NO'))
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_aliases (
|
||||
token_id TEXT PRIMARY KEY,
|
||||
condition_id TEXT NOT NULL REFERENCES polymarket_market_aliases(condition_id),
|
||||
module TEXT NOT NULL, structure TEXT, group_id TEXT, question INTEGER,
|
||||
slot INTEGER NOT NULL CHECK(slot IN (0,1)),
|
||||
observation TEXT NOT NULL CHECK(json_valid(observation)),
|
||||
UNIQUE(condition_id,module,slot)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_structures ON polymarket_token_aliases(structure);
|
||||
CREATE INDEX IF NOT EXISTS pm_alias_groups ON polymarket_token_aliases(group_id,question);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_structure_slots
|
||||
ON polymarket_token_aliases(structure,slot) WHERE structure IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS pm_alias_question_slots
|
||||
ON polymarket_token_aliases(group_id,question,module,slot) WHERE group_id IS NOT NULL;
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS polymarket_token_observation_times (
|
||||
token_id TEXT PRIMARY KEY REFERENCES polymarket_token_aliases(token_id),
|
||||
observed_at_ms INTEGER NOT NULL CHECK(observed_at_ms>0)
|
||||
);
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
use crate::{
|
||||
assets,
|
||||
book::{self, CancelReason},
|
||||
tick_size::TickSize,
|
||||
validation::phase,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Change {
|
||||
market: String,
|
||||
outcome: String,
|
||||
old_tick_size: Option<String>,
|
||||
new_tick_size: String,
|
||||
timestamp: String,
|
||||
}
|
||||
|
||||
impl Change {
|
||||
pub fn apply(self, tx: &Transaction, request_id: &str) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
ensure!(
|
||||
self.timestamp.bytes().all(|b| b.is_ascii_digit()),
|
||||
"invalid tick timestamp"
|
||||
);
|
||||
let at_ms = self
|
||||
.timestamp
|
||||
.parse::<i64>()
|
||||
.context("invalid tick timestamp")?;
|
||||
let new = TickSize::parse(&self.new_tick_size)?.0;
|
||||
let reported_old = self
|
||||
.old_tick_size
|
||||
.as_deref()
|
||||
.map(TickSize::parse)
|
||||
.transpose()?
|
||||
.map(|t| t.0);
|
||||
// Both outcome subscriptions can deliver the same market transition.
|
||||
let prior: Option<(Option<i64>,i64,String)> = tx.query_row(
|
||||
"SELECT old_micros,new_micros,response FROM tick_changes c JOIN requests r ON r.id=c.request_id
|
||||
WHERE c.market=? AND c.at_ms=?",params![self.market,at_ms],
|
||||
|r| Ok((r.get(0)?,r.get(1)?,r.get(2)?))).optional()?;
|
||||
if let Some((old, step, receipt)) = prior {
|
||||
ensure!(
|
||||
step == new && (reported_old.is_none() || reported_old == old),
|
||||
"conflicting tick event at the same timestamp"
|
||||
);
|
||||
return Ok(serde_json::from_str(&receipt)?);
|
||||
}
|
||||
phase(tx, &self.market, &["preopen", "continuous"])?;
|
||||
let latest: Option<i64> = tx.query_row(
|
||||
"SELECT MAX(at_ms) FROM tick_changes WHERE market=?",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(latest.map_or(true, |t| at_ms > t), "stale tick event");
|
||||
let current = TickSize::load(tx, &self.market)?.map(|t| t.0);
|
||||
if let (Some(expected), Some(actual)) = (reported_old, current) {
|
||||
ensure!(
|
||||
actual == expected,
|
||||
"old_tick_size differs from current market"
|
||||
);
|
||||
}
|
||||
let old = current.or(reported_old);
|
||||
ensure!(old != Some(new), "unchanged tick size");
|
||||
|
||||
let mut stmt = tx.prepare(
|
||||
"SELECT seq,account FROM orders WHERE market=?1 AND status='live'
|
||||
AND (price*100 NOT BETWEEN ?2 AND 1000000-?2 OR (price*100)%?2<>0) ORDER BY seq",
|
||||
)?;
|
||||
let invalid = stmt
|
||||
.query_map(params![self.market, new], |r| {
|
||||
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let mut canceled = Vec::with_capacity(invalid.len());
|
||||
for (seq, owner) in invalid {
|
||||
book::release(tx, seq, &owner, CancelReason::Cancelled)?;
|
||||
canceled.push(seq);
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO market_tick_sizes(market,step_micros) VALUES(?,?)
|
||||
ON CONFLICT(market) DO UPDATE SET step_micros=excluded.step_micros",
|
||||
params![self.market, new],
|
||||
)?;
|
||||
let seq: i64 = tx.query_row(
|
||||
"INSERT INTO tick_changes(market,at_ms,old_micros,new_micros,request_id)
|
||||
VALUES(?,?,?,?,?) RETURNING seq",
|
||||
params![self.market, at_ms, old, new, request_id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
Ok(
|
||||
json!({"market":self.market,"tick_seq":seq,"old_tick_size":old.map(|v|TickSize(v).text()),
|
||||
"new_tick_size":TickSize(new).text(),"timestamp":at_ms.to_string(),"canceled":canceled}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn latest_seq(db: &Connection, market: &str) -> Result<i64> {
|
||||
Ok(db.query_row(
|
||||
"SELECT COALESCE(MAX(seq),0) FROM tick_changes WHERE market=?",
|
||||
[market],
|
||||
|r| r.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct History {
|
||||
market: String,
|
||||
outcome: String,
|
||||
#[serde(default)]
|
||||
after: i64,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
impl History {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
ensure!(
|
||||
self.after >= 0 && (1..=1000).contains(&limit),
|
||||
"invalid tick history page"
|
||||
);
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown market");
|
||||
let asset = assets::id(&self.market, &self.outcome);
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT seq,at_ms,old_micros,new_micros FROM tick_changes
|
||||
WHERE market=? AND seq>? ORDER BY seq LIMIT ?",
|
||||
)?;
|
||||
let mut rows = stmt.query(params![self.market, self.after, limit + 1])?;
|
||||
let mut cursor = self.after;
|
||||
let mut events = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
if events.len() == limit as usize {
|
||||
return Ok(json!({"events":events,"cursor":cursor,"has_more":true}));
|
||||
}
|
||||
cursor = row.get(0)?;
|
||||
events.push(json!({"seq":cursor,"event_type":"tick_size_change","asset_id":asset,"market":self.market,
|
||||
"timestamp":row.get::<_,i64>(1)?.to_string(),
|
||||
"old_tick_size":row.get::<_,Option<i64>>(2)?.map(|v|TickSize(v).text()),
|
||||
"new_tick_size":TickSize(row.get(3)?).text()}));
|
||||
}
|
||||
Ok(json!({"events":events,"cursor":cursor,"has_more":false}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
use crate::{assets, inventory, minimum_size::MinimumSize, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
pub(crate) struct TickSize(pub i64);
|
||||
|
||||
// A stored price is in 0.0001 dollars. One price unit times one order lot
|
||||
// (0.01 shares) is exactly one cash micro.
|
||||
pub(crate) const PAR: i64 = 10_000;
|
||||
pub(crate) const PRICE_MICROS: i64 = 100;
|
||||
pub(crate) fn input(cents: Option<i64>, micros: Option<i64>) -> Result<Option<i64>> {
|
||||
match (cents, micros) {
|
||||
(None, None) => Ok(None),
|
||||
(Some(c), None) if (0..=100).contains(&c) => Ok(Some(c * 100)),
|
||||
(None, Some(m)) if (0..=1_000_000).contains(&m) && m % PRICE_MICROS == 0 => {
|
||||
Ok(Some(m / PRICE_MICROS))
|
||||
}
|
||||
_ => anyhow::bail!("provide one valid price in cents or micros"),
|
||||
}
|
||||
}
|
||||
pub(crate) fn required(cents: Option<i64>, micros: Option<i64>) -> Result<i64> {
|
||||
input(cents, micros)?.ok_or_else(|| anyhow::anyhow!("price required"))
|
||||
}
|
||||
pub(crate) fn validate(tick: Option<&TickSize>, price: i64) -> Result<()> {
|
||||
if let Some(tick) = tick {
|
||||
tick.check(price * PRICE_MICROS)
|
||||
} else {
|
||||
ensure!(
|
||||
(0..=PAR).contains(&price) && price % 100 == 0,
|
||||
"legacy market requires a whole-cent price"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Exchange {
|
||||
/// Current grid for a listed local outcome, including the whole-cent legacy grid.
|
||||
pub fn minimum_tick_size(
|
||||
&self,
|
||||
token: &str,
|
||||
) -> Result<Option<serde_json::Number>, MarketDataError> {
|
||||
let (_, market) = assets::parse_id(token)
|
||||
.map_err(|_| MarketDataError::Invalid("Invalid token id".into()))?;
|
||||
let mut stmt = self.db.prepare_cached(
|
||||
"SELECT s.step_micros FROM markets m LEFT JOIN market_tick_sizes s ON s.market=m.id WHERE m.id=?1"
|
||||
)?;
|
||||
let tick = stmt
|
||||
.query_row([market], |r| r.get::<_, Option<i64>>(0))
|
||||
.optional()?;
|
||||
Ok(tick.map(|step| step.map(TickSize).unwrap_or(TickSize::WHOLE_CENT).number()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TickSize {
|
||||
pub(crate) const WHOLE_CENT: Self = Self(10_000);
|
||||
|
||||
pub(crate) fn number(&self) -> serde_json::Number {
|
||||
inventory::decimal(self.0.into(), inventory::UNIT)
|
||||
}
|
||||
|
||||
pub(crate) fn parse(value: &str) -> Result<Self> {
|
||||
let micros = match value.trim_end_matches('0') {
|
||||
"0.1" => 100_000,
|
||||
"0.01" => 10_000,
|
||||
"0.005" => 5_000,
|
||||
"0.0025" => 2_500,
|
||||
"0.001" => 1_000,
|
||||
"0.0001" => 100,
|
||||
_ => anyhow::bail!("unsupported tick_size"),
|
||||
};
|
||||
Ok(Self(micros))
|
||||
}
|
||||
|
||||
pub fn configure(tx: &Transaction, market: &str, value: &str) -> Result<()> {
|
||||
let micros = Self::parse(value)?.0;
|
||||
tx.execute(
|
||||
"INSERT INTO market_tick_sizes(market,step_micros) VALUES(?,?)",
|
||||
params![market, micros],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load(db: &Connection, market: &str) -> Result<Option<Self>> {
|
||||
Ok(db
|
||||
.prepare_cached("SELECT step_micros FROM market_tick_sizes WHERE market=?")?
|
||||
.query_row([market], |r| Ok(Self(r.get(0)?)))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn text(&self) -> String {
|
||||
self.number().to_string()
|
||||
}
|
||||
|
||||
pub fn check(&self, price: i64) -> Result<()> {
|
||||
ensure!(
|
||||
(self.0..=1_000_000 - self.0).contains(&price) && price % self.0 == 0,
|
||||
"price outside trading range or off tick_size {}",
|
||||
self.text()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn local_step(&self) -> NonZeroU32 {
|
||||
NonZeroU32::new((self.0 / PRICE_MICROS) as u32).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Side {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct LimitAmounts {
|
||||
market: String,
|
||||
outcome: String,
|
||||
side: Side,
|
||||
price_micros: i64,
|
||||
size_micros: i64,
|
||||
}
|
||||
|
||||
impl LimitAmounts {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
ensure!(
|
||||
matches!(self.outcome.as_str(), "YES" | "NO"),
|
||||
"invalid outcome"
|
||||
);
|
||||
let tick = TickSize::load(db, &self.market)?
|
||||
.ok_or_else(|| anyhow::anyhow!("listed market with configured tick_size required"))?;
|
||||
tick.check(self.price_micros)?;
|
||||
let shares = crate::lots::amount(None, Some(self.size_micros))? * crate::lots::MICROS;
|
||||
if let Some(minimum) = MinimumSize::load(db, &self.market)? {
|
||||
minimum.check_microshares(shares)?;
|
||||
}
|
||||
// Every supported step times 0.01 shares is an integer number of micros.
|
||||
let collateral = i128::from(self.price_micros) * i128::from(shares) / 1_000_000;
|
||||
let (maker, taker) = match self.side {
|
||||
Side::Buy => (collateral, i128::from(shares)),
|
||||
Side::Sell => (i128::from(shares), collateral),
|
||||
};
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&self.market,&self.outcome),"tick_size":tick.text(),
|
||||
"price_micros":self.price_micros,"size_micros":shares,"collateral_micros":collateral,
|
||||
"makerAmount":maker.to_string(),"takerAmount":taker.to_string(),
|
||||
"local_precision_supported":true}),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
use crate::{
|
||||
assets,
|
||||
token_directory::{condition_hex, decimal_token},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct Bind {
|
||||
market: String,
|
||||
external_condition: String,
|
||||
zero_outcome: String,
|
||||
observed_at_ms: Option<i64>,
|
||||
data: Vec<Value>,
|
||||
}
|
||||
|
||||
struct Row<'a> {
|
||||
token: &'a str,
|
||||
opposite: &'a str,
|
||||
module: &'a str,
|
||||
structure: Option<&'a str>,
|
||||
group: Option<&'a str>,
|
||||
slot: usize,
|
||||
question: Option<i64>,
|
||||
}
|
||||
|
||||
fn full_condition(id: &str) -> bool {
|
||||
id.len() == 66 && condition_hex(id).as_deref() == Some(id)
|
||||
}
|
||||
|
||||
fn position_id(raw: &str) -> [u8; 32] {
|
||||
// The decimal string has already been checked against uint256::MAX.
|
||||
let mut bytes = [0u8; 32];
|
||||
for digit in raw.bytes() {
|
||||
let mut carry = u16::from(digit - b'0');
|
||||
for byte in bytes.iter_mut().rev() {
|
||||
let next = u16::from(*byte) * 10 + carry;
|
||||
*byte = next as u8;
|
||||
carry = next >> 8;
|
||||
}
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
impl<'a> Row<'a> {
|
||||
fn read(row: &'a Value, condition: &str) -> Result<Self> {
|
||||
let token = row["token_id"].as_str().context("token_id is required")?;
|
||||
let opposite = row["opposite_token_id"]
|
||||
.as_str()
|
||||
.context("opposite_token_id is required")?;
|
||||
ensure!(
|
||||
decimal_token(token) == Some(token)
|
||||
&& decimal_token(opposite) == Some(opposite)
|
||||
&& token != opposite,
|
||||
"invalid external outcome identifiers"
|
||||
);
|
||||
ensure!(
|
||||
row["condition_id"] == condition,
|
||||
"external condition mismatch"
|
||||
);
|
||||
let module = row["module"].as_str().context("module is required")?;
|
||||
let slot = row["outcome_index"]
|
||||
.as_u64()
|
||||
.filter(|i| *i < 2)
|
||||
.context("invalid outcome index")? as usize;
|
||||
let structure = row["structural_condition_id"].as_str();
|
||||
let group = row["neg_risk_market_id"].as_str();
|
||||
let question = row["question_index"].as_i64();
|
||||
ensure!(
|
||||
group.is_some() == question.is_some()
|
||||
&& group.is_none_or(full_condition)
|
||||
&& question.is_none_or(|q| q >= 0),
|
||||
"invalid negative-risk question reference"
|
||||
);
|
||||
match module {
|
||||
"v1_ctf" => ensure!(
|
||||
row["structural_condition_id"].is_null(),
|
||||
"CTF has no structure ID"
|
||||
),
|
||||
"binary" | "neg_risk" => {
|
||||
ensure!(
|
||||
(module == "neg_risk") == group.is_some(),
|
||||
"V2 module mismatch"
|
||||
);
|
||||
let bytes = position_id(token);
|
||||
let other = position_id(opposite);
|
||||
let mut expected = String::from("0x");
|
||||
use std::fmt::Write;
|
||||
for byte in &bytes[..31] {
|
||||
write!(expected, "{byte:02x}")?;
|
||||
}
|
||||
expected.push_str("00");
|
||||
ensure!(
|
||||
structure == Some(expected.as_str())
|
||||
&& usize::from(bytes[31]) == slot
|
||||
&& bytes[..31] == other[..31]
|
||||
&& usize::from(other[31]) == 1 - slot,
|
||||
"V2 token does not encode the supplied condition and outcome"
|
||||
);
|
||||
}
|
||||
_ => anyhow::bail!("unsupported external token module"),
|
||||
}
|
||||
Ok(Self {
|
||||
token,
|
||||
opposite,
|
||||
module,
|
||||
structure,
|
||||
group,
|
||||
slot,
|
||||
question,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Bind {
|
||||
pub(crate) fn register(self, tx: &Transaction<'_>) -> Result<Value> {
|
||||
identifier(&self.market)?;
|
||||
ensure!(
|
||||
self.observed_at_ms.is_none_or(|ms| ms > 0),
|
||||
"invalid observation time"
|
||||
);
|
||||
ensure!(
|
||||
matches!(self.zero_outcome.as_str(), "YES" | "NO"),
|
||||
"zero_outcome must be YES or NO"
|
||||
);
|
||||
ensure!(
|
||||
full_condition(&self.external_condition),
|
||||
"expected a canonical external market condition"
|
||||
);
|
||||
ensure!(
|
||||
(2..=4).contains(&self.data.len()),
|
||||
"provide a complete outcome pair for each protocol"
|
||||
);
|
||||
let mut families = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let token = Row::read(value, &self.external_condition)?;
|
||||
let slot = token.slot;
|
||||
let pair = families.entry(token.module).or_insert_with(|| [None, None]);
|
||||
ensure!(
|
||||
pair[slot].replace(token).is_none(),
|
||||
"repeated protocol outcome"
|
||||
);
|
||||
}
|
||||
if self.observed_at_ms.is_some() {
|
||||
let mut states = BTreeMap::new();
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
let state = SnapshotState::read(value)?;
|
||||
let pair = states.entry(row.module).or_insert_with(|| [None, None]);
|
||||
pair[row.slot] = Some(state);
|
||||
}
|
||||
for pair in states.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.closed == b.closed && a.resolved == b.resolved,
|
||||
"protocol pair has inconsistent lifecycle"
|
||||
);
|
||||
if let (Some(a), Some(b)) = (a.price, b.price) {
|
||||
ensure!((a + b - 1.0).abs() <= 1e-9, "final payouts must sum to one");
|
||||
}
|
||||
}
|
||||
}
|
||||
let v2_count = families.keys().filter(|m| **m != "v1_ctf").count();
|
||||
ensure!(v2_count <= 1, "multiple V2 protocols for the same market");
|
||||
let mut group_ref = None;
|
||||
for pair in families.values() {
|
||||
let [Some(a), Some(b)] = pair else {
|
||||
anyhow::bail!("incomplete protocol pair");
|
||||
};
|
||||
ensure!(
|
||||
a.opposite == b.token
|
||||
&& b.opposite == a.token
|
||||
&& a.structure == b.structure
|
||||
&& a.group == b.group
|
||||
&& a.question == b.question,
|
||||
"outcomes do not form one pair"
|
||||
);
|
||||
if let Some((group, question)) = group_ref {
|
||||
ensure!(
|
||||
(a.group, a.question) == (group, question),
|
||||
"protocols identify different questions"
|
||||
);
|
||||
}
|
||||
group_ref = Some((a.group, a.question));
|
||||
}
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[&self.market],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "unknown local market");
|
||||
tx.execute("INSERT INTO polymarket_market_aliases VALUES(?1,?2,?3) ON CONFLICT(condition_id) DO NOTHING",
|
||||
params![self.external_condition,self.market,self.zero_outcome])?;
|
||||
let bound: (String, String) = tx.query_row(
|
||||
"SELECT market,zero_outcome FROM polymarket_market_aliases WHERE condition_id=?1",
|
||||
[&self.external_condition],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
bound == (self.market.clone(), self.zero_outcome.clone()),
|
||||
"market condition already bound with different identity"
|
||||
);
|
||||
let current_group: Option<(Option<String>, Option<i64>)> = tx.query_row(
|
||||
"SELECT group_id,question FROM polymarket_token_aliases WHERE condition_id=?1 LIMIT 1",
|
||||
[&self.external_condition], |row| Ok((row.get(0)?,row.get(1)?)),
|
||||
).optional()?;
|
||||
if let (Some((stored_group, stored_question)), Some((group, question))) =
|
||||
(current_group, group_ref)
|
||||
{
|
||||
ensure!(
|
||||
(stored_group.as_deref(), stored_question) == (group, question),
|
||||
"market already bound to a different question"
|
||||
);
|
||||
}
|
||||
for value in &self.data {
|
||||
let row = Row::read(value, &self.external_condition)?;
|
||||
// Only retain fields exposed by the external directory.
|
||||
let observation: serde_json::Map<_, _> = [
|
||||
"token_id",
|
||||
"condition_id",
|
||||
"structural_condition_id",
|
||||
"module",
|
||||
"outcome_index",
|
||||
"clob_index",
|
||||
"outcome",
|
||||
"opposite_token_id",
|
||||
"resolved",
|
||||
"final_price",
|
||||
"title",
|
||||
"market_slug",
|
||||
"closed",
|
||||
"neg_risk",
|
||||
"neg_risk_market_id",
|
||||
"question_index",
|
||||
"event_id",
|
||||
"event_slug",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|key| (key.to_owned(), value[key].clone()))
|
||||
.collect();
|
||||
let observation = Value::Object(observation);
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_aliases VALUES(?1,?2,?3,?4,?5,?6,?7,?8)
|
||||
ON CONFLICT(token_id) DO NOTHING",
|
||||
params![
|
||||
row.token,
|
||||
self.external_condition,
|
||||
row.module,
|
||||
row.structure,
|
||||
row.group,
|
||||
row.question,
|
||||
row.slot as i64,
|
||||
observation.to_string()
|
||||
],
|
||||
)?;
|
||||
let observed: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT observation FROM polymarket_token_aliases WHERE token_id=?1",
|
||||
[row.token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let prior: Value = serde_json::from_str(&observed.context("missing stored token")?)?;
|
||||
let prior_identity = Row::read(&prior, &self.external_condition)?;
|
||||
ensure!(
|
||||
prior_identity.module == row.module
|
||||
&& prior_identity.structure == row.structure
|
||||
&& prior_identity.slot == row.slot
|
||||
&& prior_identity.group == row.group
|
||||
&& prior_identity.question == row.question
|
||||
&& prior_identity.opposite == row.opposite,
|
||||
"token already bound with different identity"
|
||||
);
|
||||
if let Some(observed_at_ms) = self.observed_at_ms {
|
||||
refresh(tx, row.token, prior, &observation, observed_at_ms)?;
|
||||
}
|
||||
}
|
||||
Ok(
|
||||
json!({"market":self.market,"external_condition":self.external_condition,
|
||||
"zero_asset_id":assets::id(&self.market,&self.zero_outcome),"tokens":self.data.len()}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct SnapshotState {
|
||||
closed: bool,
|
||||
resolved: bool,
|
||||
price: Option<f64>,
|
||||
}
|
||||
|
||||
impl SnapshotState {
|
||||
fn read(data: &Value) -> Result<Self> {
|
||||
let closed = data["closed"]
|
||||
.as_bool()
|
||||
.context("closed must be a boolean")?;
|
||||
let resolved = data["resolved"]
|
||||
.as_bool()
|
||||
.context("resolved must be a boolean")?;
|
||||
let price = data["final_price"].as_f64();
|
||||
if resolved {
|
||||
ensure!(
|
||||
closed && price.is_some_and(|p| (0.0..=1.0).contains(&p)),
|
||||
"invalid final payout"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
data["final_price"].is_null(),
|
||||
"unresolved asset has a final payout"
|
||||
);
|
||||
}
|
||||
Ok(Self {
|
||||
closed,
|
||||
resolved,
|
||||
price,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const LIVE_FIELDS: &[&str] = &["closed", "resolved", "final_price", "outcome"];
|
||||
|
||||
fn refresh(
|
||||
tx: &Transaction<'_>,
|
||||
token: &str,
|
||||
mut prior: Value,
|
||||
incoming: &Value,
|
||||
observed_at_ms: i64,
|
||||
) -> Result<()> {
|
||||
let last: Option<i64> = tx
|
||||
.query_row(
|
||||
"SELECT observed_at_ms FROM polymarket_token_observation_times WHERE token_id=?1",
|
||||
[token],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(last) = last {
|
||||
if observed_at_ms < last {
|
||||
return Ok(());
|
||||
}
|
||||
if observed_at_ms == last {
|
||||
ensure!(
|
||||
LIVE_FIELDS.iter().all(|&key| prior[key] == incoming[key]),
|
||||
"conflicting observations at the same time"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if prior["resolved"] == true {
|
||||
ensure!(
|
||||
incoming["resolved"] == true
|
||||
&& prior["final_price"].as_f64() == incoming["final_price"].as_f64(),
|
||||
"observation contradicts a recorded final payout"
|
||||
);
|
||||
}
|
||||
for &key in LIVE_FIELDS {
|
||||
prior[key] = incoming[key].clone();
|
||||
}
|
||||
tx.execute(
|
||||
"UPDATE polymarket_token_aliases SET observation=?1 WHERE token_id=?2",
|
||||
params![prior.to_string(), token],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO polymarket_token_observation_times VALUES(?1,?2)
|
||||
ON CONFLICT(token_id) DO UPDATE SET observed_at_ms=excluded.observed_at_ms",
|
||||
params![token, observed_at_ms],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS id,
|
||||
json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
)
|
||||
SELECT s.ordinal,t.observation,m.market,
|
||||
CASE WHEN t.slot=0 THEN m.zero_outcome
|
||||
WHEN m.zero_outcome='YES' THEN 'NO' ELSE 'YES' END AS outcome,o.observed_at_ms
|
||||
FROM selectors s
|
||||
JOIN polymarket_token_aliases t ON
|
||||
(s.kind='external_token' AND t.token_id=s.id)
|
||||
OR (s.kind='condition' AND
|
||||
(t.condition_id=s.id OR t.group_id=s.id OR t.structure=s.id OR t.structure=s.id||'00'))
|
||||
JOIN polymarket_market_aliases m ON m.condition_id=t.condition_id
|
||||
LEFT JOIN polymarket_token_observation_times o ON o.token_id=t.token_id
|
||||
ORDER BY s.ordinal,t.question,t.condition_id,(t.module<>'v1_ctf'),t.slot
|
||||
@@ -0,0 +1,141 @@
|
||||
use crate::{assets, inventory::decimal, Exchange, MarketDataError};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_TOKEN: &str =
|
||||
"115792089237316195423570985008687907853269984665640564039457584007913129639935";
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TokenDirectoryQuery {
|
||||
#[serde(alias = "token_ids")]
|
||||
token_id: Option<String>,
|
||||
#[serde(alias = "condition_id", alias = "conditionId")]
|
||||
condition: Option<String>,
|
||||
}
|
||||
|
||||
fn invalid(message: impl Into<String>) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.into())
|
||||
}
|
||||
|
||||
pub(crate) fn condition_hex(value: &str) -> Option<String> {
|
||||
let hex = value
|
||||
.strip_prefix("0x")
|
||||
.or_else(|| value.strip_prefix("0X"))?;
|
||||
if !matches!(hex.len(), 62 | 64) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("0x{}", hex.to_ascii_lowercase()))
|
||||
}
|
||||
|
||||
pub(crate) fn decimal_token(value: &str) -> Option<&str> {
|
||||
let digits = value.trim_start_matches('0');
|
||||
if value.is_empty()
|
||||
|| !value.bytes().all(|b| b.is_ascii_digit())
|
||||
|| digits.len() > MAX_TOKEN.len()
|
||||
|| (digits.len() == MAX_TOKEN.len() && digits > MAX_TOKEN)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(if digits.is_empty() { "0" } else { digits })
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_tokens(&self, query: TokenDirectoryQuery) -> Result<Value, MarketDataError> {
|
||||
let token = query.token_id.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let condition = query.condition.as_deref().filter(|s| !s.trim().is_empty());
|
||||
let (raw, is_token, limit, selector) = match (token, condition) {
|
||||
(Some(raw), None) => (raw, true, 50, "token_id"),
|
||||
(None, Some(raw)) => (raw, false, 10, "condition"),
|
||||
_ => return Err(invalid("provide exactly one of 'token_id' or 'condition'")),
|
||||
};
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let mut seen = HashSet::new();
|
||||
let mut keys = Vec::new();
|
||||
for value in raw.split(',').map(str::trim) {
|
||||
let (key, outcome, kind) = if is_token {
|
||||
if let Ok((outcome, market)) = assets::parse_id(value) {
|
||||
(market.to_owned(), Some(outcome), "local_token")
|
||||
} else {
|
||||
let token = decimal_token(value)
|
||||
.ok_or_else(|| invalid(format!("invalid token id: {value}")))?;
|
||||
(token.to_owned(), None, "external_token")
|
||||
}
|
||||
} else if let Some(hex) = condition_hex(value) {
|
||||
(hex, None, "condition")
|
||||
} else {
|
||||
let listed: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)
|
||||
OR EXISTS(SELECT 1 FROM neg_risk_groups WHERE id=?1)",
|
||||
[value],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if !listed {
|
||||
return Err(invalid(format!("invalid condition id: {value}")));
|
||||
}
|
||||
(value.to_owned(), None, "condition")
|
||||
};
|
||||
if seen.insert((key.clone(), outcome)) {
|
||||
if seen.len() > limit {
|
||||
return Err(invalid(format!(
|
||||
"'{selector}' accepts at most {limit} distinct values"
|
||||
)));
|
||||
}
|
||||
keys.push((key, outcome, kind));
|
||||
}
|
||||
}
|
||||
let input = serde_json::to_string(&keys).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut data = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_directory.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
let market: String = r.get(0)?;
|
||||
let phase: String = r.get(5)?;
|
||||
let winner: Option<String> = r.get(6)?;
|
||||
let index: i64 = r.get(7)?;
|
||||
let (outcome, other) = if index == 0 { ("YES", "NO") } else { ("NO", "YES") };
|
||||
let group: Option<String> = r.get(8)?;
|
||||
let price = winner.as_deref().filter(|_| phase=="resolved").map(|winner| {
|
||||
if winner == "VOID" { decimal(5,10) } else { decimal(i128::from(winner == outcome),1) }
|
||||
});
|
||||
Ok((r.get::<_, i64>(12)?, json!({
|
||||
"token_id":assets::id(&market,outcome),"condition_id":market,
|
||||
"structural_condition_id":null,"module":if group.is_some() { "local_neg_risk" } else { "local_binary" },
|
||||
"outcome_index":index,"clob_index":null,"outcome":r.get::<_,String>(if index==0 {3} else {4})?,
|
||||
"opposite_token_id":assets::id(&market,other),
|
||||
"resolved":phase=="resolved","closed":matches!(phase.as_str(),"closed"|"resolved"),
|
||||
"final_price":price,"title":r.get::<_,String>(1)?,"market_slug":r.get::<_,String>(2)?,
|
||||
"neg_risk":group.is_some(),"neg_risk_market_id":group,"question_index":r.get::<_,Option<i64>>(9)?,
|
||||
"event_id":r.get::<_,Option<i64>>(10)?,"event_slug":r.get::<_,Option<String>>(11)?
|
||||
})))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let externals = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("token_aliases.sql"))?;
|
||||
let rows = stmt.query_map([&input], |r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, String>(3)?,
|
||||
r.get::<_, Option<i64>>(4)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
let external_ordinals: HashSet<_> = externals.iter().map(|r| r.0).collect();
|
||||
data.retain(|(ordinal, _)| !external_ordinals.contains(ordinal));
|
||||
for (ordinal, raw, market, outcome, observed_at_ms) in externals {
|
||||
let mut row: Value =
|
||||
serde_json::from_str(&raw).map_err(|_| MarketDataError::Unavailable)?;
|
||||
row["local_condition_id"] = json!(market);
|
||||
row["local_asset_id"] = json!(assets::id(&market, &outcome));
|
||||
row["observed_at_ms"] = json!(observed_at_ms);
|
||||
data.push((ordinal, row));
|
||||
}
|
||||
data.sort_by_key(|row| row.0);
|
||||
let data: Vec<_> = data.into_iter().map(|(_, row)| row).collect();
|
||||
tx.commit()?;
|
||||
Ok(json!({"data":data}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
WITH selectors AS (
|
||||
SELECT key AS ordinal, json_extract(value,'$[0]') AS market,
|
||||
json_extract(value,'$[1]') AS outcome, json_extract(value,'$[2]') AS kind
|
||||
FROM json_each(?1)
|
||||
), markets_selected AS (
|
||||
SELECT s.ordinal,m.id AS market,s.outcome
|
||||
FROM selectors s JOIN markets m ON m.id=s.market
|
||||
WHERE s.kind<>'external_token'
|
||||
UNION ALL
|
||||
SELECT s.ordinal,n.market,NULL
|
||||
FROM selectors s JOIN neg_risk_members n ON n.group_id=s.market
|
||||
WHERE s.kind='condition' AND s.outcome IS NULL AND NOT EXISTS (SELECT 1 FROM markets m WHERE m.id=s.market)
|
||||
), slots(outcome, outcome_index) AS (VALUES ('YES',0),('NO',1))
|
||||
SELECT m.id,w.question,w.slug,w.yes_label,w.no_label,m.phase,m.winner,s.outcome_index,
|
||||
n.group_id,n.ordinal,e.event_id,e.slug,x.ordinal
|
||||
FROM markets_selected x JOIN markets m ON m.id=x.market
|
||||
JOIN market_wire_metadata w ON w.market=x.market
|
||||
JOIN slots s ON x.outcome IS NULL OR s.outcome=x.outcome
|
||||
LEFT JOIN neg_risk_members n ON n.market=x.market
|
||||
LEFT JOIN listed_markets l ON l.market=x.market
|
||||
LEFT JOIN numbered_events e ON e.id=l.event
|
||||
ORDER BY x.ordinal,n.ordinal,m.id,s.outcome_index
|
||||
@@ -1,5 +1,7 @@
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::Transaction;
|
||||
use crate::MarketDataError;
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{Connection, Transaction};
|
||||
use serde_json::json;
|
||||
pub(crate) fn identifier(id: &str) -> Result<()> {
|
||||
ensure!(
|
||||
!id.trim().is_empty() && id.trim().chars().count() <= 256,
|
||||
@@ -7,6 +9,10 @@ pub(crate) fn identifier(id: &str) -> Result<()> {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn hex_id(id: &str, digits: usize) -> bool {
|
||||
id.len() == 2 + digits && id.starts_with("0x") && id[2..].bytes().all(|b| b.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
pub(crate) fn amount(n: i64) -> Result<()> {
|
||||
ensure!((1..=1_000_000_000).contains(&n), "invalid amount");
|
||||
Ok(())
|
||||
@@ -20,3 +26,91 @@ pub(crate) fn phase(tx: &Transaction, market: &str, allowed: &[&str]) -> Result<
|
||||
ensure!(allowed.contains(&p.as_str()), "wrong market phase");
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize, PartialEq)]
|
||||
#[serde(untagged)]
|
||||
pub(crate) enum IdSelector {
|
||||
One(String),
|
||||
Many(Vec<String>),
|
||||
}
|
||||
|
||||
impl IdSelector {
|
||||
pub(crate) fn ids(&self) -> Result<Vec<String>> {
|
||||
let mut ids = match self {
|
||||
Self::One(id) => vec![id.clone()],
|
||||
Self::Many(ids) => ids.clone(),
|
||||
};
|
||||
ids.sort();
|
||||
ids.dedup();
|
||||
ensure!(
|
||||
(1..=20).contains(&ids.len()),
|
||||
"expected 1 to 20 distinct IDs"
|
||||
);
|
||||
for id in &ids {
|
||||
identifier(id)?;
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn directory_selector(
|
||||
db: &Connection,
|
||||
raw: Option<&str>,
|
||||
numeric: bool,
|
||||
) -> Result<Option<IdSelector>> {
|
||||
raw.map(|raw| {
|
||||
let mut keys = Vec::new();
|
||||
for id in raw.split(',').map(str::trim) {
|
||||
identifier(id)?;
|
||||
if numeric {
|
||||
let n = id.parse::<i64>().context("invalid event_id")?;
|
||||
ensure!(n > 0, "invalid event_id");
|
||||
keys.push(n.to_string());
|
||||
} else {
|
||||
if id.starts_with("0x") && !hex_id(id, 64) {
|
||||
// Locally listed condition IDs may legitimately use a short 0x prefix.
|
||||
let listed: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?1)",
|
||||
[id],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(listed, "invalid condition: {id}");
|
||||
}
|
||||
keys.push(id.to_owned());
|
||||
}
|
||||
}
|
||||
Ok(IdSelector::Many(keys))
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) fn condition_filter(
|
||||
raw: Option<&str>,
|
||||
db: &Connection,
|
||||
) -> Result<Option<String>, MarketDataError> {
|
||||
let Some(raw) = raw else {
|
||||
return Ok(None);
|
||||
};
|
||||
let selector = IdSelector::Many(
|
||||
raw.split(',')
|
||||
.map(str::trim)
|
||||
.map(|id| {
|
||||
if hex_id(id, 64) {
|
||||
id.to_ascii_lowercase()
|
||||
} else {
|
||||
id.to_owned()
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let ids = selector
|
||||
.ids()
|
||||
.map_err(|e| MarketDataError::Invalid(e.to_string()))?;
|
||||
let mut exists = db.prepare_cached("SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)")?;
|
||||
for id in &ids {
|
||||
if !hex_id(id, 64) && !exists.query_row([id], |r| r.get::<_, bool>(0))? {
|
||||
return Err(MarketDataError::Invalid(format!("invalid condition: {id}")));
|
||||
}
|
||||
}
|
||||
Ok(Some(json!(ids).to_string()))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS last_asset_trades (
|
||||
market TEXT NOT NULL REFERENCES markets, outcome TEXT NOT NULL,
|
||||
execution INTEGER NOT NULL, price INTEGER NOT NULL, PRIMARY KEY(market,outcome)
|
||||
);
|
||||
|
||||
-- One row per priced asset, including legacy fills with no timestamp.
|
||||
-- Execution numbers are unique across the two journals.
|
||||
WITH legs(market,outcome,execution,price) AS (
|
||||
SELECT o.market,o.outcome,f.seq,f.price FROM fills f JOIN orders o ON o.seq=f.bid
|
||||
UNION ALL SELECT market,'YES',seq,yes_price FROM paired_fills
|
||||
UNION ALL SELECT market,'NO',seq,100-yes_price FROM paired_fills
|
||||
)
|
||||
INSERT INTO last_asset_trades(market,outcome,execution,price)
|
||||
SELECT market,outcome,MAX(execution),price FROM legs GROUP BY market,outcome
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS last_asset_direct AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO last_asset_trades
|
||||
SELECT market,outcome,NEW.seq,NEW.price FROM orders WHERE seq=NEW.bid
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
END;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS reserved_position_orders ON orders(account,market,outcome)
|
||||
WHERE status='live' AND side='sell';
|
||||
CREATE VIEW IF NOT EXISTS position_sizes AS
|
||||
SELECT p.account,p.market,p.outcome,p.quantity AS available,
|
||||
COALESCE((SELECT SUM(o.remaining) FROM orders o WHERE o.account=p.account AND o.market=p.market
|
||||
AND o.outcome=p.outcome AND o.status='live' AND o.side='sell'),0) AS reserved,
|
||||
m.phase,CASE WHEN m.phase='resolved' THEN
|
||||
CASE WHEN m.winner='VOID' THEN 50 WHEN p.outcome=m.winner THEN 100 ELSE 0 END
|
||||
END AS payout_per_share
|
||||
FROM positions p JOIN markets m ON m.id=p.market;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,116 @@
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Transaction};
|
||||
use serde::Serialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn serialize_hundredths<S: serde::Serializer>(
|
||||
value: &i64,
|
||||
serializer: S,
|
||||
) -> std::result::Result<S::Ok, S::Error> {
|
||||
crate::lots::display(*value).serialize(serializer)
|
||||
}
|
||||
|
||||
fn serialize_cash_cents<S: serde::Serializer>(
|
||||
value: &i64,
|
||||
serializer: S,
|
||||
) -> std::result::Result<S::Ok, S::Error> {
|
||||
crate::inventory::decimal((*value).into(), 10000).serialize(serializer)
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
struct Totals {
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
matched_shares: i64,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
taker_shares: i64,
|
||||
#[serde(serialize_with = "serialize_cash_cents")]
|
||||
taker_notional_cents: i64,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
unknown_role_shares: i64,
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
fn add(&mut self, other: &Self) -> Result<()> {
|
||||
for (total, value) in [
|
||||
(&mut self.matched_shares, other.matched_shares),
|
||||
(&mut self.taker_shares, other.taker_shares),
|
||||
(&mut self.taker_notional_cents, other.taker_notional_cents),
|
||||
(&mut self.unknown_role_shares, other.unknown_role_shares),
|
||||
] {
|
||||
*total = total.checked_add(value).context("volume overflow")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Serialize)]
|
||||
pub(crate) struct Volume {
|
||||
all_time: Totals,
|
||||
last_24h: Totals,
|
||||
#[serde(serialize_with = "serialize_hundredths")]
|
||||
unknown_time_shares: i64,
|
||||
}
|
||||
|
||||
pub(crate) struct Report {
|
||||
pub as_of_ms: i64,
|
||||
pub total: Volume,
|
||||
pub markets: BTreeMap<String, Volume>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub fn read(db: &Transaction, event: Option<&str>, market: Option<&str>) -> Result<Self> {
|
||||
ensure!(
|
||||
event.is_some() != market.is_some(),
|
||||
"specify event or market"
|
||||
);
|
||||
let as_of_ms = db.query_row(
|
||||
"SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let mut report = Self {
|
||||
as_of_ms,
|
||||
total: Volume::default(),
|
||||
markets: BTreeMap::new(),
|
||||
};
|
||||
let mut stmt = db.prepare_cached(include_str!("volume.sql"))?;
|
||||
let mut rows = stmt.query(params![event, market, as_of_ms])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let volume = report.markets.entry(row.get(0)?).or_default();
|
||||
let recent: Option<bool> = row.get(1)?;
|
||||
let totals = Totals {
|
||||
matched_shares: row.get(2)?,
|
||||
taker_shares: row.get(3)?,
|
||||
taker_notional_cents: row.get(4)?,
|
||||
unknown_role_shares: row.get(5)?,
|
||||
};
|
||||
for v in [volume, &mut report.total] {
|
||||
v.all_time.add(&totals)?;
|
||||
if recent == Some(true) {
|
||||
v.last_24h.add(&totals)?;
|
||||
} else if recent.is_none() {
|
||||
v.unknown_time_shares = v
|
||||
.unknown_time_shares
|
||||
.checked_add(totals.matched_shares)
|
||||
.context("volume overflow")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
market.is_none() || !report.markets.is_empty(),
|
||||
"unknown market"
|
||||
);
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
pub fn response(&self) -> Value {
|
||||
let mut conditions: Vec<_> = self.markets.iter().collect();
|
||||
conditions.sort_by_key(|(id, v)| (std::cmp::Reverse(v.all_time.taker_shares), *id));
|
||||
let conditions: Vec<_> = conditions
|
||||
.into_iter()
|
||||
.map(|(market, volume)| json!({"market":market,"volume":volume}))
|
||||
.collect();
|
||||
json!({"as_of_ms":self.as_of_ms,"volume":self.total,"conditions":conditions})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
-- ?1 selects an event's visible conditions; ?2 selects a single market.
|
||||
WITH selected(market) AS MATERIALIZED (
|
||||
SELECT s.market FROM listed_markets s
|
||||
LEFT JOIN augmented_outcomes a ON a.market=s.market
|
||||
WHERE s.event=?1 AND (a.role IS NULL OR a.role<>'placeholder')
|
||||
UNION ALL SELECT id FROM markets WHERE id=?2
|
||||
), executions AS (
|
||||
SELECT s.market, f.seq, f.quantity, p.at_ms, f.price AS taker_price
|
||||
FROM selected s CROSS JOIN orders o ON o.market=s.market AND o.side='buy'
|
||||
CROSS JOIN fills f ON f.bid=o.seq LEFT JOIN trade_prices p ON p.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT s.market, f.seq, f.quantity, f.at_ms,
|
||||
CASE c.taker_order WHEN f.yes_order THEN f.yes_price
|
||||
WHEN f.no_order THEN 10000-f.yes_price END
|
||||
FROM selected s CROSS JOIN paired_fills f ON f.market=s.market
|
||||
LEFT JOIN execution_context c ON c.execution=f.seq
|
||||
)
|
||||
SELECT s.market, e.at_ms BETWEEN ?3-86400000 AND ?3 AS recent,
|
||||
COALESCE(SUM(e.quantity),0),
|
||||
COALESCE(SUM(e.quantity) FILTER (WHERE c.taker_order IS NOT NULL),0),
|
||||
COALESCE(SUM(e.quantity*e.taker_price) FILTER (WHERE c.taker_order IS NOT NULL),0),
|
||||
COALESCE(SUM(e.quantity) FILTER (WHERE c.execution IS NULL),0)
|
||||
FROM selected s LEFT JOIN executions e ON e.market=s.market
|
||||
LEFT JOIN execution_context c ON c.execution=e.seq
|
||||
GROUP BY s.market,recent
|
||||
+2944
-8
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
# matching
|
||||
|
||||
每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。价格单位为分,数量单位为份。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。
|
||||
每个 OrderBook 保存一个交易品的常驻盘口。买卖双方各有一棵按价格、原始受理序号排序的 BTreeMap。每本簿的价格均用同一个最小价格步长的整数倍表示,数量用整数表示最小交易单位。exchange 的价格使用 0.0001 美元,每个数量单位为 0.01 份。exchange 按市场和结果持有这些簿,并把已提交的订单余量逐笔应用到对应的树。
|
||||
|
||||
## 文件依赖
|
||||
|
||||
@@ -23,11 +23,17 @@ sequenceDiagram
|
||||
alt 连续交易
|
||||
B->>M: match_incoming,传入一条新订单
|
||||
M->>M: 从对手方最优价起遍历,同价按原序号分配
|
||||
else 未指定市价委托保护价
|
||||
B->>M: opposing_levels,传入买卖方向
|
||||
M->>M: 从最优对手价起,逐档汇总同价订单的剩余份额
|
||||
M-->>B: 逐档返回价格和总量,调用方按需停止读取
|
||||
else 盘中按金额买入
|
||||
B->>M: match_budget_buy,传入买单序号、最高价、预算分数
|
||||
M->>M: 在同一卖盘上逐单扣减可用预算,末档取可负担的整份
|
||||
B->>M: match_budget_buy,传入买单序号、最高价、以微美元计的总预算
|
||||
M->>M: 在同一卖盘上逐单扣减可用预算,末档取预算可负担的最大整数单位数
|
||||
else 集合竞价
|
||||
B->>M: opening,在本簿现有两侧计算统一成交价
|
||||
B->>M: opening,在买一与卖一之间计算统一成交价
|
||||
M->>M: 从卖一起,只访问新的卖价或买价之后的第一个价格步长
|
||||
M->>M: 最大成交量优先,再取供需差最小者,并列时选最低价
|
||||
end
|
||||
M-->>B: 返回成交计划,保留已提交盘口
|
||||
alt SQLite 提交成功
|
||||
@@ -37,9 +43,15 @@ sequenceDiagram
|
||||
end
|
||||
```
|
||||
|
||||
## 细步长样例
|
||||
|
||||
Gamma 市场 559651 的一份公开目录记录中,最小步长为 0.001 美元,买一为 0.012,卖一为 0.013。以这个步长建立内存簿,两个价位分别用整数 12、13 表示。假设盘中在 12 上有两张各 2 份的卖单,在 13 上有一张 2 份卖单,以 13 为限价买入 5 份,会按受理顺序以 12、12、13 成交,合计 61 个步长,即 0.061 美元。这个成交场景使用模拟订单。exchange 以 0.0001 美元为内部单位表示价格,实际送入簿内的这两个价位为 120、130,按市场配置的步长 10 进行竞价。[官方目录](https://gamma-api.polymarket.com/markets/559651)
|
||||
|
||||
开盘沿用 Eventbook 的集合竞价规则。若价位 812 有 2 份卖单,812 和 817 分别有 3 份和 2 份买单,在 812 可成交 2 份,需求多出 3 份;在 813 至 817 均可成交 2 份,供需相等。最终以最低的 813 清算。813 上可以没有挂单。遍历工作量取决于订单和有供需变化的价位数,即使最小步长细化,空价位也无需逐档扫描。若调用方价格单位为分、市场仅允许每 10 分一档,使用 opening_with_step(10),输入委托须已对齐。同样的供需变化在买价 50 分之后要到 60 分才生效。
|
||||
|
||||
## 吞吐基准
|
||||
|
||||
在获准的测量机器上执行 `cargo run --release --locked -p matching --example throughput`。用同一工具链、硬件和负载对比基线 ca45f83 与本分支,在基线工作区放入同一个 examples/throughput.rs。程序预热后分别报告七轮的中位和最佳 ops/s,包括无交叉、单笔、扫 32 单、写入并撮合移除一张单,以及 8192 单集合竞价。前三项使用固定盘口,写入场景在每次迭代中实际维护盘口;开盘场景的单位是整次竞价。均为单线程内存测量,SQLite、网关和网络延迟在范围之外。此次未执行 release 测量。
|
||||
在获准的测量机器上执行 `cargo run --release --locked -p matching --example throughput`。用同一工具链、硬件和负载对比基线 ca45f83 与本分支,在基线工作区放入同一个 examples/throughput.rs。程序预热后分别报告七轮的中位和最佳 ops/s,包括无交叉、单笔、扫 32 单、写入并撮合移除一张单,以及 8192 单集合竞价。前三项使用固定盘口,写入场景在每次迭代中实际维护盘口;开盘场景的单位是整次竞价。均为单线程内存测量,SQLite、网关和网络延迟在范围之外。另设同样 8192 单的稀疏网格场景。该场景在十个价位上分配订单,价位间距为 1000 步;先核对得到 2049 笔成交才计时,旧基线若不支持该范围则显示跳过。此次未执行 release 测量。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
|
||||
@@ -62,4 +62,17 @@ fn main() {
|
||||
measure("opening/8192-orders", 100, || {
|
||||
black_box(&book).opening().len()
|
||||
});
|
||||
// Same order IDs, quantities, and distinct levels over a wider price grid.
|
||||
let mut sparse = OrderBook::default();
|
||||
for seq in 1..=8192 {
|
||||
let side = if seq <= 4096 { Side::Sell } else { Side::Buy };
|
||||
sparse.update(order(seq, side, 500_000 + 1_000 * (seq % 10), 1));
|
||||
}
|
||||
if sparse.opening().len() == 2049 {
|
||||
measure("opening/8192-orders/sparse-ticks", 100, || {
|
||||
black_box(&sparse).opening().len()
|
||||
});
|
||||
} else {
|
||||
eprintln!("opening/8192-orders/sparse-ticks skipped: expected 2049 fills");
|
||||
}
|
||||
}
|
||||
|
||||
+158
-13
@@ -2,6 +2,7 @@ mod order;
|
||||
pub use order::{Fill, Order, Side};
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::BTreeMap;
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
@@ -41,7 +42,26 @@ impl OrderBook {
|
||||
}
|
||||
}
|
||||
|
||||
/// Buy whole shares at maker prices, walking the same FIFO ask tree as a limit buy.
|
||||
/// Visible opposing price levels, best first. Sum orders at one level
|
||||
/// before exposing it so a client sees the same depth regardless of FIFO splits.
|
||||
pub fn opposing_levels(&self, side: Side) -> impl Iterator<Item = (i64, i128)> + '_ {
|
||||
let orders: Box<dyn Iterator<Item = &Order> + '_> = match side {
|
||||
Side::Buy => Box::new(self.asks.values()),
|
||||
Side::Sell => Box::new(self.bids.values()),
|
||||
};
|
||||
let mut orders = orders.peekable();
|
||||
std::iter::from_fn(move || {
|
||||
let first = orders.next()?;
|
||||
let mut size = i128::from(first.remaining);
|
||||
while let Some(order) = orders.next_if(|o| o.price == first.price) {
|
||||
size += i128::from(order.remaining);
|
||||
}
|
||||
Some((first.price, size))
|
||||
})
|
||||
}
|
||||
|
||||
/// Buy integer lots at maker prices. Express the budget in price ticks
|
||||
/// multiplied by quantity lots, the same units as price * remaining.
|
||||
pub fn match_budget_buy(&self, seq: i64, limit: i64, budget: i64) -> Vec<Fill> {
|
||||
let mut cash = budget;
|
||||
let mut capacity = i64::MAX;
|
||||
@@ -72,28 +92,53 @@ impl OrderBook {
|
||||
}
|
||||
|
||||
pub fn opening(&self) -> Vec<Fill> {
|
||||
self.opening_with_step(NonZeroU32::MIN)
|
||||
}
|
||||
|
||||
/// Orders have already been validated as multiples of this price step.
|
||||
pub fn opening_with_step(&self, step: NonZeroU32) -> Vec<Fill> {
|
||||
let (Some(bid), Some(ask)) = (self.bids.values().next(), self.asks.values().next()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if bid.price < ask.price {
|
||||
return Vec::new();
|
||||
}
|
||||
// Move each price boundary once as the candidate tick rises.
|
||||
// Every crossed book with positive live quantities executes at least one
|
||||
// share between its best ask and best bid. Outside, volume is zero.
|
||||
let mut tick = ask.price;
|
||||
let mut price = tick;
|
||||
let mut best_score = None;
|
||||
let mut demand: i128 = self.bids.values().map(|o| i128::from(o.remaining)).sum();
|
||||
let mut supply = 0i128;
|
||||
let mut bids = self.bids.values().rev().peekable();
|
||||
let mut asks = self.asks.values().peekable();
|
||||
let price = (0..=100)
|
||||
.min_by_key(|&tick| {
|
||||
while bids.peek().is_some_and(|o| o.price < tick) {
|
||||
demand -= i128::from(bids.next().unwrap().remaining);
|
||||
}
|
||||
while asks.peek().is_some_and(|o| o.price <= tick) {
|
||||
supply += i128::from(asks.next().unwrap().remaining);
|
||||
}
|
||||
(Reverse(demand.min(supply)), (demand - supply).abs(), tick)
|
||||
})
|
||||
.expect("nonempty tick range");
|
||||
loop {
|
||||
while bids.peek().is_some_and(|o| o.price < tick) {
|
||||
demand -= i128::from(bids.next().unwrap().remaining);
|
||||
}
|
||||
while asks.peek().is_some_and(|o| o.price <= tick) {
|
||||
supply += i128::from(asks.next().unwrap().remaining);
|
||||
}
|
||||
let score = (Reverse(demand.min(supply)), (demand - supply).abs());
|
||||
if best_score.map_or(true, |best| score < best) {
|
||||
price = tick;
|
||||
best_score = Some(score);
|
||||
}
|
||||
|
||||
// Supply changes at an ask. Demand changes one tick AFTER a bid.
|
||||
// Equal scores keep the first (lowest) tick in the interval.
|
||||
let next_ask = asks.peek().map(|o| o.price);
|
||||
let after_bid = bids
|
||||
.peek()
|
||||
.and_then(|o| o.price.checked_add(i64::from(step.get())));
|
||||
let Some(next) = next_ask.into_iter().chain(after_bid).min() else {
|
||||
break;
|
||||
};
|
||||
if next > bid.price {
|
||||
break;
|
||||
}
|
||||
tick = next;
|
||||
}
|
||||
plan(self.bids.values(), self.asks.values(), Some(price))
|
||||
}
|
||||
}
|
||||
@@ -241,4 +286,104 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fine_tick_execution_preserves_maker_price_and_fifo() {
|
||||
let mut book = OrderBook::default();
|
||||
let order = |seq, side, price, remaining| Order {
|
||||
seq,
|
||||
side,
|
||||
price,
|
||||
remaining,
|
||||
};
|
||||
// One tick is $0.001 on this book.
|
||||
for (seq, price) in [(1, 13), (2, 12), (3, 12)] {
|
||||
book.update(order(seq, Side::Sell, price, 2));
|
||||
}
|
||||
let incoming = order(4, Side::Buy, 13, 5);
|
||||
let fills = book.match_incoming(&incoming);
|
||||
let expected = vec![
|
||||
Fill {
|
||||
bid: 4,
|
||||
ask: 2,
|
||||
price: 12,
|
||||
quantity: 2,
|
||||
},
|
||||
Fill {
|
||||
bid: 4,
|
||||
ask: 3,
|
||||
price: 12,
|
||||
quantity: 2,
|
||||
},
|
||||
Fill {
|
||||
bid: 4,
|
||||
ask: 1,
|
||||
price: 13,
|
||||
quantity: 1,
|
||||
},
|
||||
];
|
||||
assert_eq!(fills, expected);
|
||||
assert_eq!(book.match_budget_buy(4, 13, 61), expected);
|
||||
assert_eq!(book.match_budget_buy(4, 13, 60), expected[..2]);
|
||||
assert!(book.match_incoming(&order(5, Side::Buy, 11, 1)).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearing_can_fall_one_tick_above_a_bid_without_an_order_at_that_price() {
|
||||
for (low, high) in [
|
||||
(12, 17),
|
||||
(812, 817),
|
||||
(120_000, 990_000),
|
||||
(i64::MAX - 5, i64::MAX),
|
||||
] {
|
||||
let mut book = OrderBook::default();
|
||||
for (seq, side, price, remaining) in [
|
||||
(1, Side::Sell, low, 2),
|
||||
(2, Side::Buy, low, 3),
|
||||
(3, Side::Buy, high, 2),
|
||||
] {
|
||||
book.update(Order {
|
||||
seq,
|
||||
side,
|
||||
price,
|
||||
remaining,
|
||||
});
|
||||
}
|
||||
assert_eq!(
|
||||
book.opening(),
|
||||
vec![Fill {
|
||||
bid: 3,
|
||||
ask: 1,
|
||||
price: low + 1,
|
||||
quantity: 2
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn opening_selects_an_admissible_tick_on_the_configured_grid() {
|
||||
let mut book = OrderBook::default();
|
||||
for (seq, side, price, remaining) in [
|
||||
(1, Side::Sell, 50, 2),
|
||||
(2, Side::Buy, 50, 3),
|
||||
(3, Side::Buy, 70, 2),
|
||||
] {
|
||||
book.update(Order {
|
||||
seq,
|
||||
side,
|
||||
price,
|
||||
remaining,
|
||||
});
|
||||
}
|
||||
assert_eq!(book.opening()[0].price, 51);
|
||||
assert_eq!(
|
||||
book.opening_with_step(NonZeroU32::new(10).unwrap()),
|
||||
vec![Fill {
|
||||
bid: 3,
|
||||
ask: 1,
|
||||
price: 60,
|
||||
quantity: 2
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ pub enum Side {
|
||||
pub struct Order {
|
||||
pub seq: i64,
|
||||
pub side: Side,
|
||||
/// Integer price ticks per share, in the same unit throughout this book.
|
||||
pub price: i64,
|
||||
/// Number of minimum quantity lots left on the book.
|
||||
pub remaining: i64,
|
||||
}
|
||||
|
||||
@@ -16,6 +18,8 @@ pub struct Order {
|
||||
pub struct Fill {
|
||||
pub bid: i64,
|
||||
pub ask: i64,
|
||||
/// Integer price ticks per share, in the same unit throughout this book.
|
||||
pub price: i64,
|
||||
/// Executed lots, using the same scale as Order::remaining.
|
||||
pub quantity: i64,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{"op": "event", "id": "event-election", "event": "election", "title": "模拟选举", "category": "politics", "slug": "sample-election"}
|
||||
{"op": "list", "id": "list-a", "market": "a", "rules": "甲获胜时为 YES。以模拟选举公告为准。", "listing": {"event": "election", "question": "最终胜者属于「甲」吗?", "yes_label": "是", "no_label": "否", "group_title": "甲", "source": "模拟结果公告", "resolver": "本地裁决员", "rules_version": 1}}
|
||||
{"op": "list", "id": "list-b", "market": "b", "rules": "以命名公告确定参选者,该参选者获胜时为 YES;未命名则为 NO。以模拟选举公告为准。", "listing": {"event": "election", "question": "待公告的参选者获胜吗?", "yes_label": "是", "no_label": "否", "group_title": "预留位", "source": "模拟结果公告", "resolver": "本地裁决员", "rules_version": 1}}
|
||||
{"op": "list", "id": "list-other", "market": "other", "rules": "获胜者在最终裁决时仍未被列名则为 YES。以模拟选举公告为准。", "listing": {"event": "election", "question": "最终胜者属于「其他」吗?", "yes_label": "是", "no_label": "否", "group_title": "其他", "source": "模拟结果公告", "resolver": "本地裁决员", "rules_version": 1}}
|
||||
{"op": "define_neg_risk", "id": "group-1", "group": "winner", "event": "election", "markets": ["a", "b", "other"], "augmented": {"other": "other", "placeholders": ["b"]}}
|
||||
{"op": "fund", "id": "fund", "account": "user", "cents": 3000}
|
||||
{"op": "split", "id": "split-a", "account": "user", "market": "a", "qty": 2}
|
||||
{"op": "convert", "id": "convert-a", "group": "winner", "account": "user", "no_markets": ["a"], "qty": 1}
|
||||
{"op": "open", "id": "open-slot", "market": "b"}
|
||||
{"op": "clarify", "id": "name-slot", "market": "b", "name": "丙", "question": "丙会赢得模拟选举吗?", "evidence": "模拟公告 7"}
|
||||
{"op": "catalog", "event": "election"}
|
||||
@@ -0,0 +1,12 @@
|
||||
{"op":"fund","id":"seller","account":"seller","cents":100}
|
||||
{"op":"fund","id":"buyer","account":"buyer","micros":512500}
|
||||
{"op":"list","id":"market","market":"m","rules":"Official result","taker_fee_rate_ppm":50000}
|
||||
{"op":"split","id":"split","market":"m","account":"seller","qty":1}
|
||||
{"op":"open","id":"open","market":"m"}
|
||||
{"op":"order","id":"rest","market":"m","outcome":"YES","account":"buyer","side":"buy","price":49,"qty":1}
|
||||
{"op":"balance","account":"buyer"}
|
||||
{"op":"cancel_all","id":"withdraw","account":"buyer"}
|
||||
{"op":"order","id":"offer","market":"m","outcome":"YES","account":"seller","side":"sell","price":50,"qty":1}
|
||||
{"op":"order","id":"trade","market":"m","outcome":"YES","account":"buyer","side":"buy","price":50,"qty":1,"tif":"FOK"}
|
||||
{"op":"balance","account":"buyer"}
|
||||
{"op":"activity","account":"buyer","include_deposits":true}
|
||||
@@ -0,0 +1,11 @@
|
||||
{"op":"list","id":"rain-list","market":"rain-final","rules":"Settle from the tournament's official final result."}
|
||||
{"op":"fund","id":"rain-cash","account":"trader","cents":200}
|
||||
{"op":"open","id":"rain-open","market":"rain-final"}
|
||||
{"op":"order","id":"rain-bid","market":"rain-final","outcome":"YES","side":"buy","account":"trader","price":40,"qty":1}
|
||||
{"op":"publish_clarification","id":"rain-context","market":"rain-final","content":"The final result includes overtime.","clear_book":false}
|
||||
{"op":"publish_clarification","id":"rain-update","market":"rain-final","content":"The tournament result sheet uses UTC.","clear_book":true}
|
||||
{"op":"resolution","market":"rain-final"}
|
||||
{"op":"balance","account":"trader"}
|
||||
{"op":"close","id":"rain-end","market":"rain-final"}
|
||||
{"op":"finalize","id":"rain-result","market":"rain-final","winner":"YES"}
|
||||
{"op":"resolution","market":"rain-final"}
|
||||
@@ -0,0 +1,11 @@
|
||||
{"op":"list","id":"list","market":"demo","rules":"Local binary outcome","tick_size":"0.01","min_order_size":"1"}
|
||||
{"op":"fund","id":"fund","account":"maker","cents":3000}
|
||||
{"op":"split","id":"split","account":"maker","market":"demo","qty":10}
|
||||
{"op":"open","id":"open","market":"demo"}
|
||||
{"op":"clob_book","token_id":"eb:YES:demo"}
|
||||
{"op":"order","id":"direct","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":30,"size_micros":2500000}
|
||||
{"op":"order","id":"reflected","account":"maker","asset_id":"eb:NO:demo","side":"sell","price":70,"qty":1}
|
||||
{"op":"order","id":"far","account":"maker","asset_id":"eb:YES:demo","side":"buy","price":20,"qty":1}
|
||||
{"op":"order","id":"near-ask","account":"maker","asset_id":"eb:YES:demo","side":"sell","price":60,"qty":1}
|
||||
{"op":"order","id":"far-ask","account":"maker","asset_id":"eb:YES:demo","side":"sell","price":80,"qty":2}
|
||||
{"op":"clob_book","token_id":"eb:YES:demo"}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user