Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5bbe185257 | |||
| f32b817c0a |
+25
-34
@@ -9,6 +9,8 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
main["src/main.rs"] -->|把标准输入输出交给 serve| stream["src/stream.rs"]
|
||||
main -->|启动公开行情 HTTP| market_http["src/market_http.rs"]
|
||||
market_http -.->|查询 Gamma 标签及目录| api
|
||||
main -.->|打开数据库| api["exchange crate"]
|
||||
stream -.->|执行命令| api
|
||||
```
|
||||
@@ -247,40 +249,6 @@ sequenceDiagram
|
||||
|
||||
event_id 取自本地 events 或 catalog 查询,market_id 取自 assets 查询。两个参数均可重复,同类 ID 取并集,同时指定事件与市场时取交集。独立市场的公告也能通过 market_id 查询。默认按公告 ID 降序,每页 20 条;支持 order=id、ascending、offset 和 0 到 100 的 limit。当前查询对其他筛选参数返回 400。
|
||||
|
||||
### 组合账本
|
||||
|
||||
重放[组合样例](../../docs/examples/combo-ledger.jsonl),或自选两个已上架市场的结果,向 `prepare_combo` 提交 `legs`。取回的 `combo` ID 可用于 `split_combo`、`merge_combo`、`redeem_combo` 和只读的 `combo`。拆分和合并的数量表示成对的 YES 和 NO 份额,兑付需要指定一侧。数量可使用整数份额 `qty` 或微份 `qty_micros`。只读查询加 `account` 可查看该账户的两侧份额。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor U as 操作员
|
||||
participant S as stream.rs
|
||||
participant E as Exchange
|
||||
U->>S: prepare_combo,提交腿的市场与选择
|
||||
S->>E: 执行组合定义命令
|
||||
E-->>U: 组合 ID、腿和可兑奖状态
|
||||
U->>S: split_combo,再查询 combo
|
||||
S->>E: 冻结模拟现金,生成 YES 和 NO
|
||||
E-->>U: 账户两侧的微份额及当前兑付状态
|
||||
```
|
||||
|
||||
### 组合询价
|
||||
|
||||
重放[组合询价样例](../../docs/examples/combo-rfq.jsonl)。样例先用双方现金生成互补的组合份额,再用已有份额合并并卖出。报价方通过 `combo_rfq_open` 发现尚未结束的询价。请求方用 `combo_rfq` 查看报价,再接受指定报价。报价与接受命令使用各自的请求 ID,账户余额查询会列出已受理询价的现金预留。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant J as JSONL 命令入口
|
||||
actor M as 报价方
|
||||
T->>J: request_combo_quote
|
||||
M->>J: combo_rfq_open 与 quote_combo
|
||||
T->>J: accept_combo_quote,指定报价 ID
|
||||
J-->>T: 确认期限与预留状态
|
||||
M->>J: respond_combo_quote,提交最后确认
|
||||
T->>J: combo_rfq,读取成交或失败状态
|
||||
```
|
||||
|
||||
### 从事件页进入订单簿
|
||||
|
||||
```mermaid
|
||||
@@ -459,3 +427,26 @@ sequenceDiagram
|
||||
E-->>H: true
|
||||
H-->>C: 200,neg_risk 为真
|
||||
```
|
||||
|
||||
|
||||
## Gamma 标签
|
||||
|
||||
按顺序重放 [NVIDIA 主题](../../docs/examples/topic.jsonl)和[标签样例](../../docs/examples/gamma-tags.jsonl)。使用 `GET /tags` 发现标签,使用 `GET /tags/101` 或 `GET /tags/slug/technology` 查询同一标签。事件和市场的数字 ID 分别来自 `GET /events?slug=nvda-closing-price-2027` 与 `GET /markets?slug=nvda-200`,可以拼入 `/events/{id}/tags` 或 `/markets/{id}/tags`。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor C as 目录客户端
|
||||
participant H as market_http.rs
|
||||
participant E as Exchange
|
||||
C->>H: GET /tags/slug/price-thresholds
|
||||
H->>E: 按 slug 读取标签
|
||||
E-->>C: id 为字符串 102
|
||||
C->>H: GET /markets?tag_id=102&include_tag=true
|
||||
H->>E: 在分页前筛选已关联的市场
|
||||
E-->>H: nvda-200 和对应标签数组
|
||||
H-->>C: 盘口列表
|
||||
C->>H: GET /tags/slug/technology/related-tags/tags?omit_empty=true
|
||||
H->>E: 查 Technology 的直接相关标签及其开放赛事
|
||||
E-->>H: Price thresholds
|
||||
H-->>C: 相关标签详情数组
|
||||
```
|
||||
|
||||
+168
-11
@@ -255,7 +255,7 @@ fn market_lookup(engine: &Mutex<Exchange>, prefix: &str, raw: &str) -> Reply {
|
||||
|
||||
fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
let (resource, tail) = path.strip_prefix('/')?.split_once('/')?;
|
||||
if !matches!(resource, "markets" | "events") {
|
||||
if !matches!(resource, "markets" | "events" | "tags") {
|
||||
return None;
|
||||
}
|
||||
let (by_slug, raw) = match tail.strip_prefix("slug/") {
|
||||
@@ -265,27 +265,103 @@ fn directory_route(path: &str) -> Option<(&str, bool, &str)> {
|
||||
(!raw.is_empty() && !raw.contains('/')).then_some((resource, by_slug, raw))
|
||||
}
|
||||
|
||||
enum TagRoute<'a> {
|
||||
Related((bool, &'a str, bool)),
|
||||
Resource((exchange::DirectoryResource, &'a str)),
|
||||
}
|
||||
|
||||
fn related_tags_route(path: &str) -> Option<(bool, &str, bool)> {
|
||||
let (path, expanded) = path
|
||||
.strip_suffix("/tags")
|
||||
.map_or((path, false), |p| (p, true));
|
||||
let (resource, by_slug, raw) = directory_route(path.strip_suffix("/related-tags")?)?;
|
||||
(resource == "tags").then_some((by_slug, raw, expanded))
|
||||
}
|
||||
|
||||
fn related_tags(engine: &Mutex<Exchange>, route: (bool, &str, bool), params: &str) -> Reply {
|
||||
let (by_slug, raw, expanded) = route;
|
||||
let slug;
|
||||
let key = if by_slug {
|
||||
slug = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
exchange::DirectoryKey::Slug(&slug)
|
||||
} else {
|
||||
exchange::DirectoryKey::Id(directory_id(raw)?)
|
||||
};
|
||||
let query = serde_urlencoded::from_str::<exchange::RelatedTagsQuery>(params)
|
||||
.map_err(|_| (422, "Invalid related tag query"))?;
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.gamma_related_tags(key, expanded, query)
|
||||
.map(Value::Array)
|
||||
.map_err(|_| (500, "Directory unavailable"))
|
||||
}
|
||||
|
||||
fn resource_tags_route(path: &str) -> Option<(exchange::DirectoryResource, &str)> {
|
||||
let (resource, id) = path
|
||||
.strip_prefix('/')?
|
||||
.strip_suffix("/tags")?
|
||||
.split_once('/')?;
|
||||
if id.is_empty() || id.contains('/') {
|
||||
return None;
|
||||
}
|
||||
let resource = match resource {
|
||||
"events" => exchange::DirectoryResource::Events,
|
||||
"markets" => exchange::DirectoryResource::Markets,
|
||||
_ => return None,
|
||||
};
|
||||
Some((resource, id))
|
||||
}
|
||||
|
||||
fn resource_tags(
|
||||
engine: &Mutex<Exchange>,
|
||||
route: (exchange::DirectoryResource, &str),
|
||||
query: &str,
|
||||
) -> Reply {
|
||||
if !query.is_empty() {
|
||||
return Err((400, "Unsupported directory query"));
|
||||
}
|
||||
let (resource, raw) = route;
|
||||
let id = directory_id(raw)?;
|
||||
engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.gamma_resource_tags(resource, id)
|
||||
.map_err(|_| (500, "Directory unavailable"))?
|
||||
.ok_or((404, "Not found"))
|
||||
}
|
||||
|
||||
fn directory_id(raw: &str) -> std::result::Result<i64, (u16, &'static str)> {
|
||||
let value = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|id| *id > 0 && value.bytes().all(|b| b.is_ascii_digit()))
|
||||
.ok_or((400, "Invalid directory id"))
|
||||
}
|
||||
|
||||
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 slug;
|
||||
let key = if by_slug {
|
||||
exchange::DirectoryKey::Slug(&value)
|
||||
slug = percent_decode_str(raw)
|
||||
.decode_utf8()
|
||||
.map_err(|_| (400, "Invalid directory key"))?;
|
||||
exchange::DirectoryKey::Slug(&slug)
|
||||
} 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)
|
||||
exchange::DirectoryKey::Id(directory_id(raw)?)
|
||||
};
|
||||
let exchange = engine.lock().map_err(|_| (500, "Directory unavailable"))?;
|
||||
let found = match resource {
|
||||
"markets" => exchange.gamma_market(key),
|
||||
"tags" => exchange.gamma_tag(key),
|
||||
_ => exchange.gamma_event(key),
|
||||
};
|
||||
found
|
||||
@@ -358,7 +434,43 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
};
|
||||
return send(req, status, body, None);
|
||||
}
|
||||
let tags_lookup = related_tags_route(path)
|
||||
.map(TagRoute::Related)
|
||||
.or_else(|| resource_tags_route(path).map(TagRoute::Resource));
|
||||
if let Some(lookup) = tags_lookup {
|
||||
if req.method() != &Method::Get {
|
||||
return send(req, 405, json!({"error":"Method not allowed"}), Some("GET"));
|
||||
}
|
||||
let reply = match lookup {
|
||||
TagRoute::Related(route) => related_tags(engine, route, params),
|
||||
TagRoute::Resource(route) => resource_tags(engine, route, params),
|
||||
};
|
||||
let (status, body) = match reply {
|
||||
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, "/tags") => {
|
||||
let query = serde_urlencoded::from_str::<exchange::TagsQuery>(params);
|
||||
match query {
|
||||
Ok(query) => engine
|
||||
.lock()
|
||||
.map_err(|_| (500, "Directory unavailable"))
|
||||
.and_then(|e| {
|
||||
e.gamma_tags(query)
|
||||
.map(Value::Array)
|
||||
.map_err(|err| match err {
|
||||
exchange::MarketDataError::Invalid(_) => (422, "Invalid tag query"),
|
||||
exchange::MarketDataError::Unavailable => {
|
||||
(500, "Directory unavailable")
|
||||
}
|
||||
})
|
||||
}),
|
||||
Err(_) => Err((422, "Invalid tag query")),
|
||||
}
|
||||
}
|
||||
(&Method::Get, _) if is_setting => token_setting(name, engine, params, segment),
|
||||
(_, _) if is_setting => {
|
||||
allow = Some("GET");
|
||||
@@ -471,6 +583,7 @@ fn respond(mut req: Request, engine: &Mutex<Exchange>) -> std::io::Result<()> {
|
||||
| "/markets"
|
||||
| "/events"
|
||||
| "/market-clarifications"
|
||||
| "/tags"
|
||||
| "/v2/oi"
|
||||
| "/v2/value"
|
||||
| "/v2/trades"
|
||||
@@ -656,6 +769,13 @@ mod tests {
|
||||
{
|
||||
db.execute(serde_json::from_str(command).unwrap()).unwrap();
|
||||
}
|
||||
for line in include_str!("../../../docs/examples/gamma-tags.jsonl").lines() {
|
||||
db.execute(serde_json::from_str(line).unwrap()).unwrap();
|
||||
}
|
||||
assert!(db
|
||||
.execute(json!({"op":"set_tags","id":"invalid-tag-replacement",
|
||||
"kind":"event","target":"nvda-2027","tag_ids":[101,999]}))
|
||||
.is_err());
|
||||
let topic = db
|
||||
.gamma_event(exchange::DirectoryKey::Slug("nvda-closing-price-2027"))
|
||||
.unwrap()
|
||||
@@ -690,6 +810,20 @@ mod tests {
|
||||
assert_eq!(quoted["bestBid"], json!(0.39));
|
||||
assert_eq!(quoted["bestAsk"], json!(0.41));
|
||||
assert_eq!(quoted["outcomePrices"], r#"["0.4","0.6"]"#);
|
||||
assert!(db
|
||||
.execute(json!({"op":"set_related_tags","id":"invalid-tag-links",
|
||||
"tag_id":101,"links":[{"id":9001,"related_tag_id":999,"rank":1}]}))
|
||||
.is_err());
|
||||
let links = json!([{"id":"9001","tagID":101,"relatedTagID":103,"rank":1},
|
||||
{"id":"9002","tagID":101,"relatedTagID":102,"rank":2}]);
|
||||
let event_tags_path = format!("{event_path}/tags");
|
||||
let market_tags_path = format!("{market_path}/tags");
|
||||
let event_tags = topic["tags"].clone();
|
||||
assert_eq!(event_tags[0]["id"], "101");
|
||||
assert_eq!(event_tags[1]["id"], "102");
|
||||
let market_tags = json!([event_tags[1].clone()]);
|
||||
let mut tagged_market = info.clone();
|
||||
tagged_market["tags"] = market_tags.clone();
|
||||
let empty_trades = json!({"data":[],"pagination":{"limit":100,"offset":0,"has_more":false,"next_cursor":null}});
|
||||
let cases = [
|
||||
("GET","/v2/oi?conditionId=s,s",String::new(),200,Some(json!({"data":[{"condition_id":"s","value":0}]}))),
|
||||
@@ -715,6 +849,29 @@ mod tests {
|
||||
("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","/tags?order=id&ascending=true&limit=1&offset=1",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags?is_carousel=false",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags/101",String::new(),200,Some(event_tags[0].clone())),
|
||||
("GET","/tags/slug/price-thresholds",String::new(),200,Some(event_tags[1].clone())),
|
||||
("GET","/tags/101/related-tags",String::new(),200,Some(links.clone())),
|
||||
("GET","/tags/slug/technology/related-tags?omit_empty=true",String::new(),200,Some(json!([links[1].clone()]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=true&status=closed",String::new(),200,Some(json!([links[0].clone()]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=true&status=all",String::new(),200,Some(links)),
|
||||
("GET","/tags/slug/technology/related-tags/tags?omit_empty=true",String::new(),200,Some(market_tags.clone())),
|
||||
("GET","/tags/999/related-tags",String::new(),200,Some(json!([]))),
|
||||
("GET","/tags/101/related-tags?omit_empty=invalid",String::new(),422,None),
|
||||
("GET","/markets?tag_id=101&related_tags=true&include_tag=true",String::new(),200,Some(json!([tagged_market.clone()]))),
|
||||
("GET","/events?tag_id=101&related_tags=true&closed=false",String::new(),200,Some(json!([topic.clone()]))),
|
||||
("GET","/events?tag_id=101&related_tags=false&closed=true",String::new(),200,Some(json!([]))),
|
||||
("GET","/events?tag_id=101&related_tags=true&tag_slug=technology&closed=true",String::new(),200,Some(json!([]))),
|
||||
("GET","/tags/999",String::new(),404,None),
|
||||
("GET",event_tags_path.as_str(),String::new(),200,Some(event_tags.clone())),
|
||||
("GET",market_tags_path.as_str(),String::new(),200,Some(market_tags)),
|
||||
("GET","/markets/999999/tags",String::new(),404,None),
|
||||
("GET","/events?tag_id=101&tag_slug=price-thresholds",String::new(),200,Some(json!([topic.clone()]))),
|
||||
("GET","/events?tag_id=101&exclude_tag_id=102",String::new(),200,Some(json!([]))),
|
||||
("GET","/markets?tag_id=102&include_tag=true",String::new(),200,Some(json!([tagged_market]))),
|
||||
("GET","/markets?tag_id=101",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!([]))),
|
||||
|
||||
+27
-54
@@ -9,6 +9,15 @@
|
||||
```mermaid
|
||||
flowchart LR
|
||||
test["tests/market.rs"] -->|通过公开 API 驱动市场| api["src/lib.rs"]
|
||||
api -->|初始化标签表| tags_sql["src/gamma_tags.sql"]
|
||||
market -->|保存标签及其归属| tags["src/gamma_tags.rs"]
|
||||
tags --> tags_sql
|
||||
tags --> tag_links_sql["src/gamma_tag_links.sql"]
|
||||
lists -->|扩展指定标签的直接关系| tags
|
||||
directory["src/gamma_directory.rs"] -->|读取赛事标签| event_sql["src/gamma_events.sql"]
|
||||
lists["src/gamma_list.rs"] --> directory
|
||||
lists --> tags
|
||||
event_sql --> tags_sql
|
||||
api -->|解析结果资产 ID| assets["src/assets.rs"]
|
||||
queries -->|解析单笔和批量报价| marks
|
||||
marks -->|拆解每个 token_id| assets
|
||||
@@ -29,15 +38,6 @@ flowchart LR
|
||||
holders -->|按余额及结果分页| holderrows["src/holders.sql"]
|
||||
holderrows -->|读取含挂单预留的持仓| markschema
|
||||
holders -->|按毛持仓估值| portfolio
|
||||
api -->|迁移组合账本| combo_schema["src/combo_schema.sql"]
|
||||
market -->|建立组合与处理抵押| combo["src/combo.rs"]
|
||||
queries -->|读取定义、腿状态及余额| combo
|
||||
combo -->|复用现金微单位账本| ledger["src/ledger.rs"]
|
||||
combo --> combo_schema
|
||||
market -->|处理组合询价和最后确认| combo_rfq["src/combo_rfq.rs"]
|
||||
combo_rfq -->|预留与转移份额| combo
|
||||
combo_rfq -->|读写询价和成交| combo_rfq_sql["src/combo_rfq_schema.sql"]
|
||||
expiry["src/expiry.rs"] -->|独立提交到期退款| combo_rfq
|
||||
api -->|接收轮换心跳 ID| beat["src/heartbeat.rs"]
|
||||
book -->|记录订单所属 key| beat
|
||||
expiry -->|清理到期注册| beat
|
||||
@@ -409,51 +409,6 @@ sequenceDiagram
|
||||
E-->>U: 提交后新增的赢家 YES 即可赎回
|
||||
```
|
||||
|
||||
## 组合份额与兑付
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant E as Exchange
|
||||
participant C as combo.rs
|
||||
participant D as SQLite
|
||||
O->>E: prepare_combo,提交各市场及选择结果
|
||||
E->>C: 规范化腿并生成组合 ID
|
||||
C->>D: 保存组合定义与腿
|
||||
O->>E: split_combo,抵押模拟现金
|
||||
E->>C: 铸出等量 YES 和 NO
|
||||
C->>D: 提交现金扣减、份额和流水
|
||||
O->>E: combo,查询可兑奖状态
|
||||
E->>C: 读取各腿实际裁决
|
||||
alt 任一腿兑付为零或全部腿已裁决
|
||||
O->>E: redeem_combo,指定一侧与数量
|
||||
C->>D: 扣减份额、释放抵押、写流水
|
||||
else 仍有悬而未决的腿
|
||||
E-->>O: 返回待裁决状态
|
||||
end
|
||||
```
|
||||
|
||||
## 组合 RFQ 的预留与成交
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor T as 请求方
|
||||
participant E as exchange / SQLite
|
||||
actor M as 报价方
|
||||
T->>E: request_combo_quote,选择方向、结果和数量
|
||||
M->>E: combo_rfq_open,再提交 quote_combo
|
||||
T->>E: accept_combo_quote
|
||||
E->>E: 原子预留双方现金或份额
|
||||
alt 报价方在期限内确认且腿仍可交易
|
||||
M->>E: respond_combo_quote,确认
|
||||
E->>E: 转让、拆分或合并,提交唯一成交
|
||||
E-->>T: FILLED
|
||||
else 拒绝、腿关闭或期限届满
|
||||
E->>E: 释放预留,保留终态
|
||||
E-->>T: FAILED 或 EXPIRED
|
||||
end
|
||||
```
|
||||
|
||||
## 开盘后出现新候选人
|
||||
|
||||
`command.rs` 和 `market.rs` 把增强型组合的定义、命名和裁决交给 `augmented.rs`。成员编号和转换沿用 `neg_risk.rs`;`schema.sql` 拦截未命名盘口的直接订单。`catalog.rs`、`assets.rs` 和 `portfolio.rs` 从同一条命名记录生成展示字段。
|
||||
@@ -1488,3 +1443,21 @@ sequenceDiagram
|
||||
E-->>C: 返回本次两侧销毁量和实付金额
|
||||
end
|
||||
```
|
||||
|
||||
|
||||
## Gamma 标签和目录筛选
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor O as 操作员
|
||||
participant E as Exchange
|
||||
participant T as gamma_tags.rs
|
||||
participant D as SQLite
|
||||
actor C as 公开客户端
|
||||
O->>E: 登记标签、设置归属及相关标签关系
|
||||
E->>T: 校验目标与标签编号
|
||||
T->>D: 按事务保存标签、归属或带排名的有向关系
|
||||
C->>E: 查询标签、归属或按标签筛选目录
|
||||
E->>D: 查询关联,按需扩展数字标签的直接关系,再筛选和分页
|
||||
E-->>C: 标签对象、市场或赛事列表
|
||||
```
|
||||
|
||||
@@ -294,17 +294,6 @@ pub(crate) enum Query {
|
||||
event: Option<String>,
|
||||
slug: Option<String>,
|
||||
},
|
||||
ComboRfq {
|
||||
rfq: String,
|
||||
account: String,
|
||||
},
|
||||
ComboRfqOpen {
|
||||
limit: Option<u32>,
|
||||
},
|
||||
Combo {
|
||||
combo: String,
|
||||
account: Option<String>,
|
||||
},
|
||||
History {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -324,9 +313,6 @@ impl Query {
|
||||
.response(),
|
||||
)
|
||||
}
|
||||
Self::ComboRfq { rfq, account } => crate::combo_rfq::read(db, &rfq, &account),
|
||||
Self::ComboRfqOpen { limit } => crate::combo_rfq::open_requests(db, limit),
|
||||
Self::Combo { combo, account } => crate::combo::read(db, &combo, account.as_deref()),
|
||||
Self::Price(request) => request.single(db),
|
||||
Self::Prices { requests } => crate::quotes::prices(db, &requests),
|
||||
Self::QuoteHistory(request) => request.read(db),
|
||||
|
||||
@@ -1,349 +0,0 @@
|
||||
use crate::{
|
||||
assets,
|
||||
inventory::{quantity_units, UNIT},
|
||||
ledger,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
const FACTOR_UNIT: u128 = 10u128.pow(36);
|
||||
const FACTOR_LIMB: u128 = 10u128.pow(18);
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub(crate) enum Side {
|
||||
Yes,
|
||||
No,
|
||||
}
|
||||
|
||||
impl Side {
|
||||
pub(super) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Yes => "YES",
|
||||
Self::No => "NO",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn opposite(self) -> Self {
|
||||
match self {
|
||||
Self::Yes => Self::No,
|
||||
Self::No => Self::Yes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Leg {
|
||||
market: String,
|
||||
outcome: Side,
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(tx: &Transaction, mut legs: Vec<Leg>) -> Result<Value> {
|
||||
ensure!(
|
||||
(2..=50).contains(&legs.len()),
|
||||
"a combo requires 2 to 50 legs"
|
||||
);
|
||||
legs.sort_unstable_by(|a, b| a.market.cmp(&b.market));
|
||||
ensure!(
|
||||
legs.windows(2).all(|pair| pair[0].market != pair[1].market),
|
||||
"duplicate or conflicting combo market"
|
||||
);
|
||||
let canonical = serde_json::to_string(&legs)?;
|
||||
let hash = Sha256::digest(canonical.as_bytes());
|
||||
let id = format!("combo:{}", data_encoding::HEXLOWER.encode(&hash));
|
||||
let stored = tx
|
||||
.query_row(
|
||||
"SELECT canonical_legs FROM combo_conditions WHERE id=?",
|
||||
[&id],
|
||||
|r| r.get::<_, String>(0),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some(stored) = stored {
|
||||
ensure!(stored == canonical, "combo definition mismatch");
|
||||
return read(tx, &id, None);
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO combo_conditions(id,canonical_legs) VALUES(?,?)",
|
||||
params![id, canonical],
|
||||
)?;
|
||||
let mut insert = tx.prepare_cached(
|
||||
"INSERT INTO combo_legs(combo,market,outcome)
|
||||
SELECT ?1,m.id,?3 FROM markets m LEFT JOIN augmented_outcomes a ON a.market=m.id
|
||||
WHERE m.id=?2 AND COALESCE(a.role,'')<>'placeholder'",
|
||||
)?;
|
||||
for leg in &legs {
|
||||
identifier(&leg.market)?;
|
||||
ensure!(
|
||||
insert.execute(params![id, leg.market, leg.outcome.name()])? == 1,
|
||||
"unknown or hidden combo leg"
|
||||
);
|
||||
}
|
||||
read(tx, &id, None)
|
||||
}
|
||||
|
||||
struct Factor {
|
||||
down: u128,
|
||||
up: u128,
|
||||
}
|
||||
|
||||
impl Factor {
|
||||
fn resolved(payouts: &[Option<i64>]) -> Option<Self> {
|
||||
if payouts.contains(&Some(0)) {
|
||||
return Some(Self { down: 0, up: 0 });
|
||||
}
|
||||
if payouts.iter().any(Option::is_none) {
|
||||
return None;
|
||||
}
|
||||
// The local binary ledger has only full, zero and half payouts.
|
||||
let halves = payouts
|
||||
.iter()
|
||||
.filter(|payout| **payout == Some(UNIT / 2))
|
||||
.count();
|
||||
let denominator = 1u128 << halves;
|
||||
Some(Self {
|
||||
down: FACTOR_UNIT / denominator,
|
||||
up: FACTOR_UNIT.div_ceil(denominator),
|
||||
})
|
||||
}
|
||||
|
||||
fn payout(&self, side: Side, quantity: i64) -> i64 {
|
||||
match side {
|
||||
Side::Yes => product(quantity, self.down, false),
|
||||
Side::No => quantity - product(quantity, self.up, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn product(quantity: i64, factor: u128, round_up: bool) -> i64 {
|
||||
// Use base 10^18 limbs so an i64-sized share balance never needs a wide multiply.
|
||||
let qty = quantity as u128;
|
||||
let low = qty * (factor % FACTOR_LIMB);
|
||||
let high = qty * (factor / FACTOR_LIMB) + low / FACTOR_LIMB;
|
||||
let floor = high / FACTOR_LIMB;
|
||||
let has_remainder = high % FACTOR_LIMB != 0 || low % FACTOR_LIMB != 0;
|
||||
(floor + u128::from(round_up && has_remainder)) as i64
|
||||
}
|
||||
|
||||
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";
|
||||
|
||||
pub(crate) fn read(db: &Connection, combo: &str, account: Option<&str>) -> Result<Value> {
|
||||
let Some((collateral, dust)) = db
|
||||
.query_row(
|
||||
"SELECT collateral_micros,rounding_dust_micros FROM combo_conditions WHERE id=?",
|
||||
[combo],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
else {
|
||||
anyhow::bail!("unknown combo")
|
||||
};
|
||||
let mut legs = Vec::new();
|
||||
let mut payouts = Vec::new();
|
||||
let mut stmt = db.prepare_cached(SELECT_LEGS)?;
|
||||
let mut rows = stmt.query([combo])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let market = row.get::<_, String>(0)?;
|
||||
let outcome = row.get::<_, String>(1)?;
|
||||
let payout: Option<i64> = row.get(2)?;
|
||||
payouts.push(payout);
|
||||
legs.push(json!({
|
||||
"market":market,"outcome":outcome,"position_id":assets::id(&market,&outcome),
|
||||
"payout_micros_per_share":payout,"resolved_at_ms":row.get::<_,Option<i64>>(3)?
|
||||
}));
|
||||
}
|
||||
let factor = Factor::resolved(&payouts);
|
||||
let mut detail = json!({
|
||||
"combo":combo,"position_ids":[position_id(combo,Side::Yes),position_id(combo,Side::No)],
|
||||
"legs":legs,"redeemable":factor.is_some(),
|
||||
"payout_micros_per_share":factor.as_ref().map(|f| [f.payout(Side::Yes,UNIT),f.payout(Side::No,UNIT)]),
|
||||
"collateral_micros":collateral,"rounding_dust_micros":dust
|
||||
});
|
||||
if let Some(account) = account {
|
||||
identifier(account)?;
|
||||
detail["account"] = json!(account);
|
||||
let available = [
|
||||
balance(db, combo, account, Side::Yes)?,
|
||||
balance(db, combo, account, Side::No)?,
|
||||
];
|
||||
let (yes, no): (i64,i64) = db.query_row(
|
||||
"SELECT COALESCE(SUM(h.shares_micros) FILTER (WHERE h.outcome='YES'),0),
|
||||
COALESCE(SUM(h.shares_micros) FILTER (WHERE h.outcome='NO'),0)
|
||||
FROM combo_rfq_holds h JOIN combo_rfqs r ON r.id=h.rfq WHERE r.combo=? AND h.account=?",
|
||||
params![combo,account], |r| Ok((r.get(0)?,r.get(1)?)),
|
||||
)?;
|
||||
detail["balances_micros"] = json!([
|
||||
available[0]
|
||||
.checked_add(yes)
|
||||
.context("combo balance overflow")?,
|
||||
available[1]
|
||||
.checked_add(no)
|
||||
.context("combo balance overflow")?,
|
||||
]);
|
||||
if yes > 0 || no > 0 {
|
||||
detail["available_micros"] = json!(available);
|
||||
detail["reserved_micros"] = json!([yes, no]);
|
||||
}
|
||||
}
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
fn position_id(combo: &str, side: Side) -> String {
|
||||
format!(
|
||||
"ebc:{}:{}",
|
||||
side.name(),
|
||||
combo.strip_prefix("combo:").unwrap_or(combo)
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn balance(
|
||||
db: &Connection,
|
||||
combo: &str,
|
||||
account: &str,
|
||||
side: Side,
|
||||
) -> rusqlite::Result<i64> {
|
||||
db.query_row("SELECT COALESCE((SELECT shares_micros FROM combo_balances WHERE combo=? AND account=? AND outcome=?),0)",
|
||||
params![combo,account,side.name()], |r| r.get(0))
|
||||
}
|
||||
|
||||
pub(super) fn change_balance(
|
||||
tx: &Transaction,
|
||||
combo: &str,
|
||||
account: &str,
|
||||
side: Side,
|
||||
change: i64,
|
||||
) -> Result<()> {
|
||||
let qty = balance(tx, combo, account, side)?
|
||||
.checked_add(change)
|
||||
.context("combo balance overflow")?;
|
||||
ensure!(qty >= 0, "insufficient combo balance");
|
||||
if qty == 0 {
|
||||
tx.execute(
|
||||
"DELETE FROM combo_balances WHERE combo=? AND account=? AND outcome=?",
|
||||
params![combo, account, side.name()],
|
||||
)?;
|
||||
} else {
|
||||
tx.execute(
|
||||
"INSERT INTO combo_balances VALUES(?,?,?,?)
|
||||
ON CONFLICT(combo,account,outcome) DO UPDATE SET shares_micros=excluded.shares_micros",
|
||||
params![combo, account, side.name(), qty],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn change_backing(tx: &Transaction, combo: &str, change: i64) -> Result<()> {
|
||||
let (old, dust) = tx.query_row(
|
||||
"SELECT collateral_micros,rounding_dust_micros FROM combo_conditions WHERE id=?",
|
||||
[combo],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
let new = old
|
||||
.checked_add(change)
|
||||
.context("combo collateral overflow")?;
|
||||
ensure!(new >= 0, "insufficient combo collateral");
|
||||
let held: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_balances WHERE combo=?1)
|
||||
OR EXISTS(SELECT 1 FROM combo_rfq_holds h JOIN combo_rfqs r ON r.id=h.rfq
|
||||
WHERE r.combo=?1 AND h.outcome IS NOT NULL)",
|
||||
[combo],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let (locked, dust) = if held {
|
||||
(new, dust)
|
||||
} else {
|
||||
(0, dust.checked_add(new).context("combo dust overflow")?)
|
||||
};
|
||||
tx.execute(
|
||||
"UPDATE combo_conditions SET collateral_micros=?,rounding_dust_micros=? WHERE id=?",
|
||||
params![locked, dust, combo],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Amount {
|
||||
combo: String,
|
||||
account: String,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Redemption {
|
||||
combo: String,
|
||||
account: String,
|
||||
outcome: Side,
|
||||
qty: Option<i64>,
|
||||
qty_micros: Option<i64>,
|
||||
}
|
||||
|
||||
impl Amount {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request: &str, split: bool) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
let qty = quantity_units(self.qty, self.qty_micros)?;
|
||||
let delta = if split { qty } else { -qty };
|
||||
change_balance(tx, &self.combo, &self.account, Side::Yes, delta)?;
|
||||
change_balance(tx, &self.combo, &self.account, Side::No, delta)?;
|
||||
change_backing(tx, &self.combo, delta)?;
|
||||
ledger::cash_micros(tx, &self.account, -delta)?;
|
||||
let kind = if split { "SPLIT" } else { "MERGE" };
|
||||
tx.execute("INSERT INTO combo_movements(request_id,combo,account,kind,shares_micros,cash_delta_micros)
|
||||
VALUES(?,?,?,?,?,?)",params![request,self.combo,self.account,kind,qty,-delta])?;
|
||||
Ok(json!({"combo":self.combo,"pairs_micros":qty,"cash_delta_micros":-delta}))
|
||||
}
|
||||
}
|
||||
|
||||
impl Redemption {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request: &str) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
let qty = quantity_units(self.qty, self.qty_micros)?;
|
||||
let mut stmt = tx.prepare_cached(SELECT_LEGS)?;
|
||||
let payouts = stmt
|
||||
.query_map([&self.combo], |r| r.get(2))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
ensure!(!payouts.is_empty(), "unknown combo");
|
||||
let factor = Factor::resolved(&payouts).context("combo payout is pending")?;
|
||||
let paid = factor.payout(self.outcome, qty);
|
||||
change_balance(tx, &self.combo, &self.account, self.outcome, -qty)?;
|
||||
change_backing(tx, &self.combo, -paid)?;
|
||||
if paid > 0 {
|
||||
ledger::cash_micros(tx, &self.account, paid)?;
|
||||
}
|
||||
tx.execute("INSERT INTO combo_movements(request_id,combo,account,kind,outcome,shares_micros,cash_delta_micros)
|
||||
VALUES(?,?,?,'REDEEM',?,?,?)",params![request,self.combo,self.account,self.outcome.name(),qty,paid])?;
|
||||
Ok(
|
||||
json!({"combo":self.combo,"outcome":self.outcome,"burned_micros":qty,"paid_micros":paid}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn high_precision_uses_separate_down_and_up_accumulators() {
|
||||
let factor = Factor::resolved(&[Some(500000); 37]).unwrap();
|
||||
let qty = 1_i64 << 37;
|
||||
assert_eq!(factor.payout(Side::Yes, qty), 0);
|
||||
assert_eq!(factor.payout(Side::No, qty), qty - 2);
|
||||
let full = Factor::resolved(&[Some(1000000); 50]).unwrap();
|
||||
assert_eq!(full.payout(Side::Yes, i64::MAX), i64::MAX);
|
||||
assert_eq!(full.payout(Side::No, i64::MAX), 0);
|
||||
}
|
||||
}
|
||||
@@ -1,565 +0,0 @@
|
||||
use crate::{
|
||||
combo::{self, Side},
|
||||
inventory::UNIT,
|
||||
ledger,
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const REQUESTER: &str = "AWAITING_REQUESTER_ACCEPTANCE";
|
||||
const MAKER: &str = "AWAITING_MAKER_CONFIRMATION";
|
||||
const MAX_MICROS: i64 = 1_000_000_000 * UNIT;
|
||||
const DB_NOW: &str = "SELECT CAST(unixepoch('subsec')*1000 AS INTEGER)";
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
enum Direction {
|
||||
Buy,
|
||||
Sell,
|
||||
}
|
||||
|
||||
impl Direction {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Buy => "BUY",
|
||||
Self::Sell => "SELL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Source {
|
||||
Collateral,
|
||||
Inventory,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Collateral => "collateral",
|
||||
Self::Inventory => "inventory",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Request {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
shares_micros: Option<i64>,
|
||||
notional_micros: Option<i64>,
|
||||
submission_window_ms: Option<i64>,
|
||||
acceptance_window_ms: Option<i64>,
|
||||
last_look_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Quote {
|
||||
rfq: String,
|
||||
maker: String,
|
||||
price_micros: i64,
|
||||
shares_micros: i64,
|
||||
source: Source,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Accept {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
quote: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Respond {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
confirm: bool,
|
||||
}
|
||||
|
||||
struct Rfq {
|
||||
combo: String,
|
||||
requester: String,
|
||||
direction: Direction,
|
||||
side: Side,
|
||||
size_unit: String,
|
||||
requested: i64,
|
||||
submission_deadline: i64,
|
||||
expires_at: i64,
|
||||
last_look_ms: i64,
|
||||
status: String,
|
||||
selected_quote: Option<String>,
|
||||
confirm_by: Option<i64>,
|
||||
failure: Option<String>,
|
||||
}
|
||||
|
||||
struct QuoteRow {
|
||||
id: String,
|
||||
maker: String,
|
||||
price: i64,
|
||||
shares: i64,
|
||||
cash: i64,
|
||||
source: Source,
|
||||
canceled: bool,
|
||||
}
|
||||
|
||||
fn now(db: &Connection) -> rusqlite::Result<i64> {
|
||||
db.query_row(DB_NOW, [], |r| r.get(0))
|
||||
}
|
||||
|
||||
fn window(value: Option<i64>, default: i64) -> Result<i64> {
|
||||
let ms = value.unwrap_or(default);
|
||||
ensure!((1..=300_000).contains(&ms), "invalid RFQ window");
|
||||
Ok(ms)
|
||||
}
|
||||
|
||||
fn tradable(db: &Connection, combo: &str) -> rusqlite::Result<bool> {
|
||||
db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_tradable WHERE id=?)",
|
||||
[combo],
|
||||
|r| r.get(0),
|
||||
)
|
||||
}
|
||||
|
||||
fn stored_side(side: &str) -> Side {
|
||||
if side == "YES" {
|
||||
Side::Yes
|
||||
} else {
|
||||
Side::No
|
||||
}
|
||||
}
|
||||
|
||||
fn request(db: &Connection, id: &str) -> rusqlite::Result<Rfq> {
|
||||
db.query_row(
|
||||
"SELECT combo,requester,direction,outcome,size_unit,requested_micros,submission_deadline,
|
||||
expires_at,last_look_ms,status,selected_quote,confirm_by,failure
|
||||
FROM combo_rfqs WHERE id=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(Rfq {
|
||||
combo: r.get(0)?,
|
||||
requester: r.get(1)?,
|
||||
direction: if r.get::<_, String>(2)? == "BUY" {
|
||||
Direction::Buy
|
||||
} else {
|
||||
Direction::Sell
|
||||
},
|
||||
side: stored_side(&r.get::<_, String>(3)?),
|
||||
size_unit: r.get(4)?,
|
||||
requested: r.get(5)?,
|
||||
submission_deadline: r.get(6)?,
|
||||
expires_at: r.get(7)?,
|
||||
last_look_ms: r.get(8)?,
|
||||
status: r.get(9)?,
|
||||
selected_quote: r.get(10)?,
|
||||
confirm_by: r.get(11)?,
|
||||
failure: r.get(12)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const QUOTE_COLUMNS: &str =
|
||||
"SELECT id,maker,price_micros,shares_micros,cash_micros,source,canceled FROM combo_rfq_quotes";
|
||||
|
||||
fn quote_row(r: &Row<'_>) -> rusqlite::Result<QuoteRow> {
|
||||
Ok(QuoteRow {
|
||||
id: r.get(0)?,
|
||||
maker: r.get(1)?,
|
||||
price: r.get(2)?,
|
||||
shares: r.get(3)?,
|
||||
cash: r.get(4)?,
|
||||
source: if r.get::<_, String>(5)? == "collateral" {
|
||||
Source::Collateral
|
||||
} else {
|
||||
Source::Inventory
|
||||
},
|
||||
canceled: r.get(6)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn quote(db: &Connection, rfq: &str, id: &str) -> rusqlite::Result<QuoteRow> {
|
||||
db.prepare_cached(&format!("{QUOTE_COLUMNS} WHERE rfq=? AND id=?"))?
|
||||
.query_row(params![rfq, id], quote_row)
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.requester)?;
|
||||
ensure!(
|
||||
tradable(tx, &self.combo)?,
|
||||
"unknown combo or unavailable leg"
|
||||
);
|
||||
let (unit, size) = match (self.shares_micros, self.notional_micros, self.direction) {
|
||||
(Some(q), None, _) => ("shares", q),
|
||||
(None, Some(q), Direction::Buy) => ("notional", q),
|
||||
_ => anyhow::bail!("provide one share size or a BUY notional budget"),
|
||||
};
|
||||
ensure!((1..=MAX_MICROS).contains(&size), "invalid RFQ size");
|
||||
let submitted = now(tx)?;
|
||||
let submission_deadline = submitted + window(self.submission_window_ms, 10_000)?;
|
||||
let expires_at = submission_deadline + window(self.acceptance_window_ms, 20_000)?;
|
||||
let last_look_ms = window(self.last_look_ms, 5_000)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfqs(id,combo,requester,direction,outcome,size_unit,requested_micros,
|
||||
submission_deadline,expires_at,last_look_ms,status)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,'AWAITING_REQUESTER_ACCEPTANCE')",
|
||||
params![id,self.combo,self.requester,self.direction.name(),self.side.name(),unit,size,
|
||||
submission_deadline,expires_at,last_look_ms],
|
||||
)?;
|
||||
read(tx, id, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
impl Quote {
|
||||
pub(crate) fn apply(self, tx: &Transaction, id: &str) -> Result<Value> {
|
||||
identifier(&self.maker)?;
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now(tx)? < rfq.submission_deadline,
|
||||
"submission window closed"
|
||||
);
|
||||
ensure!(self.maker != rfq.requester, "no self RFQ quotes");
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
ensure!(
|
||||
(1..UNIT).contains(&self.price_micros)
|
||||
&& (1..=MAX_MICROS).contains(&self.shares_micros),
|
||||
"invalid quote amounts"
|
||||
);
|
||||
let cash = (i128::from(self.price_micros) * i128::from(self.shares_micros)
|
||||
/ i128::from(UNIT)) as i64;
|
||||
ensure!(
|
||||
cash > 0
|
||||
&& if rfq.size_unit == "notional" {
|
||||
cash <= rfq.requested
|
||||
} else {
|
||||
self.shares_micros <= rfq.requested
|
||||
},
|
||||
"quote exceeds requested size or rounds to zero"
|
||||
);
|
||||
let candidate = QuoteRow {
|
||||
id: id.into(),
|
||||
maker: self.maker,
|
||||
price: self.price_micros,
|
||||
shares: self.shares_micros,
|
||||
cash,
|
||||
source: self.source,
|
||||
canceled: false,
|
||||
};
|
||||
let maker_funding = funding(&rfq, &candidate).1;
|
||||
maker_funding.check(tx, &rfq.combo, &candidate.maker)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_quotes(id,rfq,maker,price_micros,shares_micros,cash_micros,source,seq)
|
||||
SELECT ?1,?2,?3,?4,?5,?6,?7,COALESCE(MAX(seq),0)+1 FROM combo_rfq_quotes WHERE rfq=?2",
|
||||
params![id,self.rfq,candidate.maker,candidate.price,candidate.shares,cash,candidate.source.name()],
|
||||
)?;
|
||||
Ok(
|
||||
json!({"rfq_id":self.rfq,"quote_id":id,"price_micros":candidate.price,
|
||||
"shares_micros":candidate.shares,"cash_micros":cash}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
enum Funding {
|
||||
Cash(i64),
|
||||
Shares(Side, i64),
|
||||
}
|
||||
|
||||
impl Funding {
|
||||
fn check(&self, tx: &Transaction, combo: &str, account: &str) -> Result<()> {
|
||||
match *self {
|
||||
Self::Cash(amount) => {
|
||||
let (cents, remainder) = tx.query_row(
|
||||
"SELECT a.cash,COALESCE(r.micros,0) FROM accounts a
|
||||
LEFT JOIN cash_remainders r ON r.account=a.id WHERE a.id=?",
|
||||
[account],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
ensure!(
|
||||
i128::from(cents) * 10000 + i128::from(remainder) >= i128::from(amount),
|
||||
"insufficient RFQ cash"
|
||||
);
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
ensure!(
|
||||
combo::balance(tx, combo, account, side)? >= amount,
|
||||
"insufficient RFQ shares"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve(self, tx: &Transaction, id: &str, combo: &str, account: &str) -> Result<()> {
|
||||
match self {
|
||||
Self::Cash(amount) => {
|
||||
ledger::cash_micros(tx, account, -amount)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_holds(rfq,account,cash_micros) VALUES(?,?,?)",
|
||||
params![id, account, amount],
|
||||
)?;
|
||||
}
|
||||
Self::Shares(side, amount) => {
|
||||
combo::change_balance(tx, combo, account, side, -amount)?;
|
||||
tx.execute("INSERT INTO combo_rfq_holds(rfq,account,outcome,shares_micros) VALUES(?,?,?,?)",
|
||||
params![id,account,side.name(),amount])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn funding(rfq: &Rfq, q: &QuoteRow) -> (Funding, Funding) {
|
||||
use Funding::{Cash, Shares};
|
||||
match (rfq.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => (Cash(q.cash), Cash(q.shares - q.cash)),
|
||||
(Direction::Buy, Source::Inventory) => (Cash(q.cash), Shares(rfq.side, q.shares)),
|
||||
(Direction::Sell, Source::Collateral) => (Shares(rfq.side, q.shares), Cash(q.cash)),
|
||||
(Direction::Sell, Source::Inventory) => (
|
||||
Shares(rfq.side, q.shares),
|
||||
Shares(rfq.side.opposite(), q.shares),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
impl Accept {
|
||||
pub(crate) fn apply(self, tx: &Transaction) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
ensure!(self.requester == rfq.requester, "RFQ requester mismatch");
|
||||
let now = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == REQUESTER && now < rfq.expires_at,
|
||||
"RFQ acceptance window closed"
|
||||
);
|
||||
ensure!(tradable(tx, &rfq.combo)?, "unavailable combo leg");
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(!quote.canceled, "quote unavailable");
|
||||
let (requester, maker) = funding(&rfq, "e);
|
||||
requester.reserve(tx, &self.rfq, &rfq.combo, &rfq.requester)?;
|
||||
maker.reserve(tx, &self.rfq, &rfq.combo, "e.maker)?;
|
||||
tx.execute("UPDATE combo_rfqs SET status='AWAITING_MAKER_CONFIRMATION',selected_quote=?,confirm_by=? WHERE id=?",
|
||||
params![self.quote,now+rfq.last_look_ms,self.rfq])?;
|
||||
read(tx, &self.rfq, &self.requester)
|
||||
}
|
||||
}
|
||||
|
||||
fn refund(tx: &Transaction, id: &str, combo: &str) -> Result<()> {
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"SELECT account,outcome,shares_micros,cash_micros FROM combo_rfq_holds WHERE rfq=?",
|
||||
)?;
|
||||
let mut rows = stmt.query([id])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let account = r.get::<_, String>(0)?;
|
||||
if let Some(side) = r.get::<_, Option<String>>(1)? {
|
||||
combo::change_balance(tx, combo, &account, stored_side(&side), r.get(2)?)?;
|
||||
} else {
|
||||
ledger::cash_micros(tx, &account, r.get(3)?)?;
|
||||
}
|
||||
}
|
||||
tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Respond {
|
||||
pub(crate) fn apply(self, tx: &Transaction, request_id: &str) -> Result<Value> {
|
||||
let rfq = request(tx, &self.rfq)?;
|
||||
let quote = quote(tx, &self.rfq, &self.quote)?;
|
||||
ensure!(quote.maker == self.maker, "RFQ maker mismatch");
|
||||
let clock = now(tx)?;
|
||||
ensure!(
|
||||
rfq.status == MAKER
|
||||
&& rfq.selected_quote.as_deref() == Some(self.quote.as_str())
|
||||
&& rfq.confirm_by.is_some_and(|by| clock < by),
|
||||
"last-look window closed"
|
||||
);
|
||||
if !self.confirm || !tradable(tx, &rfq.combo)? {
|
||||
let reason = if self.confirm {
|
||||
"LEG_UNAVAILABLE"
|
||||
} else {
|
||||
"MAKER_DECLINED"
|
||||
};
|
||||
refund(tx, &self.rfq, &rfq.combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FAILED',failure=? WHERE id=?",
|
||||
params![reason, self.rfq],
|
||||
)?;
|
||||
return read(tx, &self.rfq, &self.maker);
|
||||
}
|
||||
let changed = tx.execute("DELETE FROM combo_rfq_holds WHERE rfq=?", [&self.rfq])?;
|
||||
ensure!(changed == 2, "RFQ funding missing");
|
||||
let flow = settle(tx, &rfq, "e)?;
|
||||
tx.execute(
|
||||
"INSERT INTO combo_rfq_trades(rfq,quote,request_id,flow,executed_at) VALUES(?,?,?,?,?)",
|
||||
params![self.rfq, self.quote, request_id, flow, clock],
|
||||
)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='FILLED' WHERE id=?",
|
||||
[&self.rfq],
|
||||
)?;
|
||||
read(tx, &self.rfq, &self.maker)
|
||||
}
|
||||
}
|
||||
|
||||
fn settle(tx: &Transaction, r: &Rfq, q: &QuoteRow) -> Result<&'static str> {
|
||||
match (r.direction, q.source) {
|
||||
(Direction::Buy, Source::Collateral) => {
|
||||
combo::change_balance(tx, &r.combo, &r.requester, r.side, q.shares)?;
|
||||
combo::change_balance(tx, &r.combo, &q.maker, r.side.opposite(), q.shares)?;
|
||||
combo::change_backing(tx, &r.combo, q.shares)?;
|
||||
Ok("MINT")
|
||||
}
|
||||
(Direction::Sell, Source::Inventory) => {
|
||||
combo::change_backing(tx, &r.combo, -q.shares)?;
|
||||
ledger::cash_micros(tx, &r.requester, q.cash)?;
|
||||
ledger::cash_micros(tx, &q.maker, q.shares - q.cash)?;
|
||||
Ok("MERGE")
|
||||
}
|
||||
(direction, _) => {
|
||||
let (buyer, seller) = match direction {
|
||||
Direction::Buy => (&r.requester, &q.maker),
|
||||
Direction::Sell => (&q.maker, &r.requester),
|
||||
};
|
||||
combo::change_balance(tx, &r.combo, buyer, r.side, q.shares)?;
|
||||
ledger::cash_micros(tx, seller, q.cash)?;
|
||||
Ok("TRANSFER")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_quote(
|
||||
tx: &Transaction,
|
||||
id: &str,
|
||||
quote_id: &str,
|
||||
maker: &str,
|
||||
) -> Result<Value> {
|
||||
let q = quote(tx, id, quote_id)?;
|
||||
ensure!(
|
||||
!q.canceled && q.maker == maker && request(tx, id)?.status == REQUESTER,
|
||||
"quote cannot be canceled"
|
||||
);
|
||||
tx.execute(
|
||||
"UPDATE combo_rfq_quotes SET canceled=1 WHERE id=?",
|
||||
[quote_id],
|
||||
)?;
|
||||
Ok(json!({"rfq_id":id,"quote_id":quote_id,"canceled":true}))
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_request(tx: &Transaction, id: &str, owner: &str) -> Result<Value> {
|
||||
let r = request(tx, id)?;
|
||||
ensure!(
|
||||
r.requester == owner && r.status == REQUESTER,
|
||||
"RFQ cannot be canceled"
|
||||
);
|
||||
tx.execute("UPDATE combo_rfqs SET status='CANCELED' WHERE id=?", [id])?;
|
||||
read(tx, id, owner)
|
||||
}
|
||||
|
||||
pub(crate) fn expire(tx: &Transaction) -> Result<()> {
|
||||
let due = {
|
||||
let mut stmt = tx.prepare_cached(include_str!("combo_rfq_due.sql"))?;
|
||||
let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
rows.collect::<rusqlite::Result<Vec<_>>>()?
|
||||
};
|
||||
for (id, combo) in due {
|
||||
refund(tx, &id, &combo)?;
|
||||
tx.execute(
|
||||
"UPDATE combo_rfqs SET status='EXPIRED',failure='DEADLINE_ELAPSED' WHERE id=?",
|
||||
[id],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn open_requests(db: &Connection, limit: Option<u32>) -> Result<Value> {
|
||||
let limit = limit.unwrap_or(50);
|
||||
ensure!((1..=100).contains(&limit), "invalid RFQ listing limit");
|
||||
let mut stmt=db.prepare_cached(
|
||||
"SELECT r.id,r.combo,r.direction,r.outcome,r.size_unit,r.requested_micros,r.submission_deadline,
|
||||
c.canonical_legs
|
||||
FROM combo_rfqs r JOIN combo_rfq_tradable c ON c.id=r.combo
|
||||
WHERE r.status='AWAITING_REQUESTER_ACCEPTANCE'
|
||||
AND r.submission_deadline>CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
ORDER BY r.submission_deadline,r.id LIMIT ?",
|
||||
)?;
|
||||
let mut result = Vec::new();
|
||||
let mut rows = stmt.query([limit])?;
|
||||
while let Some(r) = rows.next()? {
|
||||
let legs: Value = serde_json::from_str(&r.get::<_, String>(7)?)?;
|
||||
result.push(json!({
|
||||
"rfq_id":r.get::<_,String>(0)?,"combo":r.get::<_,String>(1)?,
|
||||
"direction":r.get::<_,String>(2)?,"side":r.get::<_,String>(3)?,
|
||||
"requested_size":{"unit":r.get::<_,String>(4)?,"value_micros":r.get::<_,i64>(5)?},
|
||||
"submission_deadline":r.get::<_,i64>(6)?,"legs":legs
|
||||
}));
|
||||
}
|
||||
Ok(json!({"rfqs":result}))
|
||||
}
|
||||
|
||||
pub(crate) fn read(db: &Connection, id: &str, viewer: &str) -> Result<Value> {
|
||||
let r = request(db, id)?;
|
||||
let owner = r.requester == viewer;
|
||||
let quoted: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM combo_rfq_quotes WHERE rfq=? AND maker=?)",
|
||||
params![id, viewer],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(owner || quoted, "RFQ not visible to account");
|
||||
let ranks = if matches!(r.direction, Direction::Buy) {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut stmt = db.prepare_cached(&format!(
|
||||
"{QUOTE_COLUMNS} WHERE rfq=?1 AND (?2 OR maker=?3) AND canceled=0
|
||||
ORDER BY price_micros {ranks},shares_micros DESC,seq"
|
||||
))?;
|
||||
let quotes = stmt
|
||||
.query_map(params![id, owner, viewer], quote_row)?
|
||||
.map(|q| {
|
||||
q.map(|q| {
|
||||
json!({"quote_id":q.id,"maker":q.maker,"price_micros":q.price,
|
||||
"shares_micros":q.shares,"cash_micros":q.cash,"source":q.source})
|
||||
})
|
||||
})
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
let selected = r.selected_quote.filter(|id| {
|
||||
owner
|
||||
|| quotes
|
||||
.iter()
|
||||
.any(|q| q["quote_id"].as_str() == Some(id.as_str()))
|
||||
});
|
||||
let fill = if selected.is_some() && r.status == "FILLED" {
|
||||
db.query_row(
|
||||
"SELECT t.executed_at,t.flow,q.price_micros,q.shares_micros,q.cash_micros
|
||||
FROM combo_rfq_trades t JOIN combo_rfq_quotes q ON q.id=t.quote WHERE t.rfq=?",
|
||||
[id],
|
||||
|r| {
|
||||
Ok(
|
||||
json!({"executed_at":r.get::<_,i64>(0)?,"flow":r.get::<_,String>(1)?,
|
||||
"price_micros":r.get::<_,i64>(2)?,"shares_micros":r.get::<_,i64>(3)?,
|
||||
"cash_micros":r.get::<_,i64>(4)?}),
|
||||
)
|
||||
},
|
||||
)
|
||||
.optional()?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(json!({
|
||||
"rfq_id":id,"combo":r.combo,"direction":r.direction,"side":r.side,"status":r.status,
|
||||
"requested_size":{"unit":r.size_unit,"value_micros":r.requested},
|
||||
"submission_deadline":r.submission_deadline,"expires_at":r.expires_at,"quotes":quotes,
|
||||
"confirm_by":r.confirm_by.filter(|_|selected.is_some()),"selected_quote":selected,
|
||||
"failure":r.failure,"fill":fill
|
||||
}))
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
SELECT id,combo FROM combo_rfqs
|
||||
WHERE (status='AWAITING_REQUESTER_ACCEPTANCE' AND expires_at<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR (status='AWAITING_MAKER_CONFIRMATION' AND confirm_by<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
@@ -1,65 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfqs (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
requester TEXT NOT NULL REFERENCES accounts(id),
|
||||
direction TEXT NOT NULL CHECK(direction IN ('BUY','SELL')),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
size_unit TEXT NOT NULL CHECK(size_unit IN ('shares','notional')),
|
||||
requested_micros INTEGER NOT NULL CHECK(requested_micros>0),
|
||||
submission_deadline INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
last_look_ms INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'AWAITING_REQUESTER_ACCEPTANCE','AWAITING_MAKER_CONFIRMATION','FILLED','FAILED','EXPIRED','CANCELED'
|
||||
)),
|
||||
selected_quote TEXT,
|
||||
confirm_by INTEGER,
|
||||
failure TEXT,
|
||||
FOREIGN KEY(id,selected_quote) REFERENCES combo_rfq_quotes(rfq,id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_open_deadline ON combo_rfqs(expires_at)
|
||||
WHERE status='AWAITING_REQUESTER_ACCEPTANCE';
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_last_look ON combo_rfqs(confirm_by)
|
||||
WHERE status='AWAITING_MAKER_CONFIRMATION';
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_quotes (
|
||||
id TEXT PRIMARY KEY REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
maker TEXT NOT NULL REFERENCES accounts(id),
|
||||
price_micros INTEGER NOT NULL CHECK(price_micros BETWEEN 1 AND 999999),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_micros INTEGER NOT NULL CHECK(cash_micros>0),
|
||||
source TEXT NOT NULL CHECK(source IN ('collateral','inventory')),
|
||||
canceled INTEGER NOT NULL DEFAULT 0 CHECK(canceled IN (0,1)),
|
||||
seq INTEGER NOT NULL,
|
||||
UNIQUE(rfq,id),
|
||||
UNIQUE(rfq,seq)
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS combo_rfq_live_maker_quote ON combo_rfq_quotes(rfq,maker)
|
||||
WHERE canceled=0;
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_holds (
|
||||
rfq TEXT NOT NULL REFERENCES combo_rfqs(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL DEFAULT 0 CHECK(shares_micros>=0),
|
||||
cash_micros INTEGER NOT NULL DEFAULT 0 CHECK(cash_micros>=0),
|
||||
PRIMARY KEY(rfq,account),
|
||||
CHECK((outcome IS NULL AND shares_micros=0 AND cash_micros>0)
|
||||
OR (outcome IS NOT NULL AND shares_micros>0 AND cash_micros=0))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_holds_account ON combo_rfq_holds(account);
|
||||
CREATE INDEX IF NOT EXISTS combo_rfq_by_condition ON combo_rfqs(combo);
|
||||
CREATE TABLE IF NOT EXISTS combo_rfq_trades (
|
||||
rfq TEXT PRIMARY KEY REFERENCES combo_rfqs(id),
|
||||
quote TEXT NOT NULL REFERENCES combo_rfq_quotes(id),
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
flow TEXT NOT NULL CHECK(flow IN ('TRANSFER','MINT','MERGE')),
|
||||
executed_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS combo_rfq_tradable AS
|
||||
SELECT c.id,c.canonical_legs FROM combo_conditions c
|
||||
WHERE NOT EXISTS(SELECT 1 FROM combo_legs l JOIN markets m ON m.id=l.market
|
||||
LEFT JOIN market_visibility v ON v.market=m.id
|
||||
WHERE l.combo=c.id AND (m.phase NOT IN ('preopen','continuous')
|
||||
OR COALESCE(v.active,1)=0 OR COALESCE(v.archived,0)=1));
|
||||
COMMIT;
|
||||
@@ -1,34 +0,0 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS combo_conditions (
|
||||
id TEXT PRIMARY KEY,
|
||||
canonical_legs TEXT NOT NULL UNIQUE,
|
||||
collateral_micros INTEGER NOT NULL DEFAULT 0 CHECK(collateral_micros>=0),
|
||||
rounding_dust_micros INTEGER NOT NULL DEFAULT 0 CHECK(rounding_dust_micros>=0)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_legs (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
PRIMARY KEY(combo,market)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_balances (
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
outcome TEXT NOT NULL CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
PRIMARY KEY(combo,account,outcome)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS combo_movements (
|
||||
seq INTEGER PRIMARY KEY,
|
||||
request_id TEXT NOT NULL UNIQUE REFERENCES requests(id) DEFERRABLE INITIALLY DEFERRED,
|
||||
combo TEXT NOT NULL REFERENCES combo_conditions(id),
|
||||
account TEXT NOT NULL REFERENCES accounts(id),
|
||||
kind TEXT NOT NULL CHECK(kind IN ('SPLIT','MERGE','REDEEM')),
|
||||
outcome TEXT CHECK(outcome IN ('YES','NO')),
|
||||
shares_micros INTEGER NOT NULL CHECK(shares_micros>0),
|
||||
cash_delta_micros INTEGER NOT NULL,
|
||||
at_ms INTEGER NOT NULL DEFAULT(CAST(unixepoch('subsec')*1000 AS INTEGER)),
|
||||
CHECK((kind='REDEEM')=(outcome IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS combo_movements_by_account ON combo_movements(account,at_ms,seq);
|
||||
COMMIT;
|
||||
@@ -9,6 +9,19 @@ pub(crate) enum Command {
|
||||
micros: Option<i64>,
|
||||
},
|
||||
Event(crate::catalog::Event),
|
||||
#[serde(rename = "upsert_tag")]
|
||||
UpsertTag(crate::gamma_tags::Tag),
|
||||
#[serde(rename = "set_tags")]
|
||||
SetTags {
|
||||
kind: crate::gamma_tags::TagTarget,
|
||||
target: String,
|
||||
tag_ids: Vec<i64>,
|
||||
},
|
||||
#[serde(rename = "set_related_tags")]
|
||||
SetRelatedTags {
|
||||
tag_id: i64,
|
||||
links: Vec<crate::gamma_tags::TagLink>,
|
||||
},
|
||||
#[serde(rename = "reschedule_sports")]
|
||||
RescheduleSports {
|
||||
event: String,
|
||||
@@ -36,35 +49,6 @@ pub(crate) enum Command {
|
||||
listing: Option<crate::catalog::Listing>,
|
||||
resolution: Option<crate::resolution::Policy>,
|
||||
},
|
||||
#[serde(rename = "prepare_combo")]
|
||||
PrepareCombo {
|
||||
legs: Vec<crate::combo::Leg>,
|
||||
},
|
||||
#[serde(rename = "split_combo")]
|
||||
SplitCombo(crate::combo::Amount),
|
||||
#[serde(rename = "merge_combo")]
|
||||
MergeCombo(crate::combo::Amount),
|
||||
#[serde(rename = "redeem_combo")]
|
||||
RedeemCombo(crate::combo::Redemption),
|
||||
#[serde(rename = "request_combo_quote")]
|
||||
RequestComboQuote(crate::combo_rfq::Request),
|
||||
#[serde(rename = "quote_combo")]
|
||||
QuoteCombo(crate::combo_rfq::Quote),
|
||||
#[serde(rename = "accept_combo_quote")]
|
||||
AcceptComboQuote(crate::combo_rfq::Accept),
|
||||
#[serde(rename = "respond_combo_quote")]
|
||||
RespondComboQuote(crate::combo_rfq::Respond),
|
||||
#[serde(rename = "cancel_combo_quote")]
|
||||
CancelComboQuote {
|
||||
rfq: String,
|
||||
quote: String,
|
||||
maker: String,
|
||||
},
|
||||
#[serde(rename = "cancel_combo_rfq")]
|
||||
CancelComboRfq {
|
||||
rfq: String,
|
||||
requester: String,
|
||||
},
|
||||
#[serde(rename = "define_neg_risk")]
|
||||
DefineNegRisk {
|
||||
group: String,
|
||||
|
||||
@@ -10,14 +10,14 @@ pub(crate) fn transaction(
|
||||
) -> Result<Transaction<'_>> {
|
||||
loop {
|
||||
let tx = Transaction::new_unchecked(db, behavior)?;
|
||||
let due: bool = tx.prepare_cached(concat!(
|
||||
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 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) OR EXISTS(",
|
||||
include_str!("combo_rfq_due.sql"), ")",
|
||||
))?.query_row([], |row| row.get(0))?;
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !due {
|
||||
return Ok(tx);
|
||||
}
|
||||
@@ -49,7 +49,6 @@ pub(crate) fn transaction(
|
||||
}
|
||||
crate::kickoff::clear_due(&write)?;
|
||||
crate::heartbeat::expire(&write)?;
|
||||
crate::combo_rfq::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
crate::depth_feed::flush(&write)?;
|
||||
write.commit()?;
|
||||
|
||||
@@ -18,7 +18,8 @@ pub(super) fn header(row: &Row<'_>) -> rusqlite::Result<(String, Value)> {
|
||||
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")?
|
||||
"active":true,"closed":row.get::<_,bool>("closed")?,
|
||||
"tags":crate::gamma_tags::parse_wire(row.get("tags")?)?
|
||||
});
|
||||
Ok((key, event))
|
||||
}
|
||||
|
||||
@@ -5,5 +5,6 @@ SELECT e.id,e.event_id,e.slug,e.title,e.category,
|
||||
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
|
||||
),0) AS closed,
|
||||
COALESCE((SELECT tags FROM event_tag_arrays a WHERE a.event=e.id),'[]') AS tags
|
||||
FROM numbered_events e
|
||||
|
||||
@@ -19,6 +19,11 @@ struct Filters {
|
||||
slugs: Vec<String>,
|
||||
conditions: Vec<String>,
|
||||
tokens: Vec<String>,
|
||||
tag_id: Option<i64>,
|
||||
tag_slug: Option<String>,
|
||||
excluded_tags: Vec<i64>,
|
||||
include_tag: bool,
|
||||
related_tags: bool,
|
||||
closed: Option<bool>,
|
||||
active: Option<bool>,
|
||||
order: String,
|
||||
@@ -70,6 +75,25 @@ impl Filters {
|
||||
.ok_or_else(|| invalid(key))?,
|
||||
),
|
||||
"slug" if !value.trim().is_empty() => f.slugs.push(value.clone()),
|
||||
"tag_id" | "exclude_tag_id" if key == "tag_id" || !markets => {
|
||||
let id = value
|
||||
.parse::<i64>()
|
||||
.ok()
|
||||
.filter(|id| *id > 0)
|
||||
.ok_or_else(|| invalid(key))?;
|
||||
if key == "tag_id" {
|
||||
f.tag_id = Some(id);
|
||||
} else {
|
||||
f.excluded_tags.push(id);
|
||||
}
|
||||
}
|
||||
"tag_slug" if !markets && !value.trim().is_empty() => {
|
||||
f.tag_slug = Some(value.clone());
|
||||
}
|
||||
"related_tags" => f.related_tags = value.parse().map_err(|_| invalid(key))?,
|
||||
"include_tag" if markets => {
|
||||
f.include_tag = value.parse().map_err(|_| invalid(key))?
|
||||
}
|
||||
"condition_ids" if markets && !value.trim().is_empty() => {
|
||||
f.conditions.push(value.clone())
|
||||
}
|
||||
@@ -130,11 +154,19 @@ const MARKET_FILTER: &str = "
|
||||
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)";
|
||||
AND (?8 IS NULL OR COALESCE(v.active,1)=?8)
|
||||
AND (?9 IS NULL OR EXISTS(SELECT 1 FROM market_tags a WHERE a.market=w.market
|
||||
AND a.tag IN (SELECT value FROM json_each(?9))))";
|
||||
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)";
|
||||
AND (?3 IS NULL OR e.closed=?3)
|
||||
AND (?6 IS NULL OR EXISTS(SELECT 1 FROM event_tags a WHERE a.event=e.id
|
||||
AND a.tag IN (SELECT value FROM json_each(?6))))
|
||||
AND (?7 IS NULL OR EXISTS(SELECT 1 FROM event_tags a JOIN directory_tags t ON t.id=a.tag
|
||||
WHERE a.event=e.id AND t.slug=?7))
|
||||
AND NOT EXISTS(SELECT 1 FROM event_tags a WHERE a.event=e.id
|
||||
AND a.tag IN (SELECT value FROM json_each(?8)))";
|
||||
|
||||
fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Value>> {
|
||||
// A supplied set containing only foreign tokens must match nothing.
|
||||
@@ -161,7 +193,8 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset,
|
||||
f.active
|
||||
f.active,
|
||||
crate::gamma_tags::tag_scope(db, f.tag_id, f.related_tags)?
|
||||
],
|
||||
|r| Ok((market(r)?, r.get::<_, Option<String>>("parent")?)),
|
||||
)?
|
||||
@@ -175,9 +208,30 @@ fn markets(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Va
|
||||
let events = headers
|
||||
.query_map([json!(parents).to_string()], header)?
|
||||
.collect::<rusqlite::Result<HashMap<_, _>>>()?;
|
||||
let mut tags = HashMap::<String, Value>::new();
|
||||
if f.include_tag {
|
||||
let keys: Vec<_> = rows
|
||||
.iter()
|
||||
.filter_map(|(row, _)| row["conditionId"].as_str())
|
||||
.collect();
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT market,tags FROM market_tag_arrays WHERE market IN (SELECT value FROM json_each(?))",
|
||||
)?;
|
||||
tags = stmt
|
||||
.query_map([json!(keys).to_string()], |r| {
|
||||
Ok((r.get(0)?, crate::gamma_tags::parse_wire(r.get(1)?)?))
|
||||
})?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
}
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|(mut row, parent)| {
|
||||
if f.include_tag {
|
||||
let assigned = row["conditionId"]
|
||||
.as_str()
|
||||
.and_then(|market| tags.remove(market));
|
||||
row["tags"] = assigned.unwrap_or_else(|| json!([]));
|
||||
}
|
||||
row["events"] = json!(parent
|
||||
.and_then(|key| events.get(&key))
|
||||
.into_iter()
|
||||
@@ -200,7 +254,10 @@ fn events(db: &Connection, f: &Filters, order: &str) -> rusqlite::Result<Vec<Val
|
||||
json!(f.slugs).to_string(),
|
||||
f.closed,
|
||||
f.limit,
|
||||
f.offset
|
||||
f.offset,
|
||||
crate::gamma_tags::tag_scope(db, f.tag_id, f.related_tags)?,
|
||||
f.tag_slug,
|
||||
json!(f.excluded_tags).to_string()
|
||||
],
|
||||
header,
|
||||
)?
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS directory_tag_links (
|
||||
id INTEGER PRIMARY KEY CHECK(id>0),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
related_tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
rank INTEGER NOT NULL CHECK(rank>=0),
|
||||
UNIQUE(tag,related_tag),
|
||||
CHECK(tag<>related_tag)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS event_tags_by_tag ON event_tags(tag,event);
|
||||
COMMIT;
|
||||
@@ -0,0 +1,268 @@
|
||||
use crate::{validation::identifier, DirectoryKey, DirectoryResource, Exchange, MarketDataError};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, ToSql, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Tag {
|
||||
tag_id: i64,
|
||||
slug: String,
|
||||
label: String,
|
||||
force_show: Option<bool>,
|
||||
force_hide: Option<bool>,
|
||||
is_carousel: Option<bool>,
|
||||
}
|
||||
|
||||
impl Tag {
|
||||
pub(crate) fn save(self, tx: &Transaction) -> Result<Value> {
|
||||
ensure!(self.tag_id > 0, "invalid tag id");
|
||||
identifier(&self.slug)?;
|
||||
identifier(&self.label)?;
|
||||
tx.execute(
|
||||
"INSERT INTO directory_tags VALUES(?1,?2,?3,?4,?5,?6,
|
||||
strftime('%Y-%m-%dT%H:%M:%fZ','now'),strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
||||
ON CONFLICT(id) DO UPDATE SET slug=excluded.slug,label=excluded.label,
|
||||
force_show=excluded.force_show,force_hide=excluded.force_hide,
|
||||
is_carousel=excluded.is_carousel,updated_at=excluded.updated_at",
|
||||
params![
|
||||
self.tag_id,
|
||||
self.slug,
|
||||
self.label,
|
||||
self.force_show,
|
||||
self.force_hide,
|
||||
self.is_carousel
|
||||
],
|
||||
)?;
|
||||
Ok(json!({"tag_id":self.tag_id.to_string()}))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum TagTarget {
|
||||
Event,
|
||||
Market,
|
||||
}
|
||||
|
||||
pub(crate) fn assign(
|
||||
tx: &Transaction,
|
||||
kind: TagTarget,
|
||||
target: &str,
|
||||
tags: Vec<i64>,
|
||||
) -> Result<Value> {
|
||||
identifier(target)?;
|
||||
ensure!(
|
||||
tags.iter().all(|id| *id > 0) && tags.iter().collect::<HashSet<_>>().len() == tags.len(),
|
||||
"tag ids must be positive and unique"
|
||||
);
|
||||
let (exists, remove, insert) = match kind {
|
||||
TagTarget::Event => (
|
||||
"SELECT EXISTS(SELECT 1 FROM event_directory_ids WHERE event=?)",
|
||||
"DELETE FROM event_tags WHERE event=?",
|
||||
"INSERT INTO event_tags VALUES(?1,?2,?3)",
|
||||
),
|
||||
TagTarget::Market => (
|
||||
"SELECT EXISTS(SELECT 1 FROM markets WHERE id=?)",
|
||||
"DELETE FROM market_tags WHERE market=?",
|
||||
"INSERT INTO market_tags VALUES(?1,?2,?3)",
|
||||
),
|
||||
};
|
||||
ensure!(
|
||||
tx.query_row(exists, [target], |r| r.get::<_, bool>(0))?,
|
||||
"tag target not found"
|
||||
);
|
||||
tx.execute(remove, [target])?;
|
||||
let mut stmt = tx.prepare_cached(insert)?;
|
||||
for (position, tag) in tags.iter().enumerate() {
|
||||
stmt.execute(params![target, tag, position as i64])?;
|
||||
}
|
||||
Ok(json!({"target":target,"tag_ids":tags}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct TagLink {
|
||||
id: i64,
|
||||
related_tag_id: i64,
|
||||
rank: i64,
|
||||
}
|
||||
|
||||
pub(crate) fn set_links(tx: &Transaction, tag: i64, links: &[TagLink]) -> Result<Value> {
|
||||
let exists: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM directory_tags WHERE id=?)",
|
||||
[tag],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(exists, "tag not found");
|
||||
tx.execute("DELETE FROM directory_tag_links WHERE tag=?", [tag])?;
|
||||
let mut stmt = tx.prepare_cached(
|
||||
"INSERT INTO directory_tag_links(id,tag,related_tag,rank) VALUES(?,?,?,?)",
|
||||
)?;
|
||||
for link in links {
|
||||
stmt.execute(params![link.id, tag, link.related_tag_id, link.rank])?;
|
||||
}
|
||||
Ok(json!({"tag_id":tag.to_string(),"links":links.len()}))
|
||||
}
|
||||
|
||||
pub(super) fn tag_scope(
|
||||
db: &Connection,
|
||||
tag: Option<i64>,
|
||||
related: bool,
|
||||
) -> rusqlite::Result<Option<String>> {
|
||||
let Some(tag) = tag else { return Ok(None) };
|
||||
if !related {
|
||||
return Ok(Some(json!([tag]).to_string()));
|
||||
}
|
||||
db.prepare_cached(
|
||||
"SELECT json_group_array(id) FROM (
|
||||
SELECT ?1 AS id UNION ALL SELECT related_tag FROM directory_tag_links WHERE tag=?1
|
||||
)",
|
||||
)?
|
||||
.query_row([tag], |r| r.get(0))
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct RelatedTagsQuery {
|
||||
omit_empty: Option<bool>,
|
||||
status: Option<String>,
|
||||
}
|
||||
|
||||
pub(super) fn parse_wire(raw: String) -> rusqlite::Result<Value> {
|
||||
serde_json::from_str(&raw).map_err(|err| {
|
||||
rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, Box::new(err))
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TagsQuery {
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
ascending: Option<bool>,
|
||||
order: Option<String>,
|
||||
is_carousel: Option<bool>,
|
||||
}
|
||||
|
||||
fn invalid() -> MarketDataError {
|
||||
MarketDataError::Invalid("Invalid tag query".into())
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn gamma_tags(&self, q: TagsQuery) -> Result<Vec<Value>, MarketDataError> {
|
||||
let limit = q.limit.unwrap_or(0);
|
||||
let offset = q.offset.unwrap_or(0);
|
||||
if limit < 0 || offset < 0 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let direction = if q.ascending == Some(true) {
|
||||
"ASC"
|
||||
} else {
|
||||
"DESC"
|
||||
};
|
||||
let mut cols = Vec::new();
|
||||
for field in q.order.as_deref().unwrap_or("updatedAt").split(',') {
|
||||
cols.push(match field.trim() {
|
||||
"id" => "id",
|
||||
"slug" => "slug",
|
||||
"label" => "label",
|
||||
"createdAt" => "created_at",
|
||||
"updatedAt" => "updated_at",
|
||||
_ => return Err(invalid()),
|
||||
});
|
||||
}
|
||||
if !cols.contains(&"id") {
|
||||
cols.push("id");
|
||||
}
|
||||
let order = cols
|
||||
.iter()
|
||||
.map(|col| format!("{col} {direction}"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let sql = format!(
|
||||
"SELECT wire FROM directory_tag_wire WHERE (?1 IS NULL OR is_carousel=?1)
|
||||
ORDER BY {order} LIMIT ?2 OFFSET ?3"
|
||||
);
|
||||
let mut stmt = self.db.prepare_cached(&sql)?;
|
||||
let limit = if limit == 0 { 50 } else { limit };
|
||||
let rows = stmt.query_map(params![q.is_carousel, limit, offset], |r| {
|
||||
parse_wire(r.get(0)?)
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn gamma_tag(&self, key: DirectoryKey<'_>) -> Result<Option<Value>, MarketDataError> {
|
||||
let (sql, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("SELECT wire FROM directory_tag_wire WHERE id=?", id),
|
||||
DirectoryKey::Slug(slug) => ("SELECT wire FROM directory_tag_wire WHERE slug=?", slug),
|
||||
};
|
||||
Ok(self
|
||||
.db
|
||||
.prepare_cached(sql)?
|
||||
.query_row([arg], |r| parse_wire(r.get(0)?))
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn gamma_related_tags(
|
||||
&self,
|
||||
key: DirectoryKey<'_>,
|
||||
expanded: bool,
|
||||
query: RelatedTagsQuery,
|
||||
) -> Result<Vec<Value>, MarketDataError> {
|
||||
let (field, arg): (_, &dyn ToSql) = match &key {
|
||||
DirectoryKey::Id(id) => ("id", id),
|
||||
DirectoryKey::Slug(slug) => ("slug", slug),
|
||||
};
|
||||
let status = match query.status.as_deref() {
|
||||
Some("closed") => Some(true),
|
||||
Some("all") => None,
|
||||
_ => Some(false),
|
||||
};
|
||||
let body = if expanded {
|
||||
"t.wire"
|
||||
} else {
|
||||
"json_object('id',CAST(l.id AS TEXT),'tagID',l.tag,'relatedTagID',l.related_tag,'rank',l.rank)"
|
||||
};
|
||||
let sql = format!(
|
||||
"WITH event_states AS NOT MATERIALIZED ({})
|
||||
SELECT {body} FROM directory_tag_links l
|
||||
JOIN directory_tag_wire t ON t.id=l.related_tag
|
||||
WHERE l.tag=(SELECT id FROM directory_tags WHERE {field}=?1)
|
||||
AND (NOT ?2 OR EXISTS(
|
||||
SELECT 1 FROM event_tags a JOIN event_states e ON e.id=a.event
|
||||
WHERE a.tag=l.related_tag AND (?3 IS NULL OR e.closed=?3)
|
||||
))
|
||||
ORDER BY l.rank,l.id",
|
||||
include_str!("gamma_events.sql"),
|
||||
);
|
||||
let mut stmt = self.db.prepare_cached(&sql)?;
|
||||
let rows = stmt.query_map(
|
||||
params![arg, query.omit_empty.unwrap_or(false), status],
|
||||
|r| parse_wire(r.get(0)?),
|
||||
)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
pub fn gamma_resource_tags(
|
||||
&self,
|
||||
resource: DirectoryResource,
|
||||
id: i64,
|
||||
) -> Result<Option<Value>, MarketDataError> {
|
||||
let sql = match resource {
|
||||
DirectoryResource::Events => "SELECT COALESCE(a.tags,'[]')
|
||||
FROM event_directory_ids e LEFT JOIN event_tag_arrays a ON a.event=e.event WHERE e.id=?",
|
||||
DirectoryResource::Markets => "SELECT COALESCE(a.tags,'[]')
|
||||
FROM market_directory_ids m LEFT JOIN augmented_outcomes o ON o.market=m.market
|
||||
LEFT JOIN market_tag_arrays a ON a.market=m.market
|
||||
WHERE m.id=? AND COALESCE(o.role,'')<>'placeholder'",
|
||||
};
|
||||
Ok(self
|
||||
.db
|
||||
.prepare_cached(sql)?
|
||||
.query_row([id], |r| parse_wire(r.get(0)?))
|
||||
.optional()?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS directory_tags (
|
||||
id INTEGER PRIMARY KEY CHECK(id>0),
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
label TEXT NOT NULL,
|
||||
force_show INTEGER,
|
||||
force_hide INTEGER,
|
||||
is_carousel INTEGER,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS event_tags (
|
||||
event TEXT NOT NULL REFERENCES event_directory_ids(event),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
position INTEGER NOT NULL,
|
||||
PRIMARY KEY(event,tag)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS market_tags (
|
||||
market TEXT NOT NULL REFERENCES markets(id),
|
||||
tag INTEGER NOT NULL REFERENCES directory_tags(id),
|
||||
position INTEGER NOT NULL,
|
||||
PRIMARY KEY(market,tag)
|
||||
);
|
||||
CREATE VIEW IF NOT EXISTS directory_tag_wire AS
|
||||
SELECT id,slug,label,is_carousel,created_at,updated_at,
|
||||
json_patch(
|
||||
json_object('id',CAST(id AS TEXT),'slug',slug,'label',label,
|
||||
'createdAt',created_at,'updatedAt',updated_at),
|
||||
json_object('forceShow',json(CASE force_show WHEN 0 THEN 'false' WHEN 1 THEN 'true' END),
|
||||
'forceHide',json(CASE force_hide WHEN 0 THEN 'false' WHEN 1 THEN 'true' END),
|
||||
'isCarousel',json(CASE is_carousel WHEN 0 THEN 'false' WHEN 1 THEN 'true' END))
|
||||
) AS wire
|
||||
FROM directory_tags;
|
||||
CREATE VIEW IF NOT EXISTS event_tag_arrays AS
|
||||
SELECT event, json_group_array(json(wire)) AS tags
|
||||
FROM (SELECT a.event,t.wire FROM event_tags a JOIN directory_tag_wire t ON t.id=a.tag
|
||||
ORDER BY a.event,a.position)
|
||||
GROUP BY event;
|
||||
CREATE VIEW IF NOT EXISTS market_tag_arrays AS
|
||||
SELECT market, json_group_array(json(wire)) AS tags
|
||||
FROM (SELECT a.market,t.wire FROM market_tags a JOIN directory_tag_wire t ON t.id=a.tag
|
||||
ORDER BY a.market,a.position)
|
||||
GROUP BY market;
|
||||
COMMIT;
|
||||
@@ -32,17 +32,16 @@ pub(crate) fn cash_micros(tx: &Transaction, account: &str, delta: i64) -> Result
|
||||
|
||||
pub(crate) fn balance(db: &Connection, account: &str) -> Result<Value> {
|
||||
crate::validation::identifier(account)?;
|
||||
let (cash, remainder, reserved, rfq_reserved): (i64, i64, i64, i64) = db.query_row(
|
||||
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'),
|
||||
(SELECT COALESCE(SUM(cash_micros),0) FROM combo_rfq_holds WHERE account=a.id)
|
||||
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)?, r.get(3)?)),
|
||||
|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) + i128::from(rfq_reserved);
|
||||
let reserved = i128::from(reserved);
|
||||
Ok(
|
||||
json!({"account":account, "available_micros":available, "reserved_micros":reserved,
|
||||
"total_cash_micros":available+reserved}),
|
||||
|
||||
+16
-19
@@ -4,14 +4,13 @@ mod activity;
|
||||
mod assets;
|
||||
mod augmented;
|
||||
mod catalog;
|
||||
mod combo;
|
||||
mod combo_rfq;
|
||||
mod depth_feed;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod fees;
|
||||
mod gamma_directory;
|
||||
mod gamma_list;
|
||||
mod gamma_tags;
|
||||
mod heartbeat;
|
||||
mod holders;
|
||||
mod twap;
|
||||
@@ -54,6 +53,7 @@ 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 gamma_tags::{RelatedTagsQuery, TagsQuery};
|
||||
pub use open_interest::InterestQuery;
|
||||
pub use portfolio::http::ValueQuery;
|
||||
pub use prices_history::http::HistoryQuery;
|
||||
@@ -100,6 +100,20 @@ impl Exchange {
|
||||
if !directory_ready {
|
||||
db.execute_batch(include_str!("event_directory_schema.sql"))?;
|
||||
}
|
||||
let tags_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='view' AND name='directory_tag_wire')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !tags_ready {
|
||||
db.execute_batch(include_str!("gamma_tags.sql"))?;
|
||||
}
|
||||
let tag_links_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='directory_tag_links')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !tag_links_ready {
|
||||
db.execute_batch(include_str!("gamma_tag_links.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),
|
||||
@@ -129,20 +143,6 @@ impl Exchange {
|
||||
if !history_ready {
|
||||
db.execute_batch(include_str!("prices_history/chart_schema.sql"))?;
|
||||
}
|
||||
let combo_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='combo_movements')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !combo_ready {
|
||||
db.execute_batch(include_str!("combo_schema.sql"))?;
|
||||
}
|
||||
let combo_rfq_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='combo_rfq_trades')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !combo_rfq_ready {
|
||||
db.execute_batch(include_str!("combo_rfq_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),
|
||||
@@ -242,9 +242,6 @@ impl Exchange {
|
||||
| "market_amounts"
|
||||
| "tick_history"
|
||||
| "catalog"
|
||||
| "combo"
|
||||
| "combo_rfq"
|
||||
| "combo_rfq_open"
|
||||
| "events"
|
||||
| "history"
|
||||
| "prices_history"
|
||||
|
||||
@@ -58,6 +58,15 @@ pub(crate) fn apply(
|
||||
}
|
||||
Command::TickSizeChange(change) => change.apply(tx, request_id),
|
||||
Command::Event(event) => event.save(tx),
|
||||
Command::UpsertTag(tag) => tag.save(tx),
|
||||
Command::SetTags {
|
||||
kind,
|
||||
target,
|
||||
tag_ids,
|
||||
} => crate::gamma_tags::assign(tx, kind, &target, tag_ids),
|
||||
Command::SetRelatedTags { tag_id, links } => {
|
||||
crate::gamma_tags::set_links(tx, tag_id, &links)
|
||||
}
|
||||
Command::RescheduleSports {
|
||||
event,
|
||||
previous_ms,
|
||||
@@ -114,20 +123,6 @@ pub(crate) fn apply(
|
||||
)?;
|
||||
Ok(json!({"phase":"preopen"}))
|
||||
}
|
||||
Command::PrepareCombo { legs } => crate::combo::prepare(tx, legs),
|
||||
Command::SplitCombo(amount) => amount.apply(tx, request_id, true),
|
||||
Command::MergeCombo(amount) => amount.apply(tx, request_id, false),
|
||||
Command::RedeemCombo(redemption) => redemption.apply(tx, request_id),
|
||||
Command::RequestComboQuote(request) => request.apply(tx, request_id),
|
||||
Command::QuoteCombo(quote) => quote.apply(tx, request_id),
|
||||
Command::AcceptComboQuote(accept) => accept.apply(tx),
|
||||
Command::RespondComboQuote(response) => response.apply(tx, request_id),
|
||||
Command::CancelComboQuote { rfq, quote, maker } => {
|
||||
crate::combo_rfq::cancel_quote(tx, &rfq, "e, &maker)
|
||||
}
|
||||
Command::CancelComboRfq { rfq, requester } => {
|
||||
crate::combo_rfq::cancel_request(tx, &rfq, &requester)
|
||||
}
|
||||
Command::DefineNegRisk {
|
||||
group,
|
||||
event,
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[test]
|
||||
fn combo_replays_canonical_definition_and_keeps_rounding_dust() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("combo.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let commands = include_str!("../../../docs/examples/combo-ledger.jsonl")
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str::<Value>(line).unwrap())
|
||||
.collect::<Vec<_>>();
|
||||
for command in &commands[..3] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let definition = db.execute(commands[3].clone()).unwrap();
|
||||
let combo = definition["combo"].as_str().unwrap();
|
||||
assert_eq!(commands[4]["combo"], combo);
|
||||
assert_eq!(definition["legs"][0]["market"], "combo-a");
|
||||
let same = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"reordered","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-b","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(same, definition);
|
||||
assert!(db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"contradiction","legs":[{"market":"combo-a","outcome":"YES"},
|
||||
{"market":"combo-a","outcome":"NO"}]
|
||||
}))
|
||||
.is_err());
|
||||
let split = db.execute(commands[4].clone()).unwrap();
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
assert!(!db.execute(view.clone()).unwrap()["redeemable"]
|
||||
.as_bool()
|
||||
.unwrap());
|
||||
assert!(db.execute(commands[10].clone()).is_err());
|
||||
|
||||
drop(db);
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(commands[4].clone()).unwrap(), split);
|
||||
assert_eq!(
|
||||
db.execute(view.clone()).unwrap()["balances_micros"],
|
||||
json!([1000003, 1000003])
|
||||
);
|
||||
for command in &commands[5..10] {
|
||||
db.execute(command.clone()).unwrap();
|
||||
}
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([250000, 750000]));
|
||||
assert_eq!(
|
||||
db.execute(commands[10].clone()).unwrap()["paid_micros"],
|
||||
250000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(commands[11].clone()).unwrap()["paid_micros"],
|
||||
750000
|
||||
);
|
||||
let final_state = db.execute(view).unwrap();
|
||||
assert_eq!(final_state["balances_micros"], json!([0, 0]));
|
||||
assert_eq!(final_state["collateral_micros"], 0);
|
||||
assert_eq!(final_state["rounding_dust_micros"], 1);
|
||||
assert_eq!(
|
||||
db.execute(json!({"op":"balance","account":"alice"}))
|
||||
.unwrap()["available_micros"],
|
||||
9999999
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_leg_allows_early_redemption_even_after_an_unresolved_leg() {
|
||||
let mut db = Exchange::open(":memory:").unwrap();
|
||||
for command in [
|
||||
json!({"op":"fund","id":"fund","account":"alice","cents":200}),
|
||||
json!({"op":"list","id":"a","market":"a-pending","rules":"pending"}),
|
||||
json!({"op":"list","id":"b","market":"b-loss","rules":"settle early"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let prepared = db
|
||||
.execute(json!({
|
||||
"op":"prepare_combo","id":"combo","legs":[{"market":"a-pending","outcome":"YES"},
|
||||
{"market":"b-loss","outcome":"NO"}]
|
||||
}))
|
||||
.unwrap();
|
||||
let combo = prepared["combo"].as_str().unwrap();
|
||||
for command in [
|
||||
json!({"op":"split_combo","id":"split","combo":combo,"account":"alice","qty":2}),
|
||||
json!({"op":"close","id":"close","market":"b-loss"}),
|
||||
json!({"op":"finalize","id":"final","market":"b-loss","winner":"YES"}),
|
||||
] {
|
||||
db.execute(command).unwrap();
|
||||
}
|
||||
let view = json!({"op":"combo","combo":combo,"account":"alice"});
|
||||
let settled = db.execute(view.clone()).unwrap();
|
||||
assert!(settled["legs"][0]["payout_micros_per_share"].is_null());
|
||||
assert_eq!(settled["payout_micros_per_share"], json!([0, 1000000]));
|
||||
let yes=db.execute(json!({"op":"redeem_combo","id":"yes","combo":combo,"account":"alice","qty":2,"outcome":"YES"})).unwrap();
|
||||
let no=db.execute(json!({"op":"redeem_combo","id":"no","combo":combo,"account":"alice","qty":2,"outcome":"NO"})).unwrap();
|
||||
assert_eq!(yes["paid_micros"], 0);
|
||||
assert_eq!(no["paid_micros"], 2000000);
|
||||
assert_eq!(db.execute(view).unwrap()["rounding_dust_micros"], 0);
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn commands() -> Vec<Value> {
|
||||
include_str!("../../../docs/examples/combo-rfq.jsonl")
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let mut cmd: Value = serde_json::from_str(line).unwrap();
|
||||
if cmd["op"] == "request_combo_quote" {
|
||||
cmd["submission_window_ms"] = json!(300000);
|
||||
cmd["acceptance_window_ms"] = json!(300000);
|
||||
cmd["last_look_ms"] = json!(300000);
|
||||
}
|
||||
cmd
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_reserves_then_mints_merges_and_transfers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..6] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[6].clone()).unwrap()["rfqs"][0]["rfq_id"],
|
||||
"rfq-buy"
|
||||
);
|
||||
db.execute(cmds[7].clone()).unwrap();
|
||||
assert_eq!(
|
||||
db.execute(cmds[8].clone()).unwrap()["status"],
|
||||
"AWAITING_MAKER_CONFIRMATION"
|
||||
);
|
||||
let cash = json!({"op":"balance","account":"taker"});
|
||||
let held = db.execute(cash.clone()).unwrap();
|
||||
assert_eq!(held["reserved_micros"], 1400000);
|
||||
assert_eq!(held["total_cash_micros"], 5000000);
|
||||
assert!(db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"wrong-maker","rfq":"rfq-buy",
|
||||
"quote":"rfq-mint-quote","maker":"taker","confirm":true})
|
||||
)
|
||||
.is_err());
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let mint = db.execute(cmds[9].clone()).unwrap();
|
||||
assert_eq!(mint["fill"]["flow"], "MINT");
|
||||
assert_eq!(db.execute(cmds[9].clone()).unwrap(), mint);
|
||||
assert_eq!(db.execute(cash.clone()).unwrap()["reserved_micros"], 0);
|
||||
for cmd in &cmds[11..14] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let held = db.execute(cmds[15].clone()).unwrap();
|
||||
assert_eq!(held["balances_micros"], json!([4000000, 0]));
|
||||
assert_eq!(held["available_micros"], json!([2500000, 0]));
|
||||
let merge = db.execute(cmds[14].clone()).unwrap();
|
||||
assert_eq!(merge["fill"]["flow"], "MERGE");
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
assert_eq!(
|
||||
db.execute(cash.clone()).unwrap()["available_micros"],
|
||||
4200000
|
||||
);
|
||||
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"transfer","combo":combo,"requester":"taker",
|
||||
"direction":"SELL","side":"YES","shares_micros":1000000}),
|
||||
json!({"op":"quote_combo","id":"transfer-quote","rfq":"transfer","maker":"maker",
|
||||
"source":"collateral","price_micros":500000,"shares_micros":1000000}),
|
||||
json!({"op":"accept_combo_quote","id":"transfer-accept","rfq":"transfer","requester":"taker","quote":"transfer-quote"}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let transfer = db
|
||||
.execute(
|
||||
json!({"op":"respond_combo_quote","id":"transfer-fill","rfq":"transfer",
|
||||
"quote":"transfer-quote","maker":"maker","confirm":true}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(transfer["fill"]["flow"], "TRANSFER");
|
||||
assert_eq!(db.execute(cash).unwrap()["available_micros"], 4700000);
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
2500000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn combo_rfq_recovers_locks_on_expiry_and_rejects_competing_acceptance() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("rfq-expiry.sqlite");
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
let cmds = commands();
|
||||
for cmd in &cmds[..9] {
|
||||
db.execute(cmd.clone()).unwrap();
|
||||
}
|
||||
let combo = cmds[5]["combo"].as_str().unwrap();
|
||||
for cmd in [
|
||||
json!({"op":"request_combo_quote","id":"second","combo":combo,"requester":"taker",
|
||||
"direction":"BUY","side":"NO","notional_micros":4000000}),
|
||||
json!({"op":"quote_combo","id":"second-quote","rfq":"second","maker":"maker",
|
||||
"source":"collateral","price_micros":800000,"shares_micros":5000000}),
|
||||
] {
|
||||
db.execute(cmd).unwrap();
|
||||
}
|
||||
let accept = json!({"op":"accept_combo_quote","id":"second-accept","rfq":"second","requester":"taker","quote":"second-quote"});
|
||||
assert!(db.execute(accept.clone()).is_err());
|
||||
let status = json!({"op":"combo_rfq","rfq":"second","account":"taker"});
|
||||
assert_eq!(
|
||||
db.execute(status.clone()).unwrap()["status"],
|
||||
"AWAITING_REQUESTER_ACCEPTANCE"
|
||||
);
|
||||
let conn = rusqlite::Connection::open(&path).unwrap();
|
||||
conn.execute("UPDATE combo_rfqs SET confirm_by=0 WHERE id='rfq-buy'", [])
|
||||
.unwrap();
|
||||
drop(conn);
|
||||
drop(db);
|
||||
|
||||
let mut db = Exchange::open(&path).unwrap();
|
||||
assert_eq!(db.execute(cmds[10].clone()).unwrap()["status"], "EXPIRED");
|
||||
assert!(db.execute(cmds[9].clone()).is_err());
|
||||
db.execute(accept).unwrap();
|
||||
let decline = db
|
||||
.execute(json!({"op":"respond_combo_quote","id":"decline",
|
||||
"rfq":"second","maker":"maker","quote":"second-quote","confirm":false}))
|
||||
.unwrap();
|
||||
assert_eq!(decline["status"], "FAILED");
|
||||
assert_eq!(decline["failure"], "MAKER_DECLINED");
|
||||
for account in ["taker", "maker"] {
|
||||
let cash = db
|
||||
.execute(json!({"op":"balance","account":account}))
|
||||
.unwrap();
|
||||
assert_eq!(cash["available_micros"], 5000000);
|
||||
assert_eq!(cash["reserved_micros"], 0);
|
||||
}
|
||||
assert_eq!(
|
||||
db.execute(cmds[15].clone()).unwrap()["collateral_micros"],
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
{"op":"fund","id":"combo-fund","account":"alice","micros":10000000}
|
||||
{"op":"list","id":"combo-list-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"combo-list-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"combo-prepare","legs":[{"market":"combo-b","outcome":"NO"},{"market":"combo-a","outcome":"YES"}]}
|
||||
{"op":"split_combo","id":"combo-split","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":1000003}
|
||||
{"op":"merge_combo","id":"combo-merge","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","qty_micros":2}
|
||||
{"op":"close","id":"combo-close-a","market":"combo-a"}
|
||||
{"op":"finalize","id":"combo-final-a","market":"combo-a","winner":"VOID"}
|
||||
{"op":"close","id":"combo-close-b","market":"combo-b"}
|
||||
{"op":"finalize","id":"combo-final-b","market":"combo-b","winner":"VOID"}
|
||||
{"op":"redeem_combo","id":"combo-redeem-yes","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"YES","qty_micros":1000001}
|
||||
{"op":"redeem_combo","id":"combo-redeem-no","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice","outcome":"NO","qty_micros":1000001}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"alice"}
|
||||
@@ -1,16 +0,0 @@
|
||||
{"op":"fund","id":"rfq-taker-fund","account":"taker","micros":5000000}
|
||||
{"op":"fund","id":"rfq-maker-fund","account":"maker","micros":5000000}
|
||||
{"op":"list","id":"rfq-a","market":"combo-a","rules":"按模拟赛果 A 裁决。"}
|
||||
{"op":"list","id":"rfq-b","market":"combo-b","rules":"按模拟赛果 B 裁决。"}
|
||||
{"op":"prepare_combo","id":"rfq-combo","legs":[{"market":"combo-a","outcome":"YES"},{"market":"combo-b","outcome":"NO"}]}
|
||||
{"op":"request_combo_quote","id":"rfq-buy","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"BUY","side":"YES","shares_micros":4000000}
|
||||
{"op":"combo_rfq_open"}
|
||||
{"op":"quote_combo","id":"rfq-mint-quote","rfq":"rfq-buy","maker":"maker","source":"collateral","price_micros":350000,"shares_micros":4000000}
|
||||
{"op":"accept_combo_quote","id":"rfq-buy-accept","rfq":"rfq-buy","requester":"taker","quote":"rfq-mint-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-buy-fill","rfq":"rfq-buy","quote":"rfq-mint-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo_rfq","rfq":"rfq-buy","account":"taker"}
|
||||
{"op":"request_combo_quote","id":"rfq-sell","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","requester":"taker","direction":"SELL","side":"YES","shares_micros":1500000}
|
||||
{"op":"quote_combo","id":"rfq-merge-quote","rfq":"rfq-sell","maker":"maker","source":"inventory","price_micros":400000,"shares_micros":1500000}
|
||||
{"op":"accept_combo_quote","id":"rfq-sell-accept","rfq":"rfq-sell","requester":"taker","quote":"rfq-merge-quote"}
|
||||
{"op":"respond_combo_quote","id":"rfq-sell-fill","rfq":"rfq-sell","quote":"rfq-merge-quote","maker":"maker","confirm":true}
|
||||
{"op":"combo","combo":"combo:1131b7195fad3ca3c7ae8ebe3739ac78a765c241aa74fccf91236b6caa08cb1e","account":"taker"}
|
||||
@@ -0,0 +1,13 @@
|
||||
{"op":"upsert_tag","id":"tag-tech","tag_id":101,"label":"Technology","slug":"technology","force_show":true}
|
||||
{"op":"upsert_tag","id":"tag-threshold","tag_id":102,"label":"Price thresholds","slug":"price-thresholds","is_carousel":false}
|
||||
{"op":"set_tags","id":"tag-nvda","kind":"event","target":"nvda-2027","tag_ids":[101,102]}
|
||||
{"op":"set_tags","id":"tag-nvda-market","kind":"market","target":"nvda-200","tag_ids":[102]}
|
||||
{"op":"upsert_tag","id":"tag-archives","tag_id":103,"label":"Archived technology","slug":"archived-technology"}
|
||||
{"op":"upsert_tag","id":"tag-depth","tag_id":104,"label":"Semi-conductors","slug":"semi-conductors"}
|
||||
{"op":"event","id":"create-tag-archive","event":"tag-archive","slug":"tag-archive","title":"Archive fixture","category":"technology"}
|
||||
{"op":"list","id":"create-archived-tech","market":"archived-tech","rules":"Archive fixture.","listing":{"event":"tag-archive","question":"Archive fixture?","yes_label":"YES","no_label":"NO","source":"fixture","resolver":"operator","rules_version":1,"group_order":1}}
|
||||
{"op":"close","id":"close-archived-tech","market":"archived-tech"}
|
||||
{"op":"set_tags","id":"tag-archive-event","kind":"event","target":"tag-archive","tag_ids":[103]}
|
||||
{"op":"set_tags","id":"tag-depth-market","kind":"market","target":"nvda-300","tag_ids":[104]}
|
||||
{"op":"set_related_tags","id":"tag-technology-links","tag_id":101,"links":[{"id":9002,"related_tag_id":102,"rank":2},{"id":9001,"related_tag_id":103,"rank":1}]}
|
||||
{"op":"set_related_tags","id":"tag-threshold-links","tag_id":102,"links":[{"id":9003,"related_tag_id":104,"rank":1}]}
|
||||
+12
-16
@@ -455,22 +455,6 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
|
||||
在同一数据库先重放[费用样例](examples/neg-risk-fee.jsonl),再重放[裁决后转换样例](examples/neg-risk-after-verdict.jsonl)。甲先判 NO,新增转换把准备金增至 500002 微美元。「其他」判 YES 后,用户和金库分别领取 493752 和 6250 微美元;赢家抵押归零。乙也判 NO 后,用户交回剩余的甲 NO 和乙 NO,各 250001 微份。转换当场向「其他」补入 250001 微美元抵押,用户和金库可再领取 246876 和 3125。每次领取使用独立的请求 ID。另一种情形中,如果输入包含赢家自己的 NO,这些份额的兑付价值已经为零,现存赢家 YES 的抵押须全额保留。
|
||||
|
||||
### 组合定义、抵押与兑付
|
||||
|
||||
官方 CombinatorialModule 以规范腿集合标识组合。重复腿、同一条件的相反结果和非二元腿受到限制。组合 YES 的兑付乘各腿权重,NO 用其补数。若已有零兑付腿,未裁决的其他腿不会阻止兑付。合约保留 36 位累积精度,YES 用向下系数,NO 用向上系数的补数,每次实际兑付按抵押币最小单位向下取整。[组合合约](https://github.com/Polymarket/polymarket-v2-external/blob/main/src/modules/CombinatorialModule.sol) · [官方日终估值规则](https://docs.polymarket.com/api-reference/wallet/snapshot-a-wallets-positions-at-the-end-of-a-day)
|
||||
|
||||
本地接受 2 至 50 条已经上架的二元腿。按市场 ID 排序后生成独立的本地组合 ID,两侧份额使用其各自的本地标识。拆分、合并和兑付与抵押账本及请求回执同事务写入,不改动底层市场的份额。组合账本在最后一笔份额烧毁后登记无法兑付的尾差。重放[组合样例](examples/combo-ledger.jsonl),分别选择 A 的 YES 和 B 的 NO。拆分 1000003 微份后合并 2 微份。两条腿都作废时,YES 每份为 0.25,NO 每份为 0.75,实际分别兑付 250000 与 750000 微美元,最后记录 1 微美元尾差。
|
||||
|
||||
本轮公开组合候选目录返回 HTTP 403。生产 RFQ 资格、报价和成交,链上标识以及组合持仓对账仍待接入和验证。[公开候选目录规范](https://docs.polymarket.com/api-reference/combo-markets/get-combo-markets)
|
||||
|
||||
### 组合 RFQ 的状态、预留与成交
|
||||
|
||||
官方请求与报价模型区分 BUY/SELL、YES/NO,以及份额或名义金额。询价有报价提交期限,接受选定报价后,系统向报价方发带 `confirm_by` 的最后确认消息。确认后线上另有执行状态。本地可信 JSONL 实现这一流程,以数据库时钟约束期限。提交、接受和最后确认窗口默认分别为 10、20 和 5 秒,可由模拟请求显式设定。接受报价后立即复核并冻结双方资金或份额。报价可供请求方选择,同价时优先较大数量,再按提交顺序。选择和预留不走公开盘口。[官方报价网关](https://docs.polymarket.com/api-reference/wss/rfq) · [最后确认](https://docs.polymarket.com/api-reference/maker/confirm-or-decline-last-look) · [请求方 SDK](https://github.com/Polymarket/ts-sdk/blob/main/packages/bindings/src/combos/builder-rfq.ts)
|
||||
|
||||
报价的微美元本金是数量乘微美元价格后向下取整。本地份额询价可接受不超请求数量的单个报价,名义金额用于限制 BUY 的预算。按方向与报价资金来源,结算可转让已持有份额、用双方资金拆分、或用互补库存合并。重放[样例](examples/combo-rfq.jsonl),双方分别出资 1.40 和 2.60 生成四对份额。再合并 1.5 对后,报价方和请求方分别收回 0.90 和 0.60,组合抵押剩 2.50。相同确认请求重放原成交。拒绝和到期释放全部预留,重启后检查已到期请求。
|
||||
|
||||
当前交付采用本地单报价选中、无手续费和同步结算。外场签名、报价聚合、费率、线上限额、联网做市商的报价投递和链上异步执行还有待接入。
|
||||
|
||||
### 互斥适配器按量赎回
|
||||
|
||||
当前 SDK 的 `redeem_positions(condition_id)` 选择该市场的协议路径,领取持有人两侧的余额。另一个公开入口是 NegRiskAdapter 的 `redeemPositions(conditionId, amounts)`,先将调用人指定的 YES 和 NO 转入适配器,再执行底层兑付。即使兑付额为零,适配器仍发出带有输入数量和兑付额的事件。以下样例验证该适配器的数量语义;生产协议版本、批量交易及链上回执尚待比对。[官方持仓接口](https://docs.polymarket.com/trading/positions/manage) · [适配器源码](https://github.com/Polymarket/neg-risk-ctf-adapter/blob/main/src/NegRiskAdapter.sol#L191-L207)
|
||||
@@ -487,3 +471,15 @@ SDK 使用 `GET /neg-risk?token_id=…`,也可以从已缓存的 CLOB 市场
|
||||
### 已裁决市场的公开盘口
|
||||
|
||||
对电竞、乒乓球和 SOL 涨跌盘的六个已裁决结果单查 /book,全部返回 404。批量 /books 和 /prices 忽略已裁决资产,混合批次保留可用资产。中点和价差多数同样返回 404,但一个 V2 市场的两侧分别仍能读到价差 1 或中点 0.5。Eventbook 对已裁决结果统一省略四种公开行情,保留内部快照供交易状态和回放。封盘待裁决阶段、外场淘汰时延和例外是否由服务缓存触发仍待验证。[生产响应](examples/public-resolved-books.json)
|
||||
|
||||
|
||||
### Gamma 标签及目录导航
|
||||
|
||||
生产样本中,事件 30828 和子盘 559651 的标签专用端点均返回五个标签,分别是 103715、100265、101970、366、102458,两个端点的顺序不同。`GET /tags/slug/geopolitics` 返回字符串 ID `100265`。事件详情内带标签。市场详情默认省略标签,市场列表使用 `include_tag=true` 时可展开。不存在的事件或市场在专用标签端点返回 404,不存在的事件筛选标签返回空数组。生产 `/tags?limit=0` 的样本返回默认的 50 项。[事件标签](https://gamma-api.polymarket.com/events/30828/tags) · [市场标签](https://gamma-api.polymarket.com/markets/559651/tags) · [标签列表规范](https://docs.polymarket.com/api-reference/tags/list-tags)
|
||||
|
||||
本地分别为事件和市场登记标签及显示顺序。先重放[主题样例](examples/topic.jsonl),再重放[标签样例](examples/gamma-tags.jsonl)。`GET /events?tag_id=101&tag_slug=price-thresholds` 返回 NVIDIA 主题,追加 `exclude_tag_id=102` 后返回空数组。`GET /markets?tag_id=102&include_tag=true` 仅返回 nvda-200 和它的标签。错误的标签编号使关联写入整体回滚。模板标签、生产默认排序与父子标签写入规则仍待验证。
|
||||
|
||||
|
||||
生产 Sports 的 ID 和 slug 入口返回同一组关系,第一项指向 450,查询 450 的反向入口返回空数组。Geopolitics 有 19 个相关标签,默认的 `omit_empty=true` 保留 17 个,`status=closed` 或 `status=all` 均保留 19 个。生产事件 10083 能通过 `tag_id=100265&related_tags=true` 找到,追加 `tag_slug=geopolitics` 后无结果。生产盘口 677218 没有 Sports 标签 1,但有直接相关标签 100639,并能通过 `tag_id=1&related_tags=true` 找到。[关系查询](https://docs.polymarket.com/api-reference/tags/get-related-tags-relationships-by-tag-id) · [相关标签详情](https://docs.polymarket.com/api-reference/tags/get-tags-related-to-a-tag-id)
|
||||
|
||||
本地 `set_related_tags` 在一个事务内替换指定标签的全部出边。`/related-tags` 返回关系和排名,加 `/tags` 返回标签详情。按 ID 或 slug 查询均可。空关联或不存在的根标签返回空数组。开启 `omit_empty` 后,默认只保留与开放赛事有关联的标签,再按 `status` 可改查已关闭或所有赛事。数字标签扩展只走直接关系,slug 与排除规则继续精确匹配。样例中 Technology 指向 Price thresholds,后者指向 Semi-conductors。按 Technology 扩展查市场只返回 nvda-200。更深层的生产关系、空标签的生产索引延迟和 keyset 列表仍待核对。
|
||||
|
||||
Reference in New Issue
Block a user