Expose account executions with original order, role and fill economics
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
use crate::{assets, validation::identifier};
|
||||
use anyhow::{ensure, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Filter {
|
||||
account: String,
|
||||
market: Option<String>,
|
||||
outcome: Option<String>,
|
||||
order: Option<i64>,
|
||||
after: Option<(i64, i64)>,
|
||||
limit: Option<u32>,
|
||||
}
|
||||
|
||||
impl Filter {
|
||||
pub(crate) fn read(self, db: &Connection) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(market) = &self.market {
|
||||
identifier(market)?;
|
||||
}
|
||||
if let Some(outcome) = &self.outcome {
|
||||
ensure!(
|
||||
self.market.is_some() && matches!(outcome.as_str(), "YES" | "NO"),
|
||||
"outcome requires a market and YES or NO"
|
||||
);
|
||||
}
|
||||
if let Some(order) = self.order {
|
||||
ensure!(order > 0, "invalid order");
|
||||
}
|
||||
let limit = self.limit.unwrap_or(100);
|
||||
let (execution, order) = self.after.unwrap_or((i64::MAX, i64::MAX));
|
||||
ensure!(
|
||||
(1..=1000).contains(&limit) && execution > 0 && order > 0,
|
||||
"invalid pagination"
|
||||
);
|
||||
let mut stmt = db.prepare(include_str!("account_trades.sql"))?;
|
||||
let mut rows = stmt.query(params![
|
||||
self.account,
|
||||
self.market,
|
||||
self.outcome,
|
||||
self.order,
|
||||
execution,
|
||||
order,
|
||||
limit + 1
|
||||
])?;
|
||||
let mut trades = Vec::new();
|
||||
let mut last = None;
|
||||
let mut next_after = None;
|
||||
while let Some(r) = rows.next()? {
|
||||
if trades.len() == limit as usize {
|
||||
next_after = last;
|
||||
break;
|
||||
}
|
||||
let execution: i64 = r.get(0)?;
|
||||
let order: i64 = r.get(1)?;
|
||||
let market: String = r.get(2)?;
|
||||
let outcome: String = r.get(3)?;
|
||||
let price: i64 = r.get(6)?;
|
||||
let size: i64 = r.get(7)?;
|
||||
trades.push(
|
||||
json!({"execution":execution,"order":order,"market":market,"outcome":outcome,
|
||||
"asset_id":assets::id(&market,&outcome),"side":r.get::<_,String>(4)?,
|
||||
"kind":r.get::<_,String>(5)?,"price_micros":price*10000,"size":size,
|
||||
"gross_cents":price*size,"at_ms":r.get::<_,Option<i64>>(8)?,
|
||||
"role":r.get::<_,Option<String>>(9)?}),
|
||||
);
|
||||
last = Some((execution, order));
|
||||
}
|
||||
Ok(json!({"trades":trades,"next_after":next_after}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
WITH owned AS (
|
||||
SELECT seq FROM orders WHERE account=?1 AND (?2 IS NULL OR market=?2)
|
||||
AND (?3 IS NULL OR outcome=?3) AND (?4 IS NULL OR seq=?4)
|
||||
), legs(execution,order_seq,kind,price,quantity,at_ms) AS (
|
||||
SELECT f.seq,o.seq,'transfer',f.price,f.quantity,t.at_ms
|
||||
FROM owned o CROSS JOIN fills f ON f.bid=o.seq LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,'transfer',f.price,f.quantity,t.at_ms
|
||||
FROM owned o CROSS JOIN fills f ON f.ask=o.seq LEFT JOIN trade_prices t ON t.fill=f.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,f.kind,f.yes_price,f.quantity,f.at_ms
|
||||
FROM owned o CROSS JOIN paired_fills f ON f.yes_order=o.seq
|
||||
UNION ALL
|
||||
SELECT f.seq,o.seq,f.kind,100-f.yes_price,f.quantity,f.at_ms
|
||||
FROM owned o CROSS JOIN paired_fills f ON f.no_order=o.seq
|
||||
)
|
||||
SELECT l.execution,o.seq,o.market,o.outcome,o.side,l.kind,l.price,l.quantity,l.at_ms,
|
||||
CASE WHEN c.execution IS NULL THEN NULL WHEN c.taker_order IS NULL THEN 'auction'
|
||||
WHEN c.taker_order=o.seq THEN 'taker' ELSE 'maker' END
|
||||
FROM legs l JOIN orders o ON o.seq=l.order_seq
|
||||
LEFT JOIN execution_context c ON c.execution=l.execution
|
||||
WHERE (l.execution,l.order_seq)<(?5,?6)
|
||||
ORDER BY l.execution DESC,l.order_seq DESC LIMIT ?7
|
||||
@@ -32,7 +32,7 @@ pub(crate) fn market_assets(db: &Connection, market: &str) -> Result<Value> {
|
||||
pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
if !matches!(
|
||||
request["op"].as_str(),
|
||||
Some("order" | "book" | "quote" | "history" | "open_orders")
|
||||
Some("order" | "book" | "quote" | "history" | "open_orders" | "trades")
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
tif != TimeInForce::Fak || !fills.is_empty(),
|
||||
"FAK has no matching liquidity"
|
||||
);
|
||||
settle(tx, &market, &outcome, fills)?;
|
||||
settle(tx, &market, &outcome, fills, Some(seq))?;
|
||||
}
|
||||
let (remaining, mut status): (i64, String) = tx.query_row(
|
||||
"SELECT remaining,status FROM orders WHERE seq=?",
|
||||
@@ -162,19 +162,20 @@ pub(crate) fn settle(
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
fills: Vec<Fill>,
|
||||
taker: Option<i64>,
|
||||
) -> Result<()> {
|
||||
for f in fills {
|
||||
let first = book_leg(tx, market, outcome, &f, f.bid)?;
|
||||
let second = book_leg(tx, market, outcome, &f, f.ask)?;
|
||||
if first.outcome == second.outcome {
|
||||
let execution: i64 = if first.outcome == second.outcome {
|
||||
let (buy, sell) = if first.side == "buy" {
|
||||
(first, second)
|
||||
} else {
|
||||
(second, first)
|
||||
};
|
||||
ensure!(buy.side == "buy" && sell.side == "sell", "invalid transfer");
|
||||
tx.execute("INSERT INTO fills(seq,bid,ask,price,quantity) SELECT id,?1,?2,?3,?4 FROM next_execution",
|
||||
params![buy.seq,sell.seq,buy.price,f.quantity])?;
|
||||
tx.query_row("INSERT INTO fills(seq,bid,ask,price,quantity) SELECT id,?1,?2,?3,?4 FROM next_execution RETURNING seq",
|
||||
params![buy.seq,sell.seq,buy.price,f.quantity], |r|r.get(0))?
|
||||
} else {
|
||||
ensure!(first.side == second.side, "invalid complementary legs");
|
||||
let mint = first.side == "buy";
|
||||
@@ -195,9 +196,9 @@ pub(crate) fn settle(
|
||||
} else {
|
||||
(second, first)
|
||||
};
|
||||
tx.execute(
|
||||
tx.query_row(
|
||||
"INSERT INTO paired_fills(seq,market,kind,yes_order,no_order,yes_price,quantity)
|
||||
SELECT id,?1,?2,?3,?4,?5,?6 FROM next_execution",
|
||||
SELECT id,?1,?2,?3,?4,?5,?6 FROM next_execution RETURNING seq",
|
||||
params![
|
||||
market,
|
||||
if mint { "mint" } else { "merge" },
|
||||
@@ -206,8 +207,13 @@ pub(crate) fn settle(
|
||||
yes.price,
|
||||
f.quantity
|
||||
],
|
||||
)?;
|
||||
}
|
||||
|r| r.get(0),
|
||||
)?
|
||||
};
|
||||
tx.execute(
|
||||
"INSERT INTO execution_context(execution,taker_order) VALUES(?,?)",
|
||||
params![execution, taker],
|
||||
)?;
|
||||
for seq in [f.bid, f.ask] {
|
||||
tx.execute("UPDATE orders SET remaining=remaining-?1,status=CASE WHEN remaining=?1 THEN 'filled' ELSE 'live' END WHERE seq=?2",params![f.quantity,seq])?;
|
||||
}
|
||||
|
||||
@@ -146,6 +146,7 @@ pub(crate) enum Query {
|
||||
},
|
||||
Positions(crate::portfolio::Filter),
|
||||
OpenOrders(crate::account_orders::Filter),
|
||||
Trades(crate::account_trades::Filter),
|
||||
Book {
|
||||
market: String,
|
||||
outcome: String,
|
||||
@@ -172,6 +173,7 @@ impl Query {
|
||||
match self {
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
Self::Trades(filter) => filter.read(db),
|
||||
Self::OpenOrders(filter) => filter.read(db),
|
||||
Self::Book { market, outcome } => {
|
||||
let phase = market_phase(db, &market, &outcome)?;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
mod account_orders;
|
||||
mod account_trades;
|
||||
mod assets;
|
||||
mod catalog;
|
||||
mod expiry;
|
||||
@@ -36,7 +37,16 @@ impl Exchange {
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
if matches!(
|
||||
payload["op"].as_str(),
|
||||
Some("assets" | "catalog" | "history" | "quote" | "book" | "open_orders" | "positions")
|
||||
Some(
|
||||
"assets"
|
||||
| "catalog"
|
||||
| "history"
|
||||
| "quote"
|
||||
| "book"
|
||||
| "open_orders"
|
||||
| "positions"
|
||||
| "trades"
|
||||
)
|
||||
) {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let mut request = payload;
|
||||
|
||||
@@ -150,7 +150,7 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
let book = books
|
||||
.get(&market, &outcome)
|
||||
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
|
||||
book::settle(tx, &market, &outcome, book.opening())?;
|
||||
book::settle(tx, &market, &outcome, book.opening(), None)?;
|
||||
}
|
||||
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
||||
Ok(json!({"phase":"continuous"}))
|
||||
|
||||
@@ -93,3 +93,14 @@ CREATE TRIGGER IF NOT EXISTS finish_deadline AFTER UPDATE OF status ON orders
|
||||
WHEN OLD.status='live' AND NEW.status<>'live' BEGIN
|
||||
UPDATE order_deadlines SET pending=0 WHERE seq=NEW.seq;
|
||||
END;
|
||||
|
||||
-- A present row with no taker records an opening auction. Older executions
|
||||
-- have no row and retain an unknown role.
|
||||
CREATE TABLE IF NOT EXISTS execution_context (
|
||||
execution INTEGER PRIMARY KEY, taker_order INTEGER REFERENCES orders(seq)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS account_orders_history ON orders(account,seq);
|
||||
CREATE INDEX IF NOT EXISTS fills_by_bid ON fills(bid,seq);
|
||||
CREATE INDEX IF NOT EXISTS fills_by_ask ON fills(ask,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_yes ON paired_fills(yes_order,seq);
|
||||
CREATE INDEX IF NOT EXISTS paired_by_no ON paired_fills(no_order,seq);
|
||||
|
||||
Reference in New Issue
Block a user