Track per-outcome activity clocks in public positions

This commit is contained in:
2026-12-05 04:51:33 +08:00
parent 7e6b94aeed
commit 8b4e2c4fa3
9 changed files with 135 additions and 17 deletions
+13
View File
@@ -479,6 +479,19 @@ fn redeem(
request_id: &str,
amounts: Option<[i64; 2]>,
) -> Result<i64> {
tx.execute(
"INSERT INTO position_redemption_times(account,market,outcome,at_ms)
SELECT account,market,outcome,CAST(unixepoch('subsec')*1000 AS INTEGER)
FROM position_units WHERE account=?1 AND market=?2 AND available>0
AND (?3 IS NULL OR CASE outcome WHEN 'YES' THEN ?3 ELSE ?4 END>0)
ON CONFLICT(account,market,outcome) DO UPDATE SET at_ms=excluded.at_ms",
params![
account,
market,
amounts.map(|a| a[0]),
amounts.map(|a| a[1])
],
)?;
let (shares, paid) = match amounts {
Some(amounts) => crate::neg_risk::burn_for_redemption(tx, market, account, amounts)?,
None => burn_full_balance(tx, market, account)?,
+38 -14
View File
@@ -32,6 +32,8 @@ pub struct PositionQuery {
sort_direction: Option<String>,
#[serde(alias = "includeArchived")]
include_archived: Option<bool>,
start: Option<i64>,
end: Option<i64>,
limit: Option<u32>,
cursor: Option<String>,
}
@@ -183,6 +185,12 @@ impl Exchange {
}
}
let start = query.start.filter(|n| *n > 0);
let end = query.end.filter(|n| *n > 0);
if matches!((start, end), (Some(a), Some(b)) if b < a) {
return Err(invalid("end must not be before start"));
}
let cursor = query
.cursor
.as_deref()
@@ -220,8 +228,10 @@ impl Exchange {
.sort_direction
.or_else(|| prior.map(|s| s.direction.clone()))
.unwrap_or_else(|| "DESC".into());
if !matches!(sort.as_str(), "CURRENT_VALUE" | "PRICE" | "TOKENS")
|| !matches!(direction.as_str(), "ASC" | "DESC")
if !matches!(
sort.as_str(),
"CURRENT_VALUE" | "PRICE" | "TOKENS" | "TIMESTAMP"
) || !matches!(direction.as_str(), "ASC" | "DESC")
{
return Err(invalid("invalid or unsupported position sort"));
}
@@ -254,7 +264,9 @@ impl Exchange {
selection.archived,
events,
title,
shares_floor
shares_floor,
start,
end
])?;
while let Some(row) = rows.next()? {
let account: String = row.get(0)?;
@@ -270,19 +282,30 @@ impl Exchange {
if cash && floor > 0 && value.is_none_or(|v| v < i128::from(floor)) {
continue;
}
let last_event_at: Option<i64> = row.get(13)?;
let first_entry_at: Option<i64> = row.get(14)?;
let rank = match selection.sort.as_str() {
"TOKENS" => size,
"PRICE" => mark.unwrap_or(0),
_ => value
.unwrap_or(0)
.try_into()
.map_err(|_| MarketDataError::Unavailable)?,
};
let rank = if selection.direction == "DESC" {
-rank
} else {
rank
"TIMESTAMP" => last_event_at,
"TOKENS" => Some(size),
"PRICE" => Some(mark.unwrap_or(0)),
_ => Some(
value
.unwrap_or(0)
.try_into()
.map_err(|_| MarketDataError::Unavailable)?,
),
};
let rank =
rank.map_or(
i64::MAX,
|n| {
if selection.direction == "DESC" {
-n
} else {
n
}
},
);
let losing = selection.status == "REDEEMABLE" && payout == Some(0);
let key = (
losing,
@@ -308,6 +331,7 @@ impl Exchange {
"proxy_wallet": account, "condition_id": market,
"token_id": assets::id(&market,&outcome), "opposite_token_id": assets::id(&market,opposite),
"current_size": decimal(size.into(),UNIT),
"last_event_at":last_event_at, "first_entry_at":first_entry_at,
"current_price": mark.map(|p| decimal(p.into(),UNIT)),
"current_value": value.map(|v| decimal(v,UNIT)),
"status": status, "redeemable": redeemable, "mergeable": row.get::<_, bool>(7)?,
+37 -1
View File
@@ -8,7 +8,7 @@ WITH held AS (
SELECT l.market FROM listed_markets l JOIN event_directory_ids e ON e.event=l.event
WHERE e.id IN (SELECT value FROM json_each(?6))
))
)
), selected AS (
SELECT p.account,p.market,p.outcome,p.size,p.phase,p.payout_per_share,p.archived,
p.phase<>'resolved' AND p.size>=100000 AND COALESCE(other.size,0)>=100000 AS mergeable,
w.question,w.slug,w.yes_label,w.no_label,n.market IS NOT NULL AS negative_risk
@@ -25,3 +25,39 @@ WHERE (?7 IS NULL OR w.question LIKE ?7) AND CASE ?4
WHEN 'MERGEABLE' THEN mergeable
END
END
), observations AS (
SELECT s.account,s.market,s.outcome,t.at_ms,t.side='buy' AS entry
FROM selected s JOIN wallet_trade_legs t
ON t.account=s.account AND t.market=s.market AND t.outcome=s.outcome
UNION ALL
SELECT s.account,s.market,s.outcome,w.at_ms,w.kind='SPLIT'
FROM selected s JOIN wallet_movements w ON w.account=s.account AND w.market=s.market
WHERE w.kind IN ('SPLIT','MERGE')
UNION ALL
SELECT s.account,s.market,s.outcome,w.at_ms,0
FROM selected s
JOIN wallet_movements w ON w.account=s.account AND w.market=s.market AND w.kind='REDEEM'
JOIN requests r ON r.id=w.request_id
WHERE json_extract(r.response,CASE s.outcome WHEN 'YES' THEN '$.amounts_micros[0]' ELSE '$.amounts_micros[1]' END)>0
UNION ALL
SELECT s.account,s.market,s.outcome,w.at_ms,s.outcome='YES'
FROM selected s
JOIN neg_risk_members n ON n.market=s.market
JOIN wallet_movements w ON w.account=s.account AND w.group_id=n.group_id AND w.kind='CONVERSION'
JOIN requests r ON r.id=w.request_id
WHERE s.market IN (
SELECT value FROM json_each(r.response,CASE s.outcome WHEN 'YES' THEN '$.yes_markets' ELSE '$.no_markets' END)
)
AND (s.outcome='NO' OR COALESCE(json_extract(r.response,'$.conversion_fee.bps'),0)<10000)
UNION ALL
SELECT s.account,s.market,s.outcome,r.at_ms,0
FROM selected s JOIN position_redemption_times r USING(account,market,outcome)
), clocks AS (
SELECT account,market,outcome,MAX(at_ms)/1000 AS last_event_at,
MIN(CASE WHEN entry THEN at_ms END)/1000 AS first_entry_at
FROM observations GROUP BY account,market,outcome
)
SELECT s.*,c.last_event_at,c.first_entry_at
FROM selected s LEFT JOIN clocks c USING(account,market,outcome)
WHERE (?9 IS NULL OR c.last_event_at>=?9)
AND (?10 IS NULL OR c.last_event_at<=?10)
+9
View File
@@ -322,6 +322,15 @@ CREATE TABLE IF NOT EXISTS budget_spend_micros (
);
-- Keep issued public trade cursors valid after a restart, scoped to this database.
-- Preserve which outcome was actually burned by a full redemption.
CREATE TABLE IF NOT EXISTS position_redemption_times (
account TEXT NOT NULL REFERENCES accounts,
market TEXT NOT NULL REFERENCES markets,
outcome TEXT NOT NULL,
at_ms INTEGER NOT NULL,
PRIMARY KEY(account,market,outcome)
);
CREATE TABLE IF NOT EXISTS trade_cursor_key (
singleton INTEGER PRIMARY KEY CHECK(singleton=1), secret BLOB NOT NULL CHECK(length(secret)=32)
);