Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 97c4a18269 | |||
| 43b843c263 |
Generated
-49
@@ -2,12 +2,6 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "ahash"
|
||||
version = "0.8.15"
|
||||
@@ -123,7 +117,6 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"exchange",
|
||||
"flate2",
|
||||
"percent-encoding",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -150,15 +143,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
@@ -247,17 +231,6 @@ version = "0.1.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3e44f110d1777dc6559a51e7d45083945ded4f1bf3305494350f693b6d20b9c8"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
"zlib-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "form_urlencoded"
|
||||
version = "1.2.3"
|
||||
@@ -674,16 +647,6 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.5"
|
||||
@@ -1095,12 +1058,6 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.12"
|
||||
@@ -1735,12 +1692,6 @@ dependencies = [
|
||||
"syn 3.0.10",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zlib-rs"
|
||||
version = "0.6.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.23"
|
||||
|
||||
@@ -12,4 +12,3 @@ tungstenite = "0.28"
|
||||
tiny_http = "0.12"
|
||||
serde_urlencoded = "0.7"
|
||||
percent-encoding = "2"
|
||||
flate2 = "1"
|
||||
|
||||
@@ -389,16 +389,6 @@ sequenceDiagram
|
||||
H-->>C: 200 data 数组,未找到返回空数组
|
||||
```
|
||||
|
||||
### 查询历史份额
|
||||
|
||||
JSONL 命令 `position_balances_at` 接受 `account` 和 UTC 毫秒 `before_ms`,返回该时点之前各结果的总份额,包含挂卖预留。数据库启用历史时登记已有余额作为起点。返回的 `history_start_ms` 界定可查范围。
|
||||
|
||||
### 日终持仓快照
|
||||
|
||||
GET /v2/positions/snapshot 使用 `user` 或 `user_address` 携带钱包地址,再传 UTC 日期 `date=YYYY-MM-DD`。请求头须包含 `Accept-Encoding: gzip`。首屏带全量汇总,续页使用同一个钱包和 `pagination.next_cursor`。本地按连接来源 IP 限制首屏在 30 秒内只能成功开始一次,续页不限。闭日按数据库历史起点及本地午夜后一小时确定。成本使用切点前的成交、拆分、合并和兑付流水重建。遇到缺少可核验成本的仓位,成本返回零。
|
||||
|
||||
日终响应的 `data` 同时包含单盘和组合,组合使用 `module=3`,标题和 slug 字段为 null。组合依次按切点前的结算、同侧实际成交价和成本估值。第一页的 `summary` 汇总两类仓位,续页继续使用原游标。
|
||||
|
||||
### 查询持仓价值
|
||||
|
||||
`GET /v2/value?user=alice&condition=e` 返回该账户在市场 e 的持仓价值,单位为模拟美元。使用已登记的本地账户名或 20 字节钱包地址。省略 condition 查询所有已持有市场。无持仓的钱包返回零,仅有现金的账户也返回零。
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
mod market_http;
|
||||
mod market_ws;
|
||||
mod snapshot_http;
|
||||
mod stream;
|
||||
mod subscriptions;
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use crate::snapshot_http;
|
||||
use anyhow::Result;
|
||||
use exchange::{Exchange, HistoryError};
|
||||
use percent_encoding::percent_decode_str;
|
||||
@@ -324,16 +323,9 @@ fn clarifications(engine: &Mutex<Exchange>, query: &str) -> Reply {
|
||||
Ok(Value::Array(rows))
|
||||
}
|
||||
|
||||
fn respond(
|
||||
mut req: Request,
|
||||
engine: &Mutex<Exchange>,
|
||||
snapshots: &snapshot_http::Starts,
|
||||
) -> std::io::Result<()> {
|
||||
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 path == "/v2/positions/snapshot" {
|
||||
return snapshot_http::respond(req, engine, snapshots);
|
||||
}
|
||||
if req.method() == &Method::Get
|
||||
&& matches!(
|
||||
path,
|
||||
@@ -590,12 +582,11 @@ fn send(req: Request, status: u16, body: Value, allow: Option<&str>) -> std::io:
|
||||
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);
|
||||
let snapshots = snapshot_http::Starts::default();
|
||||
thread::scope(|scope| {
|
||||
for _ in 0..4 {
|
||||
scope.spawn(|| {
|
||||
for req in server.incoming_requests() {
|
||||
if let Err(err) = respond(req, &engine, &snapshots) {
|
||||
if let Err(err) = respond(req, &engine) {
|
||||
eprintln!("market HTTP response: {err}");
|
||||
}
|
||||
}
|
||||
@@ -893,8 +884,6 @@ mod tests {
|
||||
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","/v2/positions/snapshot",String::new(),406,None),
|
||||
("POST","/v2/positions/snapshot",String::new(),405,None),
|
||||
("GET", "/books", String::new(), 405, None),
|
||||
("POST", "/order", "{}".into(), 404, None),
|
||||
];
|
||||
@@ -906,7 +895,7 @@ mod tests {
|
||||
.recv_timeout(Duration::from_secs(5))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
respond(req, &db, &snapshot_http::Starts::default()).unwrap();
|
||||
respond(req, &db).unwrap();
|
||||
}
|
||||
});
|
||||
for (method, path, body, status, expected) in cases {
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
use exchange::{Exchange, MarketDataError, SnapshotQuery};
|
||||
use flate2::{write::GzEncoder, Compression};
|
||||
use serde_json::{json, Value};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::{self, Write},
|
||||
net::IpAddr,
|
||||
sync::Mutex,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tiny_http::{Header, Method, Request, Response};
|
||||
|
||||
const WINDOW: Duration = Duration::from_secs(30);
|
||||
pub(crate) type Starts = Mutex<HashMap<IpAddr, Instant>>;
|
||||
|
||||
fn accepts_gzip(req: &Request) -> bool {
|
||||
req.headers()
|
||||
.iter()
|
||||
.filter(|h| h.field.equiv("Accept-Encoding"))
|
||||
.any(|h| {
|
||||
h.value.as_str().split(',').any(|coding| {
|
||||
let mut parts = coding.split(';').map(str::trim);
|
||||
parts
|
||||
.next()
|
||||
.is_some_and(|name| name.eq_ignore_ascii_case("gzip"))
|
||||
&& parts.all(|part| {
|
||||
let Some((name, value)) = part.split_once('=') else {
|
||||
return false;
|
||||
};
|
||||
name.trim().eq_ignore_ascii_case("q")
|
||||
&& value
|
||||
.trim()
|
||||
.parse::<f32>()
|
||||
.is_ok_and(|q| q > 0.0 && q <= 1.0)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn error(
|
||||
req: Request,
|
||||
status: u16,
|
||||
code: &str,
|
||||
message: &str,
|
||||
header: Option<Header>,
|
||||
) -> io::Result<()> {
|
||||
let body = json!({"code":code,"error":message,"retryable":matches!(status,429|503)});
|
||||
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())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
if let Some(header) = header {
|
||||
response.add_header(header);
|
||||
}
|
||||
req.respond(response)
|
||||
}
|
||||
|
||||
pub(crate) fn respond(req: Request, engine: &Mutex<Exchange>, starts: &Starts) -> io::Result<()> {
|
||||
if req.method() != &Method::Get {
|
||||
return error(
|
||||
req,
|
||||
405,
|
||||
"method_not_allowed",
|
||||
"Method not allowed",
|
||||
Header::from_bytes("Allow", "GET").ok(),
|
||||
);
|
||||
}
|
||||
if !accepts_gzip(&req) {
|
||||
return error(
|
||||
req,
|
||||
406,
|
||||
"not_acceptable",
|
||||
"Accept-Encoding: gzip is required",
|
||||
None,
|
||||
);
|
||||
}
|
||||
let params = req.url().split_once('?').map_or("", |(_, params)| params);
|
||||
let query: SnapshotQuery = match serde_urlencoded::from_str(params) {
|
||||
Ok(query) => query,
|
||||
Err(_) => {
|
||||
return error(
|
||||
req,
|
||||
400,
|
||||
"invalid_request",
|
||||
"invalid query parameters",
|
||||
None,
|
||||
)
|
||||
}
|
||||
};
|
||||
let ip = if query.is_first_page() {
|
||||
req.remote_addr().map(|addr| addr.ip())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut walks = starts
|
||||
.lock()
|
||||
.map_err(|_| io::Error::other("snapshot rate limit unavailable"))?;
|
||||
let now = Instant::now();
|
||||
if let Some(ip) = ip {
|
||||
walks.retain(|_, at| now.duration_since(*at) < WINDOW);
|
||||
if let Some(at) = walks.get(&ip) {
|
||||
let wait = WINDOW
|
||||
.saturating_sub(now.duration_since(*at))
|
||||
.as_millis()
|
||||
.div_ceil(1000);
|
||||
drop(walks);
|
||||
return error(
|
||||
req,
|
||||
429,
|
||||
"rate_limited",
|
||||
"snapshot first-page rate limit",
|
||||
Header::from_bytes("Retry-After", wait.to_string()).ok(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let result = engine
|
||||
.lock()
|
||||
.map_err(|_| MarketDataError::Unavailable)
|
||||
.and_then(|engine| engine.public_position_snapshot(query));
|
||||
if let (Some(ip), Ok(_)) = (ip, &result) {
|
||||
walks.insert(ip, Instant::now());
|
||||
}
|
||||
drop(walks);
|
||||
match result {
|
||||
Ok(data) => gzip(req, &data),
|
||||
Err(MarketDataError::Invalid(message)) => {
|
||||
error(req, 400, "invalid_request", &message, None)
|
||||
}
|
||||
Err(MarketDataError::Unavailable) => error(
|
||||
req,
|
||||
503,
|
||||
"unavailable",
|
||||
"snapshot unavailable",
|
||||
Header::from_bytes("Retry-After", "1").ok(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn gzip(req: Request, data: &Value) -> io::Result<()> {
|
||||
let mut gzip = GzEncoder::new(Vec::new(), Compression::default());
|
||||
gzip.write_all(data.to_string().as_bytes())?;
|
||||
let response = Response::from_data(gzip.finish()?)
|
||||
.with_header(Header::from_bytes("Content-Type", "application/json").unwrap())
|
||||
.with_header(Header::from_bytes("Content-Encoding", "gzip").unwrap())
|
||||
.with_header(Header::from_bytes("Cache-Control", "public, max-age=86400").unwrap())
|
||||
.with_header(Header::from_bytes("Vary", "Accept-Encoding").unwrap());
|
||||
req.respond(response)
|
||||
}
|
||||
+11
-51
@@ -31,15 +31,13 @@ flowchart LR
|
||||
holders -->|按毛持仓估值| portfolio
|
||||
api -->|迁移组合账本| combo_schema["src/combo_schema.sql"]
|
||||
market -->|建立组合与处理抵押| combo["src/combo.rs"]
|
||||
combo -->|读取各腿直接与推导兑付| combo_legs["src/combo_legs.sql"]
|
||||
combo_basis -->|汇总并展示相同的各腿兑付| combo_legs
|
||||
queries -->|读取定义、腿状态及余额| combo
|
||||
combo -->|复用现金微单位账本| ledger["src/ledger.rs"]
|
||||
combo --> combo_schema
|
||||
market -->|处理组合询价和最后确认| combo_rfq["src/combo_rfq.rs"]
|
||||
api -->|读取公开组合持仓和活动| combo_portfolio["src/combo_portfolio/http.rs"]
|
||||
snapshot["src/portfolio/snapshot.rs"] -->|计算组合日终余额和估值| combo_snapshot["src/combo_portfolio/snapshot.rs"]
|
||||
combo_snapshot -->|重放历史组合成本| combo_basis
|
||||
combo_snapshot --> combo_mark["src/combo_portfolio/snapshot_prices.sql"]
|
||||
combo_snapshot --> combo_legs["src/combo_portfolio/snapshot_legs.sql"]
|
||||
combo_portfolio -->|重放与核对组合份额| combo_basis["src/combo_portfolio.rs"]
|
||||
combo_basis -->|按共同写入序号取成交和钱包操作| combo_events["src/combo_portfolio_events.sql"]
|
||||
combo_basis -->|核对可用与预留份额| combo_balances["src/combo_portfolio_balances.sql"]
|
||||
@@ -241,50 +239,6 @@ sequenceDiagram
|
||||
E-->>C: 已退出的份额移入 CLOSED,可领取金额归零
|
||||
```
|
||||
|
||||
## 历史持仓余额
|
||||
|
||||
`{"op":"position_balances_at","account":"alice","before_ms":1800000000000}` 查询指定毫秒之前最后确认的各结果份额。查询上限不包含 `before_ms`。数据库首次启用历史记录时,把已有可用份额与挂卖预留一起作为余额起点,返回 `history_start_ms`。更早或未来的查询会报错。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
E["lib.rs 与 expiry.rs"] --> H["position_balance_history.rs"]
|
||||
H --> S["position_balance_history_schema.sql"]
|
||||
H --> F["position_balance_history_flush.sql"]
|
||||
F --> P["position_units"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as JSONL 客户端
|
||||
participant E as Exchange
|
||||
participant D as SQLite
|
||||
C->>E: 提交会影响余额的命令
|
||||
E->>D: 更新份额和订单,标记受影响的持仓
|
||||
E->>D: 写入变动后的总份额,并与命令同事务提交
|
||||
C->>E: position_balances_at,指定账户和 before_ms
|
||||
E->>D: 每个结果取切点之前最后一条余额
|
||||
E-->>C: 查询切点、历史覆盖起点和结果份额
|
||||
```
|
||||
|
||||
### 公开日终快照
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant H as snapshot_http.rs
|
||||
participant E as portfolio/snapshot.rs
|
||||
participant D as SQLite
|
||||
C->>H: GET /v2/positions/snapshot,wallet、date 和 gzip
|
||||
H->>E: 校验日期和钱包,按 UTC 次日零点取余额
|
||||
E->>D: 读取切点之前的裁决、行情及历史流水
|
||||
D-->>E: 份额、行情与按共同写入序号排序的成交及钱包操作
|
||||
E->>E: 重放单盘成本,与历史份额核对
|
||||
E->>D: 重放切点前的组合流水并读取腿裁决与组合成交价
|
||||
E->>E: 按结算价、成交价或成本估值组合,合并两类持仓
|
||||
E-->>H: 首屏总额、当页持仓和签名游标
|
||||
H-->>C: gzip 响应
|
||||
```
|
||||
|
||||
## GTD 到期
|
||||
|
||||
```mermaid
|
||||
@@ -477,7 +431,8 @@ sequenceDiagram
|
||||
E->>C: 铸出等量 YES 和 NO
|
||||
C->>D: 提交现金扣减、份额和流水
|
||||
O->>E: combo,查询可兑奖状态
|
||||
E->>C: 读取各腿实际裁决
|
||||
E->>C: 读取已报告裁决及互斥组赢家
|
||||
C->>D: 组内赢家确定时推导其他成员为 NO
|
||||
alt 任一腿兑付为零或全部腿已裁决
|
||||
O->>E: redeem_combo,指定一侧与数量
|
||||
C->>D: 扣减份额、释放抵押、写流水
|
||||
@@ -1410,7 +1365,7 @@ sequenceDiagram
|
||||
C->>H: GET /v2/positions/combos,传钱包和可选游标
|
||||
H->>E: 校验分页范围并读取一致快照
|
||||
E->>D: 按共同写入序号重放成交、拆分、合并和兑付
|
||||
E->>D: 核对可用及预留份额,并读取各腿裁决
|
||||
E->>D: 核对可用及预留份额,并读取各腿直接与推导裁决
|
||||
H-->>C: 成本、状态及续页游标
|
||||
C->>H: GET /v2/activity/combos
|
||||
H->>D: 按本地序号倒序读取钱包操作
|
||||
@@ -1419,13 +1374,14 @@ sequenceDiagram
|
||||
|
||||
### 账户持仓估值
|
||||
|
||||
公开估值在同一份账本快照中读取可用份额、挂卖锁定份额、盘口和裁决。若所选市场有非零持仓缺少估值依据,客户端可以重试;JSONL 的 portfolio_value 另提供已定价的小计和缺价数量。
|
||||
公开估值在同一份账本快照中读取可用份额、挂卖锁定份额、盘口和裁决。全钱包查询还计入未终结组合的剩余成本,传入 `condition` 时估值限于选中的单盘。若所选市场有非零持仓缺少估值依据,客户端可以重试。JSONL 的 `portfolio_value` 提供单盘已定价小计和缺价数量。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
L["lib.rs · Exchange"] --> H["portfolio/http.rs · 钱包、条件、四位小数"]
|
||||
H --> P["portfolio/protocol.rs · 协议合约地址"]
|
||||
H --> V["portfolio.rs · 汇总份额价值"]
|
||||
H --> B["combo_portfolio.rs · 未终结组合剩余成本"]
|
||||
V --> S["portfolio/value.sql · 按账户及市场取持仓"]
|
||||
V --> Q["quotes.rs · 盘口或成交价"]
|
||||
```
|
||||
@@ -1441,6 +1397,10 @@ sequenceDiagram
|
||||
H->>D: 读取裁决兑付率或该资产的估值依据
|
||||
end
|
||||
alt 所有选中持仓均可定价
|
||||
opt 全钱包查询
|
||||
H->>D: 重放组合账本并核对锁定及可用份额
|
||||
H->>D: 读取组合各腿裁决,汇总仍未终结的组合成本
|
||||
end
|
||||
H-->>C: 全部相加,最后舍入到四位小数
|
||||
else 仍有持仓缺价
|
||||
H-->>C: 当前无法给出完整估值
|
||||
|
||||
@@ -261,10 +261,6 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
PositionBalancesAt {
|
||||
account: String,
|
||||
before_ms: i64,
|
||||
},
|
||||
OpenInterest(crate::open_interest::Request),
|
||||
Holders(crate::holders::Request),
|
||||
Balance {
|
||||
@@ -347,9 +343,6 @@ impl Query {
|
||||
Self::Holders(request) => request.read(db),
|
||||
Self::OpenInterest(request) => request.read(db),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::PositionBalancesAt { account, before_ms } => {
|
||||
crate::position_balance_history::read(db, &account, before_ms)
|
||||
}
|
||||
Self::PublicTrades(request) => request.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
|
||||
@@ -137,15 +137,8 @@ fn product(quantity: i64, factor: u128, round_up: bool) -> i64 {
|
||||
(floor + u128::from(round_up && has_remainder)) as i64
|
||||
}
|
||||
|
||||
pub(super) const SELECT_LEGS: &str = "
|
||||
SELECT l.market,l.outcome,
|
||||
CASE m.winner WHEN 'VOID' THEN 500000 WHEN l.outcome THEN 1000000
|
||||
WHEN 'YES' THEN 0 WHEN 'NO' THEN 0 END AS payout,
|
||||
s.at_ms
|
||||
FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN price_settlements s ON s.market=m.id
|
||||
WHERE l.combo=?
|
||||
ORDER BY l.market";
|
||||
// V2 NegRisk supplies the losing siblings' effective results as soon as one member wins.
|
||||
pub(super) const SELECT_LEGS: &str = include_str!("combo_legs.sql");
|
||||
|
||||
pub(crate) fn read(db: &Connection, combo: &str, account: Option<&str>) -> Result<Value> {
|
||||
let Some((collateral, dust)) = db
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
SELECT l.market,l.outcome,
|
||||
CASE
|
||||
WHEN m.winner='VOID' THEN 500000
|
||||
WHEN m.winner=l.outcome THEN 1000000
|
||||
WHEN m.winner IN ('YES','NO') THEN 0
|
||||
WHEN g.winner<>l.market THEN CASE l.outcome WHEN 'NO' THEN 1000000 ELSE 0 END
|
||||
END AS payout,
|
||||
CASE
|
||||
WHEN g.winner<>l.market AND (m.winner IS NULL OR m.winner='NO')
|
||||
THEN COALESCE(MIN(s.at_ms,gs.at_ms),s.at_ms,gs.at_ms)
|
||||
ELSE s.at_ms
|
||||
END AS resolved_at_ms
|
||||
FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN price_settlements s ON s.market=l.market
|
||||
LEFT JOIN neg_risk_members n ON n.market=l.market
|
||||
LEFT JOIN neg_risk_groups g ON g.id=n.group_id
|
||||
LEFT JOIN price_settlements gs ON gs.market=g.winner
|
||||
WHERE l.combo=?1
|
||||
ORDER BY l.market
|
||||
@@ -1,5 +1,4 @@
|
||||
mod http;
|
||||
pub(super) mod snapshot;
|
||||
|
||||
pub use http::{ComboActivityQuery, ComboPositionsQuery};
|
||||
|
||||
@@ -127,14 +126,13 @@ fn side(index: u8) -> Side {
|
||||
}
|
||||
}
|
||||
|
||||
fn basis_entries(
|
||||
fn load_positions(
|
||||
db: &Connection,
|
||||
user: &str,
|
||||
conditions: &str,
|
||||
before: Option<i64>,
|
||||
) -> Result<BTreeMap<(String, u8), Basis>, MarketDataError> {
|
||||
) -> Result<(Vec<Position>, HashMap<String, Settlement>), MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("combo_portfolio_events.sql"))?;
|
||||
let mut rows = stmt.query(params![user, conditions, before])?;
|
||||
let mut rows = stmt.query(params![user, conditions])?;
|
||||
let mut entries = BTreeMap::<(String, u8), Basis>::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let outcome = row.get::<_, String>(1)?;
|
||||
@@ -148,15 +146,6 @@ fn basis_entries(
|
||||
i128::from(row.get::<_, i64>(5)?),
|
||||
)?;
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn load_positions(
|
||||
db: &Connection,
|
||||
user: &str,
|
||||
conditions: &str,
|
||||
) -> Result<(Vec<Position>, HashMap<String, Settlement>), MarketDataError> {
|
||||
let entries = basis_entries(db, user, conditions, None)?;
|
||||
let mut balance_stmt = db.prepare_cached(include_str!("combo_portfolio_balances.sql"))?;
|
||||
let mut balances = balance_stmt.query(params![user, conditions])?;
|
||||
let mut held = BTreeMap::new();
|
||||
@@ -206,6 +195,19 @@ fn load_positions(
|
||||
Ok((positions, states))
|
||||
}
|
||||
|
||||
/// Remaining acquisition cost of non-terminal combo holdings, in micro-dollars.
|
||||
pub(crate) fn unsettled_basis(db: &Connection, user: &str) -> Result<i128, MarketDataError> {
|
||||
let (positions, states) = load_positions(db, user, "[]")?;
|
||||
positions
|
||||
.iter()
|
||||
.filter(|p| p.basis.held > 0 && states[&p.combo].factor.is_none())
|
||||
.try_fold(0i128, |total, p| {
|
||||
total
|
||||
.checked_add(p.basis.principal)
|
||||
.ok_or(MarketDataError::Unavailable)
|
||||
})
|
||||
}
|
||||
|
||||
fn iso(db: &Connection, at: Option<i64>) -> rusqlite::Result<Option<String>> {
|
||||
db.prepare_cached("SELECT strftime('%Y-%m-%dT%H:%M:%fZ',?/1000.0,'unixepoch')")?
|
||||
.query_row([at], |r| r.get(0))
|
||||
@@ -213,12 +215,11 @@ fn iso(db: &Connection, at: Option<i64>) -> rusqlite::Result<Option<String>> {
|
||||
|
||||
fn leg_details(db: &Connection, combo: &str) -> Result<Vec<Value>, MarketDataError> {
|
||||
let sql=concat!(
|
||||
"SELECT g.*,l.outcome AS leg_outcome,s.at_ms AS leg_at,
|
||||
"SELECT g.*,l.outcome AS leg_outcome,l.payout AS leg_payout,l.resolved_at_ms AS leg_at,
|
||||
e.event_id AS leg_event_id,e.slug AS leg_event_slug,e.title AS leg_event_title,e.category AS leg_category
|
||||
FROM combo_legs l JOIN (",include_str!("gamma_market.sql"),") g ON g.market=l.market
|
||||
LEFT JOIN price_settlements s ON s.market=l.market
|
||||
FROM (",include_str!("combo_legs.sql"),") l JOIN (",include_str!("gamma_market.sql"),") g ON g.market=l.market
|
||||
LEFT JOIN numbered_events e ON e.id=g.parent
|
||||
WHERE l.combo=? ORDER BY l.market",
|
||||
ORDER BY l.market",
|
||||
);
|
||||
let mut stmt = db.prepare_cached(sql)?;
|
||||
let mut rows = stmt.query([combo])?;
|
||||
@@ -227,12 +228,11 @@ fn leg_details(db: &Connection, combo: &str) -> Result<Vec<Value>, MarketDataErr
|
||||
let condition = row.get::<_, String>("market")?;
|
||||
let outcome = row.get::<_, String>("leg_outcome")?;
|
||||
let index = usize::from(outcome == "NO");
|
||||
let winner = row.get::<_, Option<String>>("winner")?;
|
||||
let status = match winner.as_deref() {
|
||||
let status = match row.get::<_, Option<i64>>("leg_payout")? {
|
||||
None => "OPEN",
|
||||
Some("VOID") => "RESOLVED_PARTIAL",
|
||||
Some(w) if w == outcome => "RESOLVED_WIN",
|
||||
Some(_) => "RESOLVED_LOSS",
|
||||
Some(0) => "RESOLVED_LOSS",
|
||||
Some(UNIT) => "RESOLVED_WIN",
|
||||
Some(_) => "RESOLVED_PARTIAL",
|
||||
};
|
||||
let view = market(row)?;
|
||||
let labels = [
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
use super::{basis_entries, side};
|
||||
use crate::{
|
||||
combo::{position_id, Factor},
|
||||
inventory::{decimal, UNIT},
|
||||
MarketDataError,
|
||||
};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{btree_map::Entry, BTreeMap};
|
||||
|
||||
struct AtCut {
|
||||
factor: Option<Factor>,
|
||||
effective_at: Option<i64>,
|
||||
marks: [Option<i64>; 2],
|
||||
}
|
||||
|
||||
impl AtCut {
|
||||
fn read(db: &Connection, combo: &str, cut: i64) -> Result<Self, MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_legs.sql"))?;
|
||||
let mut rows = stmt.query(params![combo, cut])?;
|
||||
let mut payouts = Vec::new();
|
||||
let mut zero_at = None::<i64>;
|
||||
let mut last = None::<i64>;
|
||||
while let Some(row) = rows.next()? {
|
||||
let payout = row.get::<_, Option<i64>>(1)?;
|
||||
if let Some(at) = row.get::<_, Option<i64>>(0)? {
|
||||
last = Some(last.map_or(at, |previous| previous.max(at)));
|
||||
if payout == Some(0) {
|
||||
zero_at = Some(zero_at.map_or(at, |previous| previous.min(at)));
|
||||
}
|
||||
}
|
||||
payouts.push(payout);
|
||||
}
|
||||
if payouts.is_empty() {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
let factor = Factor::resolved(&payouts);
|
||||
let mut marks = [None, None];
|
||||
if factor.is_none() {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_prices.sql"))?;
|
||||
let mut rows = stmt.query(params![combo, cut])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
marks[usize::from(row.get::<_, String>(0)? == "NO")] = Some(row.get(1)?);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
effective_at: factor.as_ref().and(zero_at.or(last)),
|
||||
factor,
|
||||
marks,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Row {
|
||||
combo: String,
|
||||
index: u8,
|
||||
size: i128,
|
||||
avg: i128,
|
||||
price: i128,
|
||||
pub(crate) cost: i128,
|
||||
pub(crate) value: i128,
|
||||
pub(crate) bucket: usize,
|
||||
}
|
||||
|
||||
impl Row {
|
||||
pub(crate) fn wire(self) -> Value {
|
||||
let source = ["basis", "mark", "settlement"][self.bucket];
|
||||
json!({
|
||||
"asset":position_id(&self.combo,side(self.index)),"condition_id":self.combo,
|
||||
"module":3,"outcome":if self.index==0 {"Yes"} else {"No"},
|
||||
"title":null,"slug":null,"event_slug":null,
|
||||
"size":decimal(self.size,UNIT),"price":decimal(self.price,UNIT),
|
||||
"avg_price":decimal(self.avg,UNIT),"cost_basis":decimal(self.cost,UNIT),
|
||||
"value":decimal(self.value,UNIT),"price_source":source
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn rows(db: &Connection, user: &str, cut: i64) -> Result<Vec<Row>, MarketDataError> {
|
||||
let mut values = Vec::new();
|
||||
let mut quotes = BTreeMap::new();
|
||||
for ((combo, index), basis) in basis_entries(db, user, "[]", Some(cut))? {
|
||||
if basis.held <= i128::from(UNIT / 10) {
|
||||
continue;
|
||||
}
|
||||
let at = match quotes.entry(combo.clone()) {
|
||||
Entry::Occupied(v) => v.into_mut(),
|
||||
Entry::Vacant(v) => v.insert(AtCut::read(db, &combo, cut)?),
|
||||
};
|
||||
let side = side(index);
|
||||
let chosen = if let (Some(factor), Some(resolved_at)) = (&at.factor, at.effective_at) {
|
||||
if factor.status(side) == "RESOLVED_LOSS" {
|
||||
let selected = json!([combo]).to_string();
|
||||
basis_entries(db, user, &selected, Some(resolved_at))?
|
||||
.get(&(combo.clone(), index))
|
||||
.copied()
|
||||
.unwrap_or_default()
|
||||
} else {
|
||||
basis
|
||||
}
|
||||
} else {
|
||||
basis
|
||||
};
|
||||
let avg = if chosen.held == 0 {
|
||||
0
|
||||
} else {
|
||||
chosen.basis().0
|
||||
};
|
||||
let cost = chosen.principal;
|
||||
let (price, value, bucket) = if let Some(factor) = &at.factor {
|
||||
let quantity = i64::try_from(basis.held).map_err(|_| MarketDataError::Unavailable)?;
|
||||
(
|
||||
i128::from(factor.payout(side, UNIT)),
|
||||
i128::from(factor.payout(side, quantity)),
|
||||
2,
|
||||
)
|
||||
} else if let Some(mark) = at.marks[usize::from(index)] {
|
||||
let mark = i128::from(mark.clamp(0, UNIT));
|
||||
(mark, mark * basis.held / i128::from(UNIT), 1)
|
||||
} else {
|
||||
(avg, cost, 0)
|
||||
};
|
||||
values.push(Row {
|
||||
combo,
|
||||
index,
|
||||
size: basis.held,
|
||||
avg,
|
||||
price,
|
||||
cost,
|
||||
value,
|
||||
bucket,
|
||||
});
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
SELECT s.at_ms,
|
||||
CASE s.winner WHEN 'VOID' THEN 500000 WHEN l.outcome THEN 1000000
|
||||
WHEN 'YES' THEN 0 WHEN 'NO' THEN 0 END AS payout
|
||||
FROM combo_legs l
|
||||
LEFT JOIN price_settlements s ON s.market=l.market AND s.at_ms<?2
|
||||
WHERE l.combo=?1
|
||||
ORDER BY l.market
|
||||
@@ -1,17 +0,0 @@
|
||||
WITH fills AS (
|
||||
SELECT r.outcome, t.flow, q.price_micros, t.executed_at, journal.seq
|
||||
FROM combo_rfqs r JOIN combo_rfq_trades t ON t.rfq=r.id
|
||||
JOIN combo_rfq_quotes q ON q.id=t.quote
|
||||
JOIN combo_portfolio_order journal ON journal.request_id=t.request_id
|
||||
WHERE r.combo=?1 AND t.executed_at<?2
|
||||
), prices AS (
|
||||
SELECT outcome,price_micros,executed_at,seq FROM fills
|
||||
UNION ALL
|
||||
SELECT CASE outcome WHEN 'YES' THEN 'NO' ELSE 'YES' END,1000000-price_micros,executed_at,seq
|
||||
FROM fills WHERE flow IN ('MINT','MERGE')
|
||||
), ranked AS (
|
||||
SELECT outcome,price_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY outcome ORDER BY executed_at DESC,seq DESC) AS latest
|
||||
FROM prices
|
||||
)
|
||||
SELECT outcome,price_micros FROM ranked WHERE latest=1
|
||||
@@ -25,5 +25,4 @@ WITH outcomes(outcome) AS (VALUES ('YES'),('NO')), moves AS (
|
||||
SELECT m.combo,m.outcome,m.at_ms,m.op,m.shares_micros,m.cash
|
||||
FROM moves m JOIN combo_portfolio_order journal ON journal.request_id=m.request_id
|
||||
WHERE (?2='[]' OR m.combo IN (SELECT value FROM json_each(?2)))
|
||||
AND (?3 IS NULL OR m.at_ms<?3)
|
||||
ORDER BY journal.seq,m.outcome
|
||||
|
||||
@@ -52,7 +52,6 @@ pub(crate) fn transaction(
|
||||
crate::combo_rfq::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
crate::depth_feed::flush(&write)?;
|
||||
crate::position_balance_history::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ mod minimum_size;
|
||||
mod neg_risk;
|
||||
mod open_interest;
|
||||
mod portfolio;
|
||||
mod position_balance_history;
|
||||
mod prices_history;
|
||||
mod public_trades;
|
||||
mod quotes;
|
||||
@@ -59,7 +58,6 @@ pub use gamma_directory::DirectoryKey;
|
||||
pub use gamma_list::DirectoryResource;
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use portfolio::snapshot::SnapshotQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
pub use prices_history::legacy::ClobHistoryQuery;
|
||||
pub use public_trades::http::TradeQuery;
|
||||
@@ -162,14 +160,6 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
lots::migrate(&mut db)?;
|
||||
let economics_order_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='cost_order_wallet')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !economics_order_ready {
|
||||
db.execute_batch(include_str!("portfolio/economics_schema.sql"))?;
|
||||
}
|
||||
position_balance_history::install(&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 {
|
||||
@@ -277,7 +267,6 @@ impl Exchange {
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "position_balances_at"
|
||||
| "holders"
|
||||
| "balance"
|
||||
| "portfolio_value"
|
||||
@@ -382,7 +371,6 @@ impl Exchange {
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
depth_feed::flush(&tx)?;
|
||||
position_balance_history::flush(&tx)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
pub(crate) mod http;
|
||||
pub(super) mod protocol;
|
||||
pub(crate) mod snapshot;
|
||||
|
||||
use crate::{
|
||||
inventory::{decimal, UNIT},
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
-- Trade executions and wallet movements have independent ID sequences.
|
||||
-- Record their shared write order so a sale and a split in the same
|
||||
-- millisecond can be replayed in the order in which they committed.
|
||||
CREATE TABLE IF NOT EXISTS position_economics_order (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
source INTEGER NOT NULL,
|
||||
record INTEGER NOT NULL,
|
||||
UNIQUE(source,record)
|
||||
);
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_fill AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(1,NEW.seq);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS cost_order_wallet AFTER INSERT ON wallet_movements
|
||||
WHEN NEW.kind IN ('SPLIT','MERGE','REDEEM','CONVERSION') BEGIN
|
||||
INSERT INTO position_economics_order(source,record) VALUES(0,NEW.id);
|
||||
END;
|
||||
COMMIT;
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{marked_holdings, protocol::CONTRACTS};
|
||||
use crate::{
|
||||
expiry,
|
||||
inventory::decimal,
|
||||
combo_portfolio, expiry,
|
||||
inventory::{decimal, UNIT},
|
||||
validation::{condition_filter, hex_id},
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
@@ -44,9 +44,18 @@ impl Exchange {
|
||||
if missing != 0 {
|
||||
return Err(MarketDataError::Unavailable);
|
||||
}
|
||||
let total = if conditions.is_none() {
|
||||
let basis = combo_portfolio::unsettled_basis(&tx, user)?;
|
||||
basis
|
||||
.checked_mul(i128::from(UNIT))
|
||||
.and_then(|scaled| priced.checked_add(scaled))
|
||||
.ok_or(MarketDataError::Unavailable)?
|
||||
} else {
|
||||
priced
|
||||
};
|
||||
// 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 rounded = total / QUANTUM + i128::from(total % QUANTUM >= QUANTUM / 2);
|
||||
let proxy_wallet = if wallet {
|
||||
user.to_ascii_lowercase()
|
||||
} else {
|
||||
|
||||
@@ -1,293 +0,0 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::{decimal, UNIT},
|
||||
validation::hex_id,
|
||||
Exchange, MarketDataError,
|
||||
};
|
||||
use data_encoding::BASE64URL_NOPAD;
|
||||
use hmac::{Hmac, Mac};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::Sha256;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SnapshotQuery {
|
||||
#[serde(alias = "user_address")]
|
||||
user: String,
|
||||
date: Option<String>,
|
||||
limit: Option<usize>,
|
||||
cursor: Option<String>,
|
||||
}
|
||||
|
||||
impl SnapshotQuery {
|
||||
pub fn is_first_page(&self) -> bool {
|
||||
self.cursor.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Cursor {
|
||||
wallet: String,
|
||||
date: String,
|
||||
limit: usize,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
fn invalid(message: &str) -> MarketDataError {
|
||||
MarketDataError::Invalid(message.to_owned())
|
||||
}
|
||||
|
||||
impl Cursor {
|
||||
fn mac(db: &Connection) -> Result<Hmac<Sha256>, MarketDataError> {
|
||||
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).map_err(|_| MarketDataError::Unavailable)?;
|
||||
mac.update(b"eventbook:/v2/positions/snapshot:v1\0");
|
||||
Ok(mac)
|
||||
}
|
||||
|
||||
fn read(db: &Connection, text: &str) -> Result<Self, MarketDataError> {
|
||||
let bad = || invalid("invalid snapshot cursor");
|
||||
if text.len() > 2048 {
|
||||
return Err(bad());
|
||||
}
|
||||
let bytes = BASE64URL_NOPAD.decode(text.as_bytes()).map_err(|_| bad())?;
|
||||
let split = bytes.len().checked_sub(32).ok_or_else(bad)?;
|
||||
let (data, signature) = bytes.split_at(split);
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(data);
|
||||
mac.verify_slice(signature).map_err(|_| bad())?;
|
||||
serde_json::from_slice(data).map_err(|_| bad())
|
||||
}
|
||||
|
||||
fn write(&self, db: &Connection) -> Result<String, MarketDataError> {
|
||||
let mut data = serde_json::to_vec(self).map_err(|_| MarketDataError::Unavailable)?;
|
||||
let mut mac = Self::mac(db)?;
|
||||
mac.update(&data);
|
||||
data.extend_from_slice(&mac.finalize().into_bytes());
|
||||
Ok(BASE64URL_NOPAD.encode(&data))
|
||||
}
|
||||
}
|
||||
|
||||
fn cutoff(db: &Connection, date: &str) -> Result<(i64, String), MarketDataError> {
|
||||
let (start, end, point, cut): (String, String, Option<i64>, Option<String>) = db.query_row(
|
||||
"SELECT date(at_ms/1000.0,'unixepoch'),date('now','-1 hour','-1 day'),
|
||||
CASE WHEN date(?1)=?1 THEN unixepoch(?1,'+1 day')*1000 END,
|
||||
CASE WHEN date(?1)=?1 THEN strftime('%Y-%m-%dT%H:%M:%SZ',?1,'+1 day') END
|
||||
FROM position_balance_history_start WHERE singleton=1",
|
||||
[date],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
|
||||
)?;
|
||||
match (point, cut) {
|
||||
(Some(point), Some(cut)) if (start.as_str()..=end.as_str()).contains(&date) => {
|
||||
Ok((point, cut))
|
||||
}
|
||||
_ => Err(MarketDataError::Invalid(format!(
|
||||
"date must be a closed UTC day in {start}..={end}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn basis(
|
||||
db: &Connection,
|
||||
wallet: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
cut: i64,
|
||||
expected: i64,
|
||||
) -> Result<(i128, i128), MarketDataError> {
|
||||
let mut stmt = db.prepare_cached(include_str!("snapshot_basis.sql"))?;
|
||||
let mut rows = stmt.query(params![wallet, market, outcome, cut])?;
|
||||
let mut held = 0i128;
|
||||
let mut cost = 0i128;
|
||||
while let Some(row) = rows.next()? {
|
||||
if row.get::<_, bool>(3)? {
|
||||
return Ok((0, 0));
|
||||
}
|
||||
let operation: String = row.get(0)?;
|
||||
if operation == "FULL_REDEEM" {
|
||||
held = 0;
|
||||
cost = 0;
|
||||
continue;
|
||||
}
|
||||
let Some(qty) = row.get::<_, Option<i64>>(1)?.map(i128::from) else {
|
||||
return Ok((0, 0));
|
||||
};
|
||||
let cash = i128::from(row.get::<_, i64>(2)?);
|
||||
match operation.as_str() {
|
||||
"buy" if qty > 0 && cash >= 0 => {
|
||||
held += qty;
|
||||
cost += cash;
|
||||
}
|
||||
"SPLIT" if qty > 0 && cash == -qty => {
|
||||
let yes = qty / 2;
|
||||
held += qty;
|
||||
cost += if outcome == "YES" { yes } else { qty - yes };
|
||||
}
|
||||
"sell" | "MERGE" | "REDEEM" if qty > 0 && qty <= held => {
|
||||
cost -= cost.checked_mul(qty).ok_or(MarketDataError::Unavailable)? / held;
|
||||
held -= qty;
|
||||
}
|
||||
"REDEEM" if qty == 0 => {}
|
||||
_ => return Ok((0, 0)),
|
||||
}
|
||||
}
|
||||
if held == 0 || held != i128::from(expected) {
|
||||
return Ok((0, 0));
|
||||
}
|
||||
let avg = cost
|
||||
.checked_mul(i128::from(UNIT))
|
||||
.ok_or(MarketDataError::Unavailable)?
|
||||
/ held;
|
||||
Ok((cost, avg))
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn public_position_snapshot(&self, query: SnapshotQuery) -> Result<Value, MarketDataError> {
|
||||
if !hex_id(&query.user, 40)
|
||||
|| super::protocol::CONTRACTS
|
||||
.iter()
|
||||
.any(|c| c.eq_ignore_ascii_case(&query.user))
|
||||
{
|
||||
return Err(invalid("invalid user wallet"));
|
||||
}
|
||||
let wallet = query.user.to_ascii_lowercase();
|
||||
let tx = self.db.unchecked_transaction()?;
|
||||
let first = query.cursor.is_none();
|
||||
let mut cursor = if let Some(text) = query.cursor {
|
||||
let c = Cursor::read(&tx, &text)?;
|
||||
if c.wallet != wallet || query.date.as_ref().is_some_and(|date| date != &c.date) {
|
||||
return Err(invalid("snapshot cursor wallet or date does not match"));
|
||||
}
|
||||
c
|
||||
} else {
|
||||
Cursor {
|
||||
wallet,
|
||||
date: query.date.ok_or_else(|| invalid("date is required"))?,
|
||||
limit: query.limit.unwrap_or(100),
|
||||
offset: 0,
|
||||
}
|
||||
};
|
||||
if cursor.limit > 1000 {
|
||||
return Err(invalid("snapshot limit exceeds 1000"));
|
||||
}
|
||||
let (point, cut) = cutoff(&tx, &cursor.date)?;
|
||||
let mut data = Vec::new();
|
||||
let mut totals = [0i128; 3];
|
||||
let mut basis_total = 0i128;
|
||||
let mut positions = 0;
|
||||
{
|
||||
let mut stmt = tx.prepare_cached(include_str!("snapshot_positions.sql"))?;
|
||||
let mut rows = stmt.query(params![cursor.wallet, point])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let i = positions;
|
||||
positions += 1;
|
||||
let in_page = i >= cursor.offset && i - cursor.offset < cursor.limit;
|
||||
if !first && !in_page {
|
||||
continue;
|
||||
}
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let size: i64 = row.get(2)?;
|
||||
let settled: Option<i64> = row.get(7)?;
|
||||
let winner: Option<String> = row.get(8)?;
|
||||
let payout = winner.as_deref().map(|winner| {
|
||||
if winner == "VOID" {
|
||||
UNIT / 2
|
||||
} else {
|
||||
i64::from(winner == outcome) * UNIT
|
||||
}
|
||||
});
|
||||
let quote_time: Option<i64> = row.get(9)?;
|
||||
let trade_time: Option<i64> = row.get(12)?;
|
||||
let mark = if quote_time > trade_time {
|
||||
let bid: i64 = row.get(10)?;
|
||||
let ask: i64 = row.get(11)?;
|
||||
let yes = ((ask + bid) * 50).clamp(0, UNIT);
|
||||
Some(if outcome == "YES" { yes } else { UNIT - yes })
|
||||
} else {
|
||||
row.get::<_, Option<i64>>(13)?
|
||||
.map(|price| price.clamp(0, UNIT))
|
||||
};
|
||||
let frozen = settled.filter(|_| payout == Some(0));
|
||||
let basis_size = match frozen {
|
||||
Some(settlement) => tx.query_row(
|
||||
"WITH balances AS (
|
||||
SELECT shares_micros, ROW_NUMBER() OVER (
|
||||
PARTITION BY account ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history
|
||||
WHERE account COLLATE NOCASE=?1 AND market=?2 AND outcome=?3 AND at_ms<?4
|
||||
)
|
||||
SELECT COALESCE(SUM(shares_micros),0) FROM balances WHERE n=1",
|
||||
params![cursor.wallet,market,outcome,settlement],
|
||||
|row| row.get(0),
|
||||
)?,
|
||||
None => size,
|
||||
};
|
||||
let (cost, avg) = basis(
|
||||
&tx,
|
||||
&cursor.wallet,
|
||||
&market,
|
||||
&outcome,
|
||||
frozen.unwrap_or(point),
|
||||
basis_size,
|
||||
)?;
|
||||
let (price, source, bucket) = if let Some(price) = payout {
|
||||
(i128::from(price), "settlement", 2)
|
||||
} else if let Some(price) = mark {
|
||||
(i128::from(price), "mark", 1)
|
||||
} else {
|
||||
(avg, "basis", 0)
|
||||
};
|
||||
let value = if bucket == 0 {
|
||||
cost
|
||||
} else {
|
||||
price * i128::from(size) / i128::from(UNIT)
|
||||
};
|
||||
totals[bucket] += value;
|
||||
basis_total += cost;
|
||||
if in_page {
|
||||
data.push(json!({
|
||||
"asset":assets::id(&market,&outcome),
|
||||
"condition_id":market,"module":0,"outcome":row.get::<_,String>(5)?,
|
||||
"title":row.get::<_,String>(3)?,"slug":row.get::<_,String>(4)?,
|
||||
"event_slug":row.get::<_,Option<String>>(6)?,
|
||||
"size":decimal(size.into(),UNIT),"price":decimal(price,UNIT),
|
||||
"avg_price":decimal(avg,UNIT),"cost_basis":decimal(cost,UNIT),
|
||||
"value":decimal(value,UNIT),"price_source":source
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
for row in crate::combo_portfolio::snapshot::rows(&tx, &cursor.wallet, point)? {
|
||||
let i = positions;
|
||||
positions += 1;
|
||||
let in_page = i >= cursor.offset && i - cursor.offset < cursor.limit;
|
||||
if first {
|
||||
totals[row.bucket] += row.value;
|
||||
basis_total += row.cost;
|
||||
}
|
||||
if in_page {
|
||||
data.push(row.wire());
|
||||
}
|
||||
}
|
||||
let offset = cursor.offset;
|
||||
cursor.offset += data.len();
|
||||
let has_more = cursor.limit > 0 && cursor.offset < positions;
|
||||
let next = has_more.then(|| cursor.write(&tx)).transpose()?;
|
||||
let mut response = json!({"data":data,"pagination":{"limit":cursor.limit,"offset":offset,"has_more":has_more,"next_cursor":next}});
|
||||
if first {
|
||||
response["summary"] = json!({"date":cursor.date,"cut":cut,"closed_block":null,"positions":positions,
|
||||
"cost_basis":decimal(basis_total,UNIT),"value":decimal(totals.iter().sum(),UNIT),
|
||||
"value_by_source":{"basis":decimal(totals[0],UNIT),"mark":decimal(totals[1],UNIT),"settlement":decimal(totals[2],UNIT)}});
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
WITH legs AS (
|
||||
SELECT 1 AS source,t.execution AS record,t.order_seq AS leg,t.at_ms,
|
||||
t.side AS operation,t.quantity*10000 AS shares,t.quantity*t.price AS cash
|
||||
FROM wallet_trade_legs t
|
||||
WHERE t.account COLLATE NOCASE=?1 AND t.market=?2 AND t.outcome=?3
|
||||
AND (t.at_ms IS NULL OR t.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,
|
||||
CASE WHEN w.kind='REDEEM' AND json_extract(r.response,'$.amounts_micros') IS NULL
|
||||
THEN 'FULL_REDEEM' ELSE w.kind END,
|
||||
CASE WHEN w.kind='REDEEM' THEN json_extract(r.response,
|
||||
CASE ?3 WHEN 'YES' THEN '$.amounts_micros[0]' ELSE '$.amounts_micros[1]' END)
|
||||
ELSE COALESCE(p.shares_micros,w.shares*1000000) END,
|
||||
COALESCE(p.cash_micros,w.cash_delta*10000)
|
||||
FROM wallet_movements w
|
||||
LEFT JOIN precise_movements p ON p.request_id=w.request_id AND p.account=w.account
|
||||
JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.account COLLATE NOCASE=?1 AND w.market=?2 AND w.kind IN ('SPLIT','MERGE','REDEEM')
|
||||
AND (w.at_ms IS NULL OR w.at_ms<?4)
|
||||
UNION ALL
|
||||
SELECT 0,w.id,0,w.at_ms,'CONVERSION',NULL,0
|
||||
FROM wallet_movements w JOIN requests r ON r.id=w.request_id
|
||||
WHERE w.kind='CONVERSION' AND (w.at_ms IS NULL OR w.at_ms<?4) AND (
|
||||
(w.account COLLATE NOCASE=?1 AND ?2 IN (
|
||||
SELECT value FROM json_each(r.response, CASE ?3 WHEN 'YES' THEN '$.yes_markets' ELSE '$.no_markets' END)
|
||||
)) OR (?3='YES' AND json_extract(r.response,'$.conversion_fee.yes_micros_per_market')>0
|
||||
AND json_extract(r.response,'$.conversion_fee.vault') COLLATE NOCASE=?1
|
||||
AND ?2 IN (SELECT value FROM json_each(r.response,'$.yes_markets')))
|
||||
)
|
||||
), ordered AS (
|
||||
SELECT l.*,o.seq AS write_seq
|
||||
FROM legs l LEFT JOIN position_economics_order o ON o.source=l.source AND o.record=l.record
|
||||
)
|
||||
-- The pre-journal records lack a shared order within a millisecond.
|
||||
SELECT operation,shares,cash,
|
||||
at_ms IS NULL OR (write_seq IS NULL AND
|
||||
MIN(source) OVER legacy_tick<>MAX(source) OVER legacy_tick) AS ambiguous
|
||||
FROM ordered
|
||||
WINDOW legacy_tick AS (PARTITION BY write_seq IS NULL,at_ms)
|
||||
ORDER BY write_seq IS NOT NULL,CASE WHEN write_seq IS NULL THEN at_ms END,
|
||||
write_seq,source,record,leg
|
||||
@@ -1,31 +0,0 @@
|
||||
WITH holdings AS (
|
||||
SELECT account,market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY account,market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history
|
||||
WHERE account COLLATE NOCASE=?1 AND at_ms<?2
|
||||
), totals AS (
|
||||
SELECT market,outcome,SUM(shares_micros) AS size FROM holdings WHERE n=1
|
||||
GROUP BY market,outcome HAVING SUM(shares_micros)>100000
|
||||
)
|
||||
SELECT p.market,p.outcome,p.size,w.question,w.slug,
|
||||
CASE p.outcome WHEN 'YES' THEN w.yes_label ELSE w.no_label END,
|
||||
event.slug,settlement.at_ms,settlement.winner,q.at_ms,q.yes_bid,q.yes_ask,
|
||||
trade.at_ms,trade.price
|
||||
FROM totals p
|
||||
JOIN market_wire_metadata w ON w.market=p.market
|
||||
LEFT JOIN listed_markets l ON l.market=p.market
|
||||
LEFT JOIN numbered_events event ON event.id=l.event
|
||||
LEFT JOIN price_settlements settlement ON settlement.market=p.market AND settlement.at_ms<?2
|
||||
LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT seq FROM quote_events WHERE market=p.market AND at_ms<?2
|
||||
AND yes_bid IS NOT NULL AND yes_ask BETWEEN yes_bid AND yes_bid+1000
|
||||
ORDER BY at_ms DESC,seq DESC LIMIT 1
|
||||
)
|
||||
LEFT JOIN (
|
||||
SELECT market,outcome,at_ms,price_micros AS price,fill
|
||||
FROM outcome_trade_prices WHERE at_ms<?2
|
||||
) trade ON trade.market=p.market AND trade.outcome=p.outcome AND trade.fill=(
|
||||
SELECT fill FROM outcome_trade_prices WHERE market=p.market AND outcome=p.outcome AND at_ms<?2
|
||||
ORDER BY at_ms DESC,fill DESC LIMIT 1
|
||||
)
|
||||
ORDER BY p.market,p.outcome
|
||||
@@ -1,73 +0,0 @@
|
||||
use crate::{assets, inventory, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, Transaction, TransactionBehavior};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub(crate) fn install(db: &mut Connection) -> Result<()> {
|
||||
let installed = |db: &Connection| {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema
|
||||
WHERE type='table' AND name='position_balance_history_start')",
|
||||
[],
|
||||
|row| row.get::<_, bool>(0),
|
||||
)
|
||||
};
|
||||
if !installed(db)? {
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
if !installed(&tx)? {
|
||||
tx.execute_batch(include_str!("position_balance_history_schema.sql"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Record only end-of-transaction ownership changes. Sell reservations can change
|
||||
/// the ledger's available and reserved columns without changing ownership.
|
||||
pub(crate) fn flush(tx: &Transaction<'_>) -> Result<()> {
|
||||
let pending: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM position_balance_pending)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if pending {
|
||||
tx.execute_batch(include_str!("position_balance_history_flush.sql"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read(tx: &Transaction<'_>, account: &str, before_ms: i64) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
let (start, now): (i64, i64) = tx.query_row(
|
||||
"SELECT at_ms,CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
FROM position_balance_history_start WHERE singleton=1",
|
||||
[],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
before_ms > start && before_ms <= now,
|
||||
"before_ms must be after the history baseline ({start}) and no later than now ({now})"
|
||||
);
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"WITH balances AS (
|
||||
SELECT market,outcome,shares_micros,
|
||||
ROW_NUMBER() OVER (PARTITION BY market,outcome ORDER BY at_ms DESC,seq DESC) AS n
|
||||
FROM position_balance_history WHERE account=?1 AND at_ms<?2
|
||||
)
|
||||
SELECT market,outcome,shares_micros FROM balances
|
||||
WHERE n=1 AND shares_micros>0 ORDER BY market,outcome",
|
||||
)?;
|
||||
let data = stmt
|
||||
.query_map(params![account, before_ms], |row| {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let shares: i64 = row.get(2)?;
|
||||
Ok(json!({
|
||||
"asset_id":assets::id(&market,&outcome),
|
||||
"market":market,"outcome":outcome,"shares_micros":shares,
|
||||
"size":inventory::decimal(shares.into(),inventory::UNIT)
|
||||
}))
|
||||
})?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(json!({"account":account,"before_ms":before_ms,"history_start_ms":start,"data":data}))
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
WITH clock(at_ms) AS MATERIALIZED (
|
||||
SELECT MAX(CAST(unixepoch('subsec')*1000 AS INTEGER),s.at_ms,
|
||||
COALESCE((SELECT MAX(at_ms) FROM position_balance_history),s.at_ms))
|
||||
FROM position_balance_history_start s
|
||||
), affected AS (
|
||||
SELECT p.account,p.market,p.outcome,c.at_ms,
|
||||
COALESCE(v.available+v.reserved,0) AS shares_micros,
|
||||
COALESCE((SELECT h.shares_micros FROM position_balance_history h
|
||||
WHERE h.account=p.account AND h.market=p.market AND h.outcome=p.outcome
|
||||
ORDER BY h.at_ms DESC,h.seq DESC LIMIT 1),0) AS previous
|
||||
FROM position_balance_pending p
|
||||
CROSS JOIN clock c
|
||||
LEFT JOIN position_units v USING(account,market,outcome)
|
||||
)
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,at_ms,shares_micros
|
||||
FROM affected WHERE shares_micros<>previous;
|
||||
DELETE FROM position_balance_pending;
|
||||
@@ -1,62 +0,0 @@
|
||||
CREATE TABLE position_balance_history_start (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1),
|
||||
at_ms INTEGER NOT NULL
|
||||
);
|
||||
INSERT INTO position_balance_history_start VALUES(1,CAST(unixepoch('subsec')*1000 AS INTEGER));
|
||||
|
||||
CREATE TABLE position_balance_history (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
at_ms INTEGER NOT NULL, shares_micros INTEGER NOT NULL CHECK(shares_micros>=0)
|
||||
);
|
||||
CREATE INDEX position_balance_history_by_holding
|
||||
ON position_balance_history(account,market,outcome,at_ms DESC,seq DESC);
|
||||
CREATE INDEX position_balance_history_by_time ON position_balance_history(at_ms);
|
||||
INSERT INTO position_balance_history(account,market,outcome,at_ms,shares_micros)
|
||||
SELECT account,market,outcome,s.at_ms,available+reserved
|
||||
FROM position_units CROSS JOIN position_balance_history_start s
|
||||
WHERE available+reserved>0;
|
||||
|
||||
CREATE TABLE position_balance_pending (
|
||||
account TEXT NOT NULL, market TEXT NOT NULL, outcome TEXT NOT NULL,
|
||||
PRIMARY KEY(account,market,outcome)
|
||||
) WITHOUT ROWID;
|
||||
|
||||
CREATE TRIGGER position_history_quantity AFTER UPDATE OF quantity ON positions
|
||||
WHEN NEW.quantity<>OLD.quantity BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_quantity AFTER INSERT ON positions
|
||||
WHEN NEW.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_quantity AFTER DELETE ON positions
|
||||
WHEN OLD.quantity>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_new_remainder AFTER INSERT ON position_remainders
|
||||
WHEN NEW.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_remainder AFTER UPDATE OF micros ON position_remainders
|
||||
WHEN NEW.micros<>OLD.micros BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(NEW.account,NEW.market,NEW.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
CREATE TRIGGER position_history_removed_remainder AFTER DELETE ON position_remainders
|
||||
WHEN OLD.micros<>0 BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
-- A seller can lose ownership through an execution that only changes a reserved order.
|
||||
CREATE TRIGGER position_history_execution AFTER UPDATE OF remaining,status ON orders
|
||||
WHEN OLD.side='sell' AND OLD.status='live'
|
||||
AND (OLD.remaining<>NEW.remaining OR OLD.status<>NEW.status)
|
||||
BEGIN
|
||||
INSERT INTO position_balance_pending VALUES(OLD.account,OLD.market,OLD.outcome)
|
||||
ON CONFLICT(account,market,outcome) DO NOTHING;
|
||||
END;
|
||||
@@ -11,6 +11,12 @@ fn activity(db: &Exchange, query: Value) -> Value {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn value(db: &Exchange, query: Value) -> Value {
|
||||
db.public_portfolio_value(serde_json::from_value(query).unwrap())
|
||||
.unwrap()["data"]["value"]
|
||||
.clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_portfolio_replays_rfq_cost_by_side() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
@@ -34,6 +40,46 @@ fn combo_portfolio_replays_rfq_cost_by_side() {
|
||||
assert_eq!(maker["data"][0]["outcome_index"], 1);
|
||||
assert_eq!(maker["data"][0]["current_size"], json!(2.5));
|
||||
assert_eq!(maker["data"][0]["gross_entry_cost_usdc"], json!(1.625));
|
||||
|
||||
assert_eq!(value(&db, json!({"user":"taker"})), json!(0.875));
|
||||
assert_eq!(value(&db, json!({"user":"maker"})), json!(1.625));
|
||||
assert_eq!(value(&db, json!({"user":"taker","condition":"combo-a"})), 0);
|
||||
db.execute(json!({"op":"close","id":"close-first-leg","market":"combo-a"}))
|
||||
.unwrap();
|
||||
db.execute(json!({"op":"finalize","id":"lose-first-leg","market":"combo-a","winner":"NO"}))
|
||||
.unwrap();
|
||||
assert_eq!(value(&db, json!({"user":"taker"})), 0);
|
||||
assert_eq!(value(&db, json!({"user":"maker"})), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_value_rounds_single_and_combo_holdings_together() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
let cmds = include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for cmd in &cmds[..6] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"list-single","market":"single","rules":"official result"}),
|
||||
json!({"op":"split","id":"split-single","account":"alice","market":"single","qty_micros":48}),
|
||||
json!({"op":"close","id":"close-single","market":"single"}),
|
||||
json!({"op":"finalize","id":"finalize-single","market":"single","winner":"YES"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
assert_eq!(value(&db, json!({"user":"alice"})), json!(1.0001));
|
||||
assert_eq!(value(&db, json!({"user":"alice","condition":"single"})), 0);
|
||||
for cmd in &cmds[6..8] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(value(&db, json!({"user":"alice"})), json!(1.0001));
|
||||
for cmd in &cmds[8..10] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(value(&db, json!({"user":"alice"})), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -110,3 +156,52 @@ fn combo_portfolio_keeps_redemption_history_and_scope() {
|
||||
assert_eq!(second["data"][0]["payout_usdc"], json!(0.25));
|
||||
assert!(second["data"][0]["block_number"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neg_risk_winner_resolves_sibling_combo_leg_before_direct_verdict() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("derived.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = include_str!("../../../docs/examples/combo-derived-resolution.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for cmd in &cmds[..9] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(db.execute(cmds[9].clone()).unwrap()["redeemable"], false);
|
||||
assert!(db.execute(cmds[13].clone()).is_err());
|
||||
assert_eq!(value(&db, json!({"user":"alice"})).as_f64(), Some(1.0));
|
||||
for cmd in &cmds[10..12] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
drop(db);
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let derived = db.execute(cmds[12].clone()).unwrap();
|
||||
assert_eq!(derived["payout_micros_per_share"], json!([0, 1000000]));
|
||||
assert_eq!(derived["legs"][0]["payout_micros_per_share"], 0);
|
||||
assert!(derived["legs"][1]["payout_micros_per_share"].is_null());
|
||||
let before = positions(&db, json!({"user":"alice"}));
|
||||
let no = before["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|position| position["outcome_index"] == 1)
|
||||
.unwrap();
|
||||
assert_eq!(no["status"], "REDEEMABLE");
|
||||
assert_eq!(no["legs_resolved"], 1);
|
||||
assert_eq!(no["legs_pending"], 1);
|
||||
assert_eq!(no["legs"][0]["leg_status"], "RESOLVED_LOSS");
|
||||
assert!(no["legs"][0]["leg_resolved_at"].is_string());
|
||||
assert_eq!(no["legs"][1]["leg_status"], "OPEN");
|
||||
assert_eq!(value(&db, json!({"user":"alice"})), 0);
|
||||
let receipt = db.execute(cmds[13].clone()).unwrap();
|
||||
assert_eq!(receipt["paid_micros"], 1000001);
|
||||
for cmd in &cmds[14..16] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
assert_eq!(db.execute(cmds[13].clone()).unwrap(), receipt);
|
||||
let after = db.execute(cmds[16].clone()).unwrap();
|
||||
assert_eq!(after["legs"], derived["legs"]);
|
||||
assert_eq!(after["collateral_micros"], 0);
|
||||
}
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
use exchange::Exchange;
|
||||
use rusqlite::Connection;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const BUYER: &str = "0x0000000000000000000000000000000000000011";
|
||||
const MAKER: &str = "0x0000000000000000000000000000000000000022";
|
||||
const DAY: i64 = 1_699_920_000_000;
|
||||
const CUT: i64 = DAY + 86_400_000;
|
||||
|
||||
fn date(db: &Connection, at: i64) -> String {
|
||||
db.query_row("SELECT date(?/1000,'unixepoch')", [at], |r| r.get(0))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn snapshot(db: &Exchange, query: Value) -> Value {
|
||||
db.public_position_snapshot(serde_json::from_value(query).unwrap())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_snapshot_joins_binary_rows_and_prices_without_cut_lookahead() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo-snapshot.sqlite");
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
let mut combo = String::new();
|
||||
for line in include_str!("../../../docs/examples/combo-rfq.jsonl")
|
||||
.lines()
|
||||
.take(10)
|
||||
{
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
for field in ["account", "requester", "maker"] {
|
||||
match cmd[field].as_str() {
|
||||
Some("taker") => cmd[field] = json!(BUYER),
|
||||
Some("maker") => cmd[field] = json!(MAKER),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if cmd["op"] == "request_combo_quote" {
|
||||
combo = cmd["combo"].as_str().unwrap().to_owned();
|
||||
cmd["last_look_ms"] = json!(300000);
|
||||
}
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
for cmd in [
|
||||
json!({"op":"list","id":"daily-single","market":"daily-single","rules":"ordinary balance"}),
|
||||
json!({"op":"split","id":"single-split","account":BUYER,"market":"daily-single","qty":1}),
|
||||
json!({"op":"close","id":"close-leg-a","market":"combo-a"}),
|
||||
json!({"op":"finalize","id":"final-leg-a","market":"combo-a","winner":"NO"}),
|
||||
json!({"op":"redeem_combo","id":"burn-loser","combo":combo,"account":BUYER,"qty":2,"outcome":"YES"}),
|
||||
] {
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
let sql = Connection::open(&path).unwrap();
|
||||
sql.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[DAY - 1],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE position_balance_history SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute("UPDATE wallet_movements SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_rfq_trades SET executed_at=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
sql.execute(
|
||||
"UPDATE price_settlements SET at_ms=? WHERE market='combo-a'",
|
||||
[CUT],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_movements SET at_ms=?", [CUT + 1000])
|
||||
.unwrap();
|
||||
|
||||
let d = date(&sql, DAY);
|
||||
let first = snapshot(&exchange, json!({"user":BUYER,"date":d,"limit":2}));
|
||||
assert_eq!(first["summary"]["positions"], 3);
|
||||
assert_eq!(first["summary"]["cost_basis"], json!(2.4));
|
||||
assert_eq!(first["summary"]["value_by_source"]["basis"], 1);
|
||||
assert_eq!(first["summary"]["value_by_source"]["mark"], json!(1.4));
|
||||
assert_eq!(first["data"][0]["module"], 0);
|
||||
assert_eq!(first["data"][1]["module"], 0);
|
||||
let last = snapshot(
|
||||
&exchange,
|
||||
json!({"user":BUYER,"cursor":first["pagination"]["next_cursor"]}),
|
||||
);
|
||||
assert_eq!(last["data"][0]["module"], 3);
|
||||
assert_eq!(last["data"][0]["price_source"], "mark");
|
||||
assert_eq!(last["data"][0]["price"], json!(0.35));
|
||||
assert!(last["data"][0]["title"].is_null());
|
||||
assert!(!last["pagination"]["has_more"].as_bool().unwrap());
|
||||
|
||||
let maker = snapshot(&exchange, json!({"user":MAKER,"date":d}));
|
||||
assert_eq!(maker["data"][0]["outcome"], "No");
|
||||
assert_eq!(maker["data"][0]["price"], json!(0.65));
|
||||
assert_eq!(maker["data"][0]["value"], json!(2.6));
|
||||
|
||||
let following = date(&sql, CUT);
|
||||
let after = snapshot(&exchange, json!({"user":BUYER,"date":following}));
|
||||
let combo = &after["data"][2];
|
||||
assert_eq!(combo["module"], 3);
|
||||
assert_eq!(combo["size"], 2);
|
||||
assert_eq!(combo["price_source"], "settlement");
|
||||
assert_eq!(combo["value"], 0);
|
||||
assert_eq!(combo["cost_basis"], json!(1.4));
|
||||
let winning = snapshot(&exchange, json!({"user":MAKER,"date":following}));
|
||||
assert_eq!(winning["data"][0]["price"], 1);
|
||||
assert_eq!(winning["data"][0]["value"], 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_combo_uses_basis_when_no_market_price_exists() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo-basis.sqlite");
|
||||
let mut exchange = Exchange::open(&path).unwrap();
|
||||
for line in include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.take(6)
|
||||
{
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["account"] == "alice" {
|
||||
cmd["account"] = json!(BUYER);
|
||||
}
|
||||
exchange.execute(cmd).unwrap();
|
||||
}
|
||||
let sql = Connection::open(&path).unwrap();
|
||||
sql.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[DAY - 1],
|
||||
)
|
||||
.unwrap();
|
||||
sql.execute("UPDATE combo_movements SET at_ms=?", [DAY + 1000])
|
||||
.unwrap();
|
||||
let page = snapshot(&exchange, json!({"user":BUYER,"date":date(&sql,DAY)}));
|
||||
assert_eq!(page["summary"]["positions"], 2);
|
||||
assert_eq!(page["summary"]["value_by_source"]["basis"], json!(1.000002));
|
||||
assert_eq!(page["data"][0]["price_source"], "basis");
|
||||
assert_eq!(page["data"][0]["cost_basis"], json!(0.500001));
|
||||
assert_eq!(page["data"][0]["value"], json!(0.500001));
|
||||
}
|
||||
@@ -4178,182 +4178,3 @@ fn order_submission_terms_survive_fills_cancel_retries_and_legacy_upgrade() {
|
||||
assert_eq!(e.execute(cmd.clone()).unwrap()["orders"][0], expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn balance_history_uses_committed_ownership_and_an_exclusive_cut() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("historical-balances.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
setup(&mut engine);
|
||||
engine
|
||||
.execute(json!({"op":"open","id":"open-history","market":"e"}))
|
||||
.unwrap();
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute("UPDATE position_balance_history_start SET at_ms=1000", [])
|
||||
.unwrap();
|
||||
db.execute("UPDATE position_balance_history SET at_ms=2000", [])
|
||||
.unwrap();
|
||||
let count = || {
|
||||
db.query_row("SELECT COUNT(*) FROM position_balance_history", [], |r| {
|
||||
r.get::<_, i64>(0)
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let initial = count();
|
||||
assert_eq!(
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":2000}))
|
||||
.unwrap()["data"],
|
||||
json!([])
|
||||
);
|
||||
assert!(engine
|
||||
.execute(json!({"op":"position_balances_at","account":"alice","before_ms":1000}))
|
||||
.is_err());
|
||||
|
||||
let ask = order("history-ask", "alice", "sell", 50, 4);
|
||||
engine.execute(ask).unwrap();
|
||||
assert_eq!(count(), initial, "reserving shares preserves ownership");
|
||||
let buy = order("history-buy", "bob", "buy", 50, 2);
|
||||
engine.execute(buy.clone()).unwrap();
|
||||
assert_eq!(count(), initial + 2);
|
||||
engine.execute(buy).unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"idempotent replay produces no second movement"
|
||||
);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=3000 WHERE at_ms>2000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
drop(engine);
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let balance = |engine: &mut Exchange, account: &str, before_ms| {
|
||||
engine
|
||||
.execute(json!({"op":"position_balances_at","account":account,"before_ms":before_ms}))
|
||||
.unwrap()["data"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|row| row["outcome"] == "YES")
|
||||
.map(|row| row["shares_micros"].as_i64().unwrap())
|
||||
};
|
||||
assert_eq!(balance(&mut engine, "alice", 3000), Some(10_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 3001), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "bob", 3001), Some(2_000_000));
|
||||
|
||||
engine
|
||||
.execute(json!({"op":"close","id":"history-close","market":"e"}))
|
||||
.unwrap();
|
||||
engine
|
||||
.execute(json!({"op":"finalize","id":"history-final","market":"e","winner":"YES"}))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
count(),
|
||||
initial + 2,
|
||||
"closing the book releases reservations, not ownership"
|
||||
);
|
||||
engine
|
||||
.execute(json!({"op":"redeem","id":"history-redeem","account":"alice","market":"e"}))
|
||||
.unwrap();
|
||||
assert_eq!(count(), initial + 4);
|
||||
db.execute(
|
||||
"UPDATE position_balance_history SET at_ms=4000 WHERE at_ms>3000",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(balance(&mut engine, "alice", 4000), Some(8_000_000));
|
||||
assert_eq!(balance(&mut engine, "alice", 4001), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_position_snapshot_uses_the_cut_and_binds_cursor_scope() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("daily-positions.db");
|
||||
let mut engine = Exchange::open(&path).unwrap();
|
||||
let maker = "0x0000000000000000000000000000000000000011";
|
||||
let wallet = "0x0000000000000000000000000000000000000022";
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"daily-maker","account":maker,"cents":3000}),
|
||||
json!({"op":"fund","id":"daily-wallet","account":wallet,"cents":3000}),
|
||||
json!({"op":"list","id":"daily-market","market":"e","rules":"snapshot fixture"}),
|
||||
json!({"op":"list","id":"daily-basis-market","market":"f","rules":"unpriced fixture"}),
|
||||
json!({"op":"list","id":"daily-dust-market","market":"dust","rules":"dust fixture"}),
|
||||
json!({"op":"split","id":"daily-shares","account":maker,"market":"e","qty":4}),
|
||||
json!({"op":"split","id":"daily-both","account":wallet,"market":"f","qty":1}),
|
||||
json!({"op":"merge","id":"daily-merge","account":wallet,"market":"f","qty_micros":250000}),
|
||||
json!({"op":"split","id":"daily-dust","account":wallet,"market":"dust","qty_micros":100000}),
|
||||
json!({"op":"open","id":"daily-open","market":"e"}),
|
||||
order("daily-ask", maker, "sell", 40, 2),
|
||||
order("daily-buy", wallet, "buy", 40, 2),
|
||||
json!({"op":"close","id":"daily-close","market":"e"}),
|
||||
json!({"op":"finalize","id":"daily-final","market":"e","winner":"NO"}),
|
||||
] {
|
||||
engine.execute(cmd).unwrap();
|
||||
}
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
let day = 1_699_920_000_000_i64;
|
||||
let cutoff = day + 86_400_000;
|
||||
conn.execute(
|
||||
"UPDATE position_balance_history_start SET at_ms=?",
|
||||
[day - 1],
|
||||
)
|
||||
.unwrap();
|
||||
for table in [
|
||||
"position_balance_history",
|
||||
"wallet_movements",
|
||||
"quote_events",
|
||||
"trade_prices",
|
||||
] {
|
||||
conn.execute(&format!("UPDATE {table} SET at_ms=?"), [day + 1000])
|
||||
.unwrap();
|
||||
}
|
||||
conn.execute("UPDATE price_settlements SET at_ms=?", [cutoff])
|
||||
.unwrap();
|
||||
let date: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [day], |r| r.get(0))
|
||||
.unwrap();
|
||||
let read = |engine: &Exchange, query| {
|
||||
engine.public_position_snapshot(serde_json::from_value(query).unwrap())
|
||||
};
|
||||
let first = read(&engine, json!({"user":wallet,"date":date,"limit":1})).unwrap();
|
||||
assert_eq!(first["summary"]["positions"], 3);
|
||||
assert_eq!(first["summary"]["cost_basis"], 1.55);
|
||||
assert_eq!(first["data"][0]["price_source"], "mark");
|
||||
assert_eq!(first["data"][0]["value"], 0.8);
|
||||
assert_eq!(first["summary"]["value_by_source"]["basis"], 0.75);
|
||||
assert!(first["summary"]["closed_block"].is_null());
|
||||
let cursor = first["pagination"]["next_cursor"].as_str().unwrap();
|
||||
drop(engine);
|
||||
let engine = Exchange::open(&path).unwrap();
|
||||
let second = read(
|
||||
&engine,
|
||||
json!({"user_address":wallet,"cursor":cursor,"limit":999}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(second["pagination"]["limit"], 1);
|
||||
assert_eq!(second["pagination"]["offset"], 1);
|
||||
assert_eq!(second["data"][0]["price_source"], "basis");
|
||||
assert_eq!(second["data"][0]["size"], 0.75);
|
||||
assert_eq!(second["data"][0]["cost_basis"], 0.375);
|
||||
assert_eq!(second["data"][0]["avg_price"], 0.5);
|
||||
assert!(second.get("summary").is_none());
|
||||
assert!(read(&engine, json!({"user":maker,"cursor":cursor})).is_err());
|
||||
assert!(read(
|
||||
&engine,
|
||||
json!({"user":wallet,"cursor":cursor,"date":"2023-11-17"})
|
||||
)
|
||||
.is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2099-01-01"})).is_err());
|
||||
assert!(read(&engine, json!({"user":wallet,"date":"2023-02-30"})).is_err());
|
||||
|
||||
let next_day: String = conn
|
||||
.query_row("SELECT date(?1/1000,'unixepoch')", [cutoff], |r| r.get(0))
|
||||
.unwrap();
|
||||
let settled = read(&engine, json!({"user":wallet,"date":next_day})).unwrap();
|
||||
assert_eq!(settled["data"][0]["price_source"], "settlement");
|
||||
assert_eq!(settled["data"][0]["price"], 0);
|
||||
assert_eq!(settled["data"][0]["cost_basis"], 0.8);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
{"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;全部候选人按甲、乙、其余三组互斥且穷尽。","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"]}
|
||||
{"op":"list","id":"list-pending","market":"pending","rules":"An unrelated binary condition"}
|
||||
{"op":"fund","id":"fund","account":"alice","cents":200}
|
||||
{"op":"prepare_combo","id":"prepare","legs":[{"market":"b","outcome":"YES"},{"market":"pending","outcome":"YES"}]}
|
||||
{"op":"split_combo","id":"split","combo":"combo:5f919da914566e59bd98cf0b0139a50a164cf4fff7bcc4e7cd8612f5cde7bcb5","account":"alice","qty_micros":1000001}
|
||||
{"op":"combo","combo":"combo:5f919da914566e59bd98cf0b0139a50a164cf4fff7bcc4e7cd8612f5cde7bcb5","account":"alice"}
|
||||
{"op":"close","id":"close-a","market":"a"}
|
||||
{"op":"finalize","id":"finalize-a","market":"a","winner":"YES"}
|
||||
{"op":"combo","combo":"combo:5f919da914566e59bd98cf0b0139a50a164cf4fff7bcc4e7cd8612f5cde7bcb5","account":"alice"}
|
||||
{"op":"redeem_combo","id":"redeem-no","combo":"combo:5f919da914566e59bd98cf0b0139a50a164cf4fff7bcc4e7cd8612f5cde7bcb5","account":"alice","outcome":"NO","qty_micros":1000001}
|
||||
{"op":"close","id":"close-b","market":"b"}
|
||||
{"op":"finalize","id":"finalize-b","market":"b","winner":"NO"}
|
||||
{"op":"combo","combo":"combo:5f919da914566e59bd98cf0b0139a50a164cf4fff7bcc4e7cd8612f5cde7bcb5","account":"alice"}
|
||||
@@ -425,19 +425,15 @@ fidelity 以分钟为单位;省略或不大于零时按 1 分钟处理。相
|
||||
|
||||
官方 OpenAPI 给出的 condition 和 event 查询按条件返回,question 查询以问题为单位。两种查询的更新时间分别是 UTC 时间和 Unix 秒数字符串。本地使用记录下来的提案、争议和兑付时间。早期数据库缺失的时间保留为空。本地未接入链上事件,交易哈希和日志序号保留空串,区块号、报告人及投票截止估计省略。new_version_q 采用 OpenAPI 对规则修订的定义,本地原始规则不可改。旧版官方子图在 QuestionInitialized 上直接置 true,这一点存在口径差异。提案到期后需按模拟系统的最终确认流程兑付。本次按规范、合约及子图核对,生产端点没有取得可重放的响应。[官方接口](https://docs.polymarket.com/api-reference/markets/get-resolution-state) · [OpenAPI](https://data-api.polymarket.com/v2/openapi.json) · [UMA 适配器](https://github.com/Polymarket/uma-ctf-adapter/blob/main/src/UmaCtfAdapter.sol) · [裁决子图](https://github.com/Polymarket/resolution-subgraph/blob/main/src/uma-ctf-adapter.ts)
|
||||
|
||||
### 日终快照的历史份额
|
||||
|
||||
官方日终快照在次日 UTC 零点切断,结合当时持仓、价格来源和历史成本。本地先提供交易账本的历史份额。首次启用时原子记录当前余额作为历史起点,之后逐事务记录变化,保留可用份额和挂卖预留的合计。同毫秒以写入序号定序;查询排除切点本身。旧流水里没有可信时间或分侧数量的部分不能精确回填。公开快照按钱包和闭日读取,份额小于或等于 0.1 的仓位被省略。价格取切点前兑付结果、最近可用的窄价差中点或末笔交易,再回退到成本。成本由切点前的成交、拆分、合并和兑付流水重放,并与历史份额核对。本地拆分将抵押成本各半分给 YES 和 NO,最小单位余数归 NO。合并及部分兑付按减少的份额移除平均成本。新流水用跨表写入序号定序。无法确认顺序的同毫秒旧流水及缺少逐腿成本的互斥转换返回零成本。模拟账本中的区块号为 null,资产字段使用本地 ID。生产行情采样和结构仓位成本仍待对照。[官方日终持仓快照](https://docs.polymarket.com/api-reference/wallet/snapshot-a-wallets-positions-at-the-end-of-a-day)
|
||||
|
||||
本地组合与单盘共用分页及汇总,并按本地稳定顺序追加组合。组合使用模块 3,`title`、`slug`、`event_slug` 为 null。组合余额与成本均从日终切点之前的账本流水重放。任一腿兑付为零可提前确定组合兑付,其余情况等待所有腿。零兑付侧保留终局之前的成本,即使之后已部分烧毁。未结算时只采用切点之前该侧的真实组合成交价。拆分或合并成交有两侧报价,直接转让只为成交的一侧记录价格。缺价回退到成本。结算价值按实际份额使用完整兑付精度,显示的每份价格保留到微美元。本次生产快照请求返回 403。生产行情来源和成本样例仍待获取。
|
||||
|
||||
### Data API 账户持仓价值
|
||||
|
||||
官方 `GET /v2/value` 要求传 user,可选最多 20 个不同 condition。结果是 data 对象,内含 proxy_wallet 和四位小数精度的美元金额。一个无持仓的钱包值为零。官方总额还包括未终结组合的成本基础,指定 condition 时仅统计选中的单盘。资金余额不计入持仓价值。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
本地可以重放 [估值样例](examples/valuation.jsonl)。按样例依次查询 Alice,可见首次成交后 NO 缺价;买一和卖一收窄后所有持仓合计 8.87;裁决 YES 胜后为 8;赎回后为 0。持仓含挂卖预留份额。另一个回归使用两个各持有 0.000030 对份额且最终平分兑付的市场,总额 0.000060 舍入为 0.0001,单独查询任一市场则为 0。估值汇总、份额精度和多条件筛选可通过 public_wallet_value_rounds_after_summing_and_scopes_each_condition 复核。
|
||||
|
||||
当前本地价值端点仅聚合单盘持仓。组合成本已能从组合持仓与日终快照读取,仍待接入该端点。无价时 HTTP 返回可重试的 503,这是本地明确的处理方式,官方公开规范没有给出此种输入的专门示例。协议地址校验采用公布的 Polygon 部署清单,尚未取得生产 API 内部地址集合或舍入中点的线上样本。本轮生产估值接口连接超时。[官方部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
带组合的钱包可重放 [组合询价样例](examples/combo-rfq.jsonl)。成交及部分减仓后,taker 与 maker 的全钱包估值分别为 0.875 和 1.625,按 `condition=combo-a` 查询则都为 0。本地采用组合账本保存的剩余成本汇总,再对总额舍入。任一入选结果的兑付为零时,本地组合已可确定结果,立即从总额排除,即使还有腿等待裁决。公开规范确认排除终结组合,生产环境对提前判定、成本粒度和舍入中点的具体处理仍待实测。[官方 OpenAPI](https://data-api.polymarket.com/v2/openapi.json)
|
||||
|
||||
单盘无价时,本地 HTTP 返回可重试的 503。协议地址校验采用公布的 Polygon 部署清单,生产 API 使用的完整地址集合仍待实测。[官方部署地址](https://docs.polymarket.com/resources/contracts)
|
||||
|
||||
### Data API 未平仓量与归档
|
||||
|
||||
@@ -475,6 +471,8 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
|
||||
本地接受 2 至 50 条已经上架的二元腿。按市场 ID 排序后生成独立的本地组合 ID,两侧份额使用其各自的本地标识。拆分、合并和兑付与抵押账本及请求回执同事务写入,不改动底层市场的份额。组合账本在最后一笔份额烧毁后登记无法兑付的尾差。重放[组合样例](examples/combo-ledger.jsonl),分别选择 A 的 YES 和 B 的 NO。拆分 1000003 微份后合并 2 微份。两条腿都作废时,YES 每份为 0.25,NO 每份为 0.75,实际分别兑付 250000 与 750000 微美元,最后记录 1 微美元尾差。
|
||||
|
||||
V2 NegRisk 在组内已有赢家时会按需把其他成员推导为 NO。组合读取同一结果来确定能否兑付,并复用它展示各腿状态及排除已确定结果的组合成本。重放[互斥组合样例](examples/combo-derived-resolution.jsonl),只裁决甲赢时,组合所选的乙 YES 已确定兑付为零,另一条腿仍待裁决,持有人此时即可用组合 NO 赎回 1000001 微美元。随后单独记录乙 NO,不会改变这条腿已公开的结算时间。暂缺生产 NegRisk 组合的同盘对照,模拟器的独立盘口仍按原有流程裁决和兑付。[V2 NegRisk 与组合模块](https://github.com/Polymarket/polymarket-v2-external/blob/main/docs/modules.md)
|
||||
|
||||
本轮公开组合候选目录返回 HTTP 403。生产 RFQ 资格、报价和成交,链上标识以及组合持仓对账仍待接入和验证。[公开候选目录规范](https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets)
|
||||
|
||||
### 组合 RFQ 的状态、预留与成交
|
||||
|
||||
Reference in New Issue
Block a user