Enforce FOK, FAK and post-only constraints before applying fills

This commit is contained in:
2026-12-03 03:45:40 +08:00
parent d6eef2f07f
commit 4eb80fa458
6 changed files with 107 additions and 18 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ ORDERS
## 执行规则
- 交易品由永久的市场 ID 与结果 YES 或 NO 共同标识。规则随市场上市保存。操作员用 open、close 和 resolve 显式推进交易阶段,VOID 对两个结果各兑付 50 分。
- 盘前接收和撤销 GTC 限价单。开盘在 0 至 100 的整数价位中依次选最大成交量、最小供需差和最低价。同侧按价格和受理序号分配。连续交易以较早的挂单价成交,支持持续有效的 GTC 和带保护价的 IOC。
- 盘前接收和撤销 GTC 限价单。开盘在 0 至 100 的整数价位中依次选最大成交量、最小供需差和最低价。同侧按价格和受理序号分配。连续交易以较早的挂单价成交,支持持续有效的 GTC、带限价保护的 IOC / FAK,以及要求全量即时成交的 FOK。连续交易的 GTC 可指定 post_only,提交时若会吃单则整笔拒绝。
- 撤单提供订单受理时返回的整数 order 字段及账户。已撤销订单的 remaining 记录撤销时的余量,只有 live 订单仍有冻结。账户 cash 和持仓 quantity 均表示可用量。
- 写请求携带全局唯一的字符串 id,重试时返回初次回执。内容冲突或余额不足时回滚。state 读取所有账户与订单的一致快照,只供本地调试。
- 首版允许模拟账户自行拆分全额抵押的成套份额。分片主备、跨簿互补撮合、自动裁决、外部执行、链上、篮子发行、Web 和 Bot 属于后续阶段。账户身份由可信调用方指定,程序没有网络监听或真实资产入口。
+34 -12
View File
@@ -1,4 +1,4 @@
use crate::resident::Books;
use crate::{command::TimeInForce, resident::Books};
use crate::{
ledger,
validation::{amount, identifier, phase},
@@ -15,7 +15,8 @@ pub(crate) struct NewOrder {
pub side: String,
pub price: i64,
pub qty: i64,
pub tif: String,
pub tif: TimeInForce,
pub post_only: bool,
}
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<Value> {
@@ -27,6 +28,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
price,
qty,
tif,
post_only,
} = order;
identifier(&account)?;
amount(qty)?;
@@ -37,9 +39,13 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
);
ensure!((0..=100).contains(&price), "invalid price");
ensure!(
tif == "GTC" || (tif == "IOC" && stage == "continuous"),
tif == TimeInForce::Gtc || stage == "continuous",
"unsupported time in force"
);
ensure!(
!post_only || (stage == "continuous" && tif == TimeInForce::Gtc),
"post-only requires continuous GTC"
);
if side == "buy" {
ledger::cash(tx, &account, -price * qty)?;
} else {
@@ -48,22 +54,38 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
tx.execute("INSERT INTO orders(account,market,outcome,side,price,quantity,remaining,status) VALUES(?,?,?,?,?,?,?,'live')",params![account,market,outcome,side,price,qty,qty])?;
let seq = tx.last_insert_rowid();
if stage == "continuous" {
if let Some(book) = books.get(&market, &outcome) {
let incoming = Order {
seq,
side: if side == "buy" { Side::Buy } else { Side::Sell },
price,
remaining: qty,
};
settle(tx, &market, &outcome, book.match_incoming(&incoming))?;
let incoming = Order {
seq,
side: if side == "buy" { Side::Buy } else { Side::Sell },
price,
remaining: qty,
};
let fills = books
.get(&market, &outcome)
.map(|book| book.match_incoming(&incoming))
.unwrap_or_default();
ensure!(
!post_only || fills.is_empty(),
"post-only order would take liquidity"
);
if tif == TimeInForce::Fok {
ensure!(
fills.iter().map(|fill| fill.quantity).sum::<i64>() == qty,
"FOK cannot fill the entire order"
);
}
ensure!(
tif != TimeInForce::Fak || !fills.is_empty(),
"FAK has no matching liquidity"
);
settle(tx, &market, &outcome, fills)?;
}
let (remaining, mut status): (i64, String) = tx.query_row(
"SELECT remaining,status FROM orders WHERE seq=?",
[seq],
|r| Ok((r.get(0)?, r.get(1)?)),
)?;
if tif == "IOC" && remaining > 0 {
if matches!(tif, TimeInForce::Ioc | TimeInForce::Fak) && remaining > 0 {
release(tx, seq, &account)?;
status = "cancelled".into();
}
+12 -4
View File
@@ -39,8 +39,10 @@ pub(crate) enum Command {
side: String,
price: i64,
qty: i64,
#[serde(default = "gtc")]
tif: String,
#[serde(default)]
tif: TimeInForce,
#[serde(default)]
post_only: bool,
},
Cancel {
account: String,
@@ -65,6 +67,12 @@ pub(crate) enum Command {
winner: String,
},
}
fn gtc() -> String {
"GTC".into()
#[derive(Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub(crate) enum TimeInForce {
#[default]
Gtc,
Ioc,
Fak,
Fok,
}
+2
View File
@@ -111,6 +111,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
price,
qty,
tif,
post_only,
} => book::submit(
tx,
books,
@@ -122,6 +123,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
price,
qty,
tif,
post_only,
},
),
Command::Cancel { order, account } => {
+53
View File
@@ -366,3 +366,56 @@ fn explicit_redemption_is_account_scoped_and_restart_safe() {
.all(|p| p["quantity"] == 0));
}
}
#[test]
fn immediate_and_post_only_orders_use_the_committed_depth() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
for (id, price) in [("low", 40), ("high", 41)] {
let mut maker = order(id, "alice", "sell", price, 2);
maker["post_only"] = json!(true);
assert_eq!(e.execute(maker).unwrap()["status"], "live");
}
let before = state(&mut e);
for (id, tif, post, price, qty) in [
("short", "FOK", false, 40, 3),
("cross", "GTC", true, 40, 1),
("wrong-combination", "FAK", true, 40, 1),
("no-fill", "FAK", false, 39, 1),
] {
let mut req = order(id, "bob", "buy", price, qty);
req["post_only"] = json!(post);
req["tif"] = json!(tif);
assert!(e.execute(req).is_err());
assert_eq!(state(&mut e), before);
}
let mut full = order("full", "bob", "buy", 41, 3);
full["tif"] = json!("FOK");
let reply = e.execute(full.clone()).unwrap();
assert_eq!(reply["status"], "filled");
assert_eq!(reply["filled"], 3);
assert_eq!(e.execute(full).unwrap(), reply);
let mut partial = order("partial", "bob", "buy", 41, 3);
partial["tif"] = json!("FAK");
let reply = e.execute(partial).unwrap();
assert_eq!(reply["status"], "cancelled");
assert_eq!(reply["filled"], 1);
let s = state(&mut e);
assert_eq!(s["fills"].as_array().unwrap().len(), 3);
assert_eq!(s["accounts"][1]["cash"], 1838);
}
#[test]
fn rejected_sell_fok_releases_inventory() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let before = state(&mut e);
let mut sell = order("sell", "alice", "sell", 60, 5);
sell["tif"] = json!("FOK");
assert!(e.execute(sell).is_err());
assert_eq!(state(&mut e), before);
}
+5 -1
View File
@@ -6,7 +6,7 @@
|---|---|---|
| 事件、市场和结果 | 体育事件下有多个二元合约、规则和结果标签 | 稳定的结果资产标识、非体育事件、多结果组合和版本映射 |
| 报价与走势 | 本地成交曲线、连续交易展示价 | 盘口深度、细分报价单位、互补结果深度、实际历史样本 |
| 委托与成交 | 单簿价格时间优先、GTC、IOC | GTD、FOK、post-only、互补单及延迟和失败回报 |
| 委托与成交 | 单簿价格时间优先、GTC、IOC、FAK、FOK、GTC post-only | GTD、按金额买入、互补单及场所延迟和失败回报 |
| 持仓与抵押 | 模拟资产拆分、成套合并、裁决后按账户主动赎回 | 链上赎回回执、费用与多结果转换 |
| 裁决与交割 | 本地人工封盘、裁决、兑付 | 提案、争议、最终性,以及撮合后链上交割的独立状态 |
| 客户端 | CLI 查询规则、价格曲线与报价 | 用户可见的活动、挂单、持仓及断线回补的完整流程 |
@@ -26,3 +26,7 @@
市场关闭后,操作员提交 `{"op":"finalize","id":"result-1","market":"e","winner":"YES"}`。这一步锁定判定结果与兑付权利,持仓、抵押和现金保持原值。账户随后提交 `{"op":"redeem","id":"claim-1","market":"e","account":"alice"}`,一次核销本账户在该市场的全部结果份额。胜方每份兑付 100 分,败方 0 分,本地 VOID 对应两侧各 50 分。剩余抵押继续保留给其他持有人。既有 resolve 命令仍可在关闭的市场一次完成最终裁决和全体账户兑付。
[官方裁决说明](https://docs.polymarket.com/concepts/resolution.md)与[份额生命周期](https://docs.polymarket.com/concepts/positions-tokens.md)分别描述结果确定和持有人赎回。此处模拟的是二元合约的经济结果;现实中的提案挑战期、链上支付与确认另行验证。
## 即时成交和只挂单
连续交易的 order 可带 `"tif":"FOK"`、`"tif":"FAK"` 或 `"tif":"GTC","post_only":true`。本地数量单位为份。买一限价 41 分、要求 3 份时,若卖盘为 40 分两份、41 分两份,FOK 一次成交三份;若限价收紧到 40 分则整笔拒绝,卖方挂单仍在。FAK 可部分成交,未成交余量立即释放;零成交返回错误。IOC 保留模拟盘已有的零成交撤销回执。只挂单在连续交易下遇到可成交对手即拒绝;非交叉时保留原价位和受理顺序。拒单通过同一写事务回滚资金、库存和订单,成交回报按已提交成交统计。此处覆盖订单经济语义;签名、响应错误码和真实场所执行延迟另作核对。[官方订单生命周期](https://docs.polymarket.com/concepts/order-lifecycle.md) · [官方集成示例的 FAK 零成交处理](https://github.com/Polymarket/safe-wallet-integration/blob/main/README.md)