Mark outcome positions and report account holdings value
This commit is contained in:
@@ -7,7 +7,7 @@ version.workspace = true
|
||||
matching = { path = "../matching" }
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_json = { workspace = true, features = ["arbitrary_precision"] }
|
||||
rusqlite.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -32,6 +32,10 @@ flowchart LR
|
||||
queries -->|账户挂单与单笔状态| acct["src/account_orders.rs"]
|
||||
acct -->|校验账户和市场| valid
|
||||
queries -->|账户持仓| portfolio["src/portfolio.rs"]
|
||||
portfolio -->|获取每份持仓估值| marks["src/quotes.rs"]
|
||||
api -->|迁移末笔成交及持仓视图| markschema["src/valuation_schema.sql"]
|
||||
marks -->|读取资产末笔成交| markschema
|
||||
positions -->|查询可用及预留份额| markschema
|
||||
portfolio -->|查询参数与分页| positions["src/portfolio.sql"]
|
||||
portfolio -->|校验账户和市场| valid
|
||||
market -->|提案、争议与终裁检查| res["src/resolution.rs"]
|
||||
@@ -434,3 +438,25 @@ sequenceDiagram
|
||||
E-->>C: 统计时刻、总量及按累计吃单份额降序的成员
|
||||
end
|
||||
```
|
||||
|
||||
## 账户持仓估值
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as 客户端
|
||||
participant E as Exchange
|
||||
participant P as portfolio.rs
|
||||
participant D as SQLite
|
||||
C->>E: positions(account) 或 portfolio_value(account)
|
||||
E->>P: 在同一读快照查询
|
||||
P->>D: 取得可用份额、预留卖单及裁决状态
|
||||
loop 每个持仓
|
||||
alt 已裁决
|
||||
P->>P: 按该结果兑付率估值
|
||||
else 尚未裁决
|
||||
P->>D: 查最新盘口及该结果的末笔成交
|
||||
P->>P: 选取可用价格,保留缺价状态
|
||||
end
|
||||
end
|
||||
P-->>C: 逐项估值或全账户总值、已知小计及缺价持仓数
|
||||
```
|
||||
|
||||
@@ -248,6 +248,9 @@ pub(crate) enum Query {
|
||||
market: String,
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
PortfolioValue {
|
||||
account: String,
|
||||
},
|
||||
Activity(crate::activity::Filter),
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
Trades(crate::account_trades::Filter),
|
||||
@@ -293,6 +296,7 @@ impl Query {
|
||||
Self::Resolution { market } => crate::resolution::read(db, &market),
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Activity(filter) => filter.read(db),
|
||||
Self::PortfolioValue { account } => crate::portfolio::value(db, &account),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
@@ -320,22 +324,13 @@ impl Query {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
let quote = crate::quotes::Quote::current(db, &market, &outcome)?;
|
||||
let (bid, ask) = (quote.bid, quote.ask);
|
||||
// Fills also cover databases created before timestamped history was introduced.
|
||||
let last: Option<i64> = db.query_row(
|
||||
"SELECT (SELECT price FROM (
|
||||
SELECT f.seq, f.price FROM fills f JOIN orders o ON o.seq=f.bid WHERE o.market=?1 AND o.outcome=?2
|
||||
UNION ALL SELECT seq, CASE WHEN ?2='YES' THEN yes_price ELSE 100-yes_price END FROM paired_fills WHERE market=?1
|
||||
) ORDER BY seq DESC LIMIT 1)",
|
||||
params![market, outcome],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
let (display, source) = match (phase.as_str(), bid, ask, last) {
|
||||
("continuous", Some(b), Some(a), _) if (0..=10).contains(&(a - b)) => {
|
||||
(Some((a + b) * 5000), Some("midpoint"))
|
||||
}
|
||||
("continuous", _, _, Some(p)) => (Some(p * 10000), Some("last_trade")),
|
||||
_ => (None, None),
|
||||
};
|
||||
let last = quote.last;
|
||||
let (display, source) = if phase == "continuous" {
|
||||
quote.mark(&phase)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
.unzip();
|
||||
Ok(
|
||||
json!({"asset_id":assets::id(&market,&outcome),"market":market,"outcome":outcome,"phase":phase,
|
||||
"quote_seq":quote.seq,"best_bid_micros":bid.map(|p|p*10000),"best_ask_micros":ask.map(|p|p*10000),
|
||||
|
||||
@@ -53,6 +53,13 @@ impl Exchange {
|
||||
if !quotes_ready {
|
||||
db.execute_batch(include_str!("quote_schema.sql"))?;
|
||||
}
|
||||
let marks_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='last_asset_trades')",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
if !marks_ready {
|
||||
db.execute_batch(include_str!("valuation_schema.sql"))?;
|
||||
}
|
||||
let tx = expiry::transaction(&db, TransactionBehavior::Deferred)?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
@@ -75,6 +82,7 @@ impl Exchange {
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "portfolio_value"
|
||||
| "trades"
|
||||
| "activity"
|
||||
| "resolution"
|
||||
|
||||
@@ -55,12 +55,15 @@ impl Filter {
|
||||
let status: String = row.get(5)?;
|
||||
let payout: Option<i64> = row.get(6)?;
|
||||
let pairs: i64 = row.get(7)?;
|
||||
let phase: String = row.get(13)?;
|
||||
let (mark, source) = price(db, &market, &outcome, &phase, payout)?.unzip();
|
||||
positions.push(json!({
|
||||
"current_price_micros":mark,"price_source":source,"current_value_micros":holding_value(size,mark),
|
||||
"asset_id":crate::assets::id(&market,&outcome),"market":market, "outcome":outcome, "status":status, "size":size,
|
||||
"neg_risk_group":row.get::<_,Option<String>>(10)?,
|
||||
"augmented_role":row.get::<_,Option<String>>(11)?,"outcome_name":row.get::<_,Option<String>>(12)?,
|
||||
"available_size":row.get::<_,i64>(3)?, "reserved_size":row.get::<_,i64>(4)?,
|
||||
"redeemable":status=="REDEEMABLE", "payout_cents":payout.map(|p|p*size),
|
||||
"redeemable":status=="REDEEMABLE", "payout_cents":payout.map(|p|i128::from(p)*i128::from(size)),
|
||||
"mergeable":pairs>0, "available_pairs":row.get::<_,i64>(8)?
|
||||
}));
|
||||
last = Some((row.get::<_, i64>(9)?, market, outcome));
|
||||
@@ -68,3 +71,52 @@ impl Filter {
|
||||
Ok(json!({"positions":positions,"next_after":next_after}))
|
||||
}
|
||||
}
|
||||
|
||||
fn price(
|
||||
db: &Connection,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
phase: &str,
|
||||
payout: Option<i64>,
|
||||
) -> Result<Option<(i64, &'static str)>> {
|
||||
if let Some(p) = payout {
|
||||
return Ok(Some((p * 10000, "settlement")));
|
||||
}
|
||||
Ok(crate::quotes::Quote::current(db, market, outcome)?.mark(phase))
|
||||
}
|
||||
|
||||
fn holding_value(size: i64, mark: Option<i64>) -> Option<i128> {
|
||||
if size == 0 {
|
||||
return Some(0);
|
||||
}
|
||||
mark.map(|p| i128::from(p) * i128::from(size))
|
||||
}
|
||||
|
||||
pub(crate) fn value(db: &Connection, account: &str) -> Result<Value> {
|
||||
identifier(account)?;
|
||||
let mut stmt = db.prepare(
|
||||
"SELECT market,outcome,available+reserved AS size,phase,payout_per_share
|
||||
FROM position_sizes WHERE account=? AND available+reserved>0",
|
||||
)?;
|
||||
let mut rows = stmt.query([account])?;
|
||||
let mut priced = 0i128;
|
||||
let mut missing = 0u64;
|
||||
while let Some(row) = rows.next()? {
|
||||
let market: String = row.get(0)?;
|
||||
let outcome: String = row.get(1)?;
|
||||
let phase: String = row.get(3)?;
|
||||
let mark = price(db, &market, &outcome, &phase, row.get(4)?)?.map(|(p, _)| p);
|
||||
match holding_value(row.get(2)?, mark) {
|
||||
Some(amount) => {
|
||||
priced = priced
|
||||
.checked_add(amount)
|
||||
.ok_or_else(|| anyhow::anyhow!("portfolio value overflow"))?
|
||||
}
|
||||
None => missing += 1,
|
||||
}
|
||||
}
|
||||
Ok(
|
||||
json!({"account":account,"value_micros":(missing==0).then_some(priced),
|
||||
"priced_value_micros":priced,"unpriced_positions":missing}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
WITH reserved AS (
|
||||
SELECT market,outcome,SUM(remaining) AS qty
|
||||
FROM orders
|
||||
WHERE account=?1 AND status='live' AND side='sell' AND (?2 IS NULL OR market=?2)
|
||||
GROUP BY market,outcome
|
||||
), balances AS (
|
||||
SELECT p.market,p.outcome,p.quantity AS available,COALESCE(r.qty,0) AS reserved,
|
||||
p.quantity+COALESCE(r.qty,0) AS size
|
||||
FROM positions p LEFT JOIN reserved r USING (market,outcome)
|
||||
WHERE p.account=?1 AND (?2 IS NULL OR p.market=?2)
|
||||
WITH balances AS (
|
||||
SELECT market,outcome,available,reserved,available+reserved AS size,phase,payout_per_share
|
||||
FROM position_sizes WHERE account=?1 AND (?2 IS NULL OR market=?2)
|
||||
), holdings AS (
|
||||
SELECT b.*,m.phase,
|
||||
CASE WHEN m.phase='resolved' THEN
|
||||
CASE WHEN m.winner='VOID' THEN 50 WHEN b.outcome=m.winner THEN 100 ELSE 0 END
|
||||
END AS payout_per_share,
|
||||
CASE WHEN m.phase<>'resolved' THEN MIN(b.size,COALESCE(other.size,0)) ELSE 0 END AS pairs,
|
||||
CASE WHEN m.phase<>'resolved' THEN MIN(b.available,COALESCE(other.available,0)) ELSE 0 END AS free_pairs
|
||||
FROM balances b JOIN markets m ON m.id=b.market
|
||||
SELECT b.*,
|
||||
CASE WHEN b.phase<>'resolved' THEN MIN(b.size,COALESCE(other.size,0)) ELSE 0 END AS pairs,
|
||||
CASE WHEN b.phase<>'resolved' THEN MIN(b.available,COALESCE(other.available,0)) ELSE 0 END AS free_pairs
|
||||
FROM balances b
|
||||
LEFT JOIN balances other ON other.market=b.market AND other.outcome<>b.outcome
|
||||
), filtered AS (
|
||||
SELECT *,CASE WHEN size=0 THEN 'CLOSED' WHEN phase='resolved' THEN 'REDEEMABLE' ELSE 'OPEN' END AS row_status,
|
||||
@@ -30,7 +20,7 @@ WITH reserved AS (
|
||||
WHEN 'MERGEABLE' THEN pairs>0
|
||||
END
|
||||
)
|
||||
SELECT market,outcome,size,available,reserved,row_status,payout_per_share,pairs,free_pairs,sort_key,n.group_id,a.role,a.name
|
||||
SELECT market,outcome,size,available,reserved,row_status,payout_per_share,pairs,free_pairs,sort_key,n.group_id,a.role,a.name,phase
|
||||
FROM filtered LEFT JOIN neg_risk_members n USING(market) LEFT JOIN augmented_outcomes a USING(market)
|
||||
WHERE ?4 IS NULL OR (sort_key,market,outcome)>(?4,?5,?6)
|
||||
ORDER BY sort_key,market,outcome LIMIT ?7
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection, OptionalExtension, Row, Transaction};
|
||||
use rusqlite::{params, Connection, Row, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
@@ -18,6 +18,7 @@ pub(crate) struct Quote {
|
||||
pub bid: Option<i64>,
|
||||
pub ask: Option<i64>,
|
||||
at_ms: Option<i64>,
|
||||
pub last: Option<i64>,
|
||||
}
|
||||
impl Quote {
|
||||
fn read(row: &Row, outcome: &str) -> rusqlite::Result<Self> {
|
||||
@@ -33,12 +34,36 @@ impl Quote {
|
||||
bid,
|
||||
ask,
|
||||
at_ms: row.get(3)?,
|
||||
last: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn current(db: &Connection, market: &str, outcome: &str) -> Result<Self> {
|
||||
Ok(db.query_row("SELECT seq,yes_bid,yes_ask,at_ms FROM quote_events WHERE market=? ORDER BY seq DESC LIMIT 1",
|
||||
[market],|r|Self::read(r,outcome)).optional()?.unwrap_or_default())
|
||||
let mut stmt = db.prepare_cached(
|
||||
"SELECT COALESCE(q.seq,0),q.yes_bid,q.yes_ask,q.at_ms,t.price
|
||||
FROM (SELECT ?1 AS market) s LEFT JOIN quote_events q ON q.seq=(
|
||||
SELECT MAX(seq) FROM quote_events WHERE market=s.market)
|
||||
LEFT JOIN last_asset_trades t ON t.market=s.market AND t.outcome=?2",
|
||||
)?;
|
||||
Ok(stmt.query_row(params![market, outcome], |r| {
|
||||
let mut quote = Self::read(r, outcome)?;
|
||||
quote.last = r.get(4)?;
|
||||
Ok(quote)
|
||||
})?)
|
||||
}
|
||||
|
||||
pub fn mark(&self, phase: &str) -> Option<(i64, &'static str)> {
|
||||
if phase == "continuous" {
|
||||
if let (Some(b), Some(a)) = (self.bid, self.ask) {
|
||||
if (0..=10).contains(&(a - b)) {
|
||||
return Some(((a + b) * 5000, "midpoint"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if matches!(phase, "continuous" | "closed") {
|
||||
return self.last.map(|p| (p * 10000, "last_trade"));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn event(&self) -> Value {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
BEGIN IMMEDIATE;
|
||||
CREATE TABLE IF NOT EXISTS last_asset_trades (
|
||||
market TEXT NOT NULL REFERENCES markets, outcome TEXT NOT NULL,
|
||||
execution INTEGER NOT NULL, price INTEGER NOT NULL, PRIMARY KEY(market,outcome)
|
||||
);
|
||||
|
||||
-- One row per priced asset, including legacy fills with no timestamp.
|
||||
-- Execution numbers are unique across the two journals.
|
||||
WITH legs(market,outcome,execution,price) AS (
|
||||
SELECT o.market,o.outcome,f.seq,f.price FROM fills f JOIN orders o ON o.seq=f.bid
|
||||
UNION ALL SELECT market,'YES',seq,yes_price FROM paired_fills
|
||||
UNION ALL SELECT market,'NO',seq,100-yes_price FROM paired_fills
|
||||
)
|
||||
INSERT INTO last_asset_trades(market,outcome,execution,price)
|
||||
SELECT market,outcome,MAX(execution),price FROM legs GROUP BY market,outcome
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
|
||||
CREATE TRIGGER IF NOT EXISTS last_asset_direct AFTER INSERT ON fills BEGIN
|
||||
INSERT INTO last_asset_trades
|
||||
SELECT market,outcome,NEW.seq,NEW.price FROM orders WHERE seq=NEW.bid
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS last_asset_paired AFTER INSERT ON paired_fills BEGIN
|
||||
INSERT INTO last_asset_trades VALUES
|
||||
(NEW.market,'YES',NEW.seq,NEW.yes_price),(NEW.market,'NO',NEW.seq,100-NEW.yes_price)
|
||||
ON CONFLICT(market,outcome) DO UPDATE SET execution=excluded.execution,price=excluded.price
|
||||
WHERE excluded.execution>last_asset_trades.execution;
|
||||
END;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS reserved_position_orders ON orders(account,market,outcome)
|
||||
WHERE status='live' AND side='sell';
|
||||
CREATE VIEW IF NOT EXISTS position_sizes AS
|
||||
SELECT p.account,p.market,p.outcome,p.quantity AS available,
|
||||
COALESCE((SELECT SUM(o.remaining) FROM orders o WHERE o.account=p.account AND o.market=p.market
|
||||
AND o.outcome=p.outcome AND o.status='live' AND o.side='sell'),0) AS reserved,
|
||||
m.phase,CASE WHEN m.phase='resolved' THEN
|
||||
CASE WHEN m.winner='VOID' THEN 50 WHEN p.outcome=m.winner THEN 100 ELSE 0 END
|
||||
END AS payout_per_share
|
||||
FROM positions p JOIN markets m ON m.id=p.market;
|
||||
COMMIT;
|
||||
@@ -1674,3 +1674,40 @@ fn catalog_and_ranked_volume_count_executions_once_across_conditions() {
|
||||
assert_eq!(listing["volume"], condition["volume"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valuation_counts_reserved_shares_and_distinguishes_unpriced_from_zero() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("valuation.db");
|
||||
let mut e = Exchange::open(&path).unwrap();
|
||||
let mut snapshots = Vec::new();
|
||||
for line in include_str!("../../../docs/examples/valuation.jsonl").lines() {
|
||||
let cmd: Value = serde_json::from_str(line).unwrap();
|
||||
let response = e.execute(cmd.clone()).unwrap();
|
||||
match cmd["op"].as_str().unwrap() {
|
||||
"portfolio_value" => snapshots.push(response),
|
||||
"positions" => {
|
||||
let yes = response["positions"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|p| p["outcome"] == "YES")
|
||||
.unwrap();
|
||||
assert_eq!(yes["reserved_size"], 8);
|
||||
assert_eq!(yes["current_price_micros"], 565000);
|
||||
assert_eq!(yes["price_source"], "midpoint");
|
||||
assert_eq!(yes["current_value_micros"], 4520000);
|
||||
drop(e);
|
||||
e = Exchange::open(&path).unwrap();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(snapshots.len(), 4);
|
||||
assert!(snapshots[0]["value_micros"].is_null());
|
||||
assert_eq!(snapshots[0]["unpriced_positions"], 1);
|
||||
assert_eq!(snapshots[0]["priced_value_micros"], 4800000);
|
||||
assert_eq!(snapshots[1]["value_micros"], 8870000);
|
||||
assert_eq!(snapshots[2]["value_micros"], 8000000);
|
||||
assert_eq!(snapshots[3]["value_micros"], 0);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user