239 lines
8.6 KiB
Rust
239 lines
8.6 KiB
Rust
use crate::resident::Books;
|
|
use crate::{
|
|
book,
|
|
command::Command,
|
|
ledger,
|
|
validation::{amount, identifier, phase},
|
|
};
|
|
use anyhow::{ensure, Result};
|
|
use rusqlite::{params, OptionalExtension, Transaction};
|
|
use serde_json::{json, Value};
|
|
|
|
pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result<Value> {
|
|
match command {
|
|
Command::Fund { account, cents } => {
|
|
identifier(&account)?;
|
|
amount(cents)?;
|
|
tx.execute("INSERT INTO accounts VALUES(?,?)", params![account, cents])?;
|
|
Ok(json!({"funded":cents}))
|
|
}
|
|
Command::Event {
|
|
event,
|
|
title,
|
|
sport,
|
|
competition,
|
|
home,
|
|
away,
|
|
scheduled_at_ms,
|
|
} => {
|
|
identifier(&event)?;
|
|
ensure!(
|
|
scheduled_at_ms >= 0
|
|
&& home.trim() != away.trim()
|
|
&& [&title, &sport, &competition, &home, &away]
|
|
.iter()
|
|
.all(|s| !s.trim().is_empty()),
|
|
"invalid event"
|
|
);
|
|
tx.execute(
|
|
"INSERT INTO events VALUES(?,?,?,?,?,?,?)",
|
|
params![
|
|
event,
|
|
title,
|
|
sport,
|
|
competition,
|
|
home,
|
|
away,
|
|
scheduled_at_ms
|
|
],
|
|
)?;
|
|
Ok(json!({"event":event}))
|
|
}
|
|
Command::List {
|
|
market,
|
|
rules,
|
|
listing,
|
|
} => {
|
|
identifier(&market)?;
|
|
ensure!(!rules.trim().is_empty(), "rules required");
|
|
tx.execute(
|
|
"INSERT INTO markets(id,rules,phase) VALUES(?,?,'preopen')",
|
|
params![market, rules],
|
|
)?;
|
|
if let Some(listing) = listing {
|
|
listing.save(tx, &market)?;
|
|
}
|
|
Ok(json!({"phase":"preopen"}))
|
|
}
|
|
Command::Split {
|
|
market,
|
|
account,
|
|
qty,
|
|
} => {
|
|
identifier(&account)?;
|
|
amount(qty)?;
|
|
phase(tx, &market, &["preopen", "continuous"])?;
|
|
ledger::cash(tx, &account, -100 * qty)?;
|
|
tx.execute(
|
|
"UPDATE markets SET collateral=collateral+? WHERE id=?",
|
|
params![100 * qty, market],
|
|
)?;
|
|
for side in ["YES", "NO"] {
|
|
ledger::position(tx, &account, &market, side, qty)?;
|
|
}
|
|
Ok(json!({"pairs":qty}))
|
|
}
|
|
Command::Merge {
|
|
market,
|
|
account,
|
|
qty,
|
|
} => {
|
|
identifier(&account)?;
|
|
amount(qty)?;
|
|
phase(tx, &market, &["preopen", "continuous", "closed"])?;
|
|
let cents = 100 * qty;
|
|
for outcome in ["YES", "NO"] {
|
|
ledger::position(tx, &account, &market, outcome, -qty)?;
|
|
}
|
|
let released = tx.execute(
|
|
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
|
params![cents, market],
|
|
)?;
|
|
ensure!(released == 1, "insufficient collateral");
|
|
ledger::cash(tx, &account, cents)?;
|
|
Ok(json!({"pairs":qty,"released_cents":cents}))
|
|
}
|
|
Command::Order {
|
|
market,
|
|
account,
|
|
outcome,
|
|
side,
|
|
price,
|
|
qty,
|
|
tif,
|
|
expiration,
|
|
post_only,
|
|
} => book::submit(
|
|
tx,
|
|
books,
|
|
book::NewOrder {
|
|
market,
|
|
account,
|
|
outcome,
|
|
side,
|
|
price,
|
|
qty,
|
|
tif: tif.unwrap_or_else(|| {
|
|
if expiration.unwrap_or(0) != 0 {
|
|
crate::command::TimeInForce::Gtd
|
|
} else {
|
|
crate::command::TimeInForce::Gtc
|
|
}
|
|
}),
|
|
expiration,
|
|
post_only,
|
|
},
|
|
),
|
|
Command::Cancel { order, account } => {
|
|
identifier(&account)?;
|
|
let qty = book::release(tx, order, &account, book::CancelReason::Cancelled)?;
|
|
Ok(json!({"cancelled":qty}))
|
|
}
|
|
Command::Open { market } => {
|
|
phase(tx, &market, &["preopen"])?;
|
|
// Run one auction. Using the earliest order's outcome as the quote unit
|
|
// preserves the existing low-tick tie break for a one-outcome auction.
|
|
let first:Option<String>=tx.query_row(
|
|
"SELECT outcome FROM orders WHERE market=? AND status='live' ORDER BY seq LIMIT 1",
|
|
[&market],|r|r.get(0)).optional()?;
|
|
if let Some(outcome) = first {
|
|
let book = books
|
|
.get(&market, &outcome)
|
|
.ok_or_else(|| anyhow::anyhow!("missing auction book"))?;
|
|
book::settle(tx, &market, &outcome, book.opening(), None)?;
|
|
}
|
|
tx.execute("UPDATE markets SET phase='continuous' WHERE id=?", [market])?;
|
|
Ok(json!({"phase":"continuous"}))
|
|
}
|
|
Command::Close { market } => {
|
|
phase(tx, &market, &["preopen", "continuous"])?;
|
|
let mut stmt =
|
|
tx.prepare("SELECT seq,account FROM orders WHERE market=? AND status='live'")?;
|
|
let orders = stmt
|
|
.query_map([&market], |r| {
|
|
Ok((r.get::<_, i64>(0)?, r.get::<_, String>(1)?))
|
|
})?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
for (seq, account) in orders {
|
|
book::release(tx, seq, &account, book::CancelReason::Cancelled)?;
|
|
}
|
|
tx.execute("UPDATE markets SET phase='closed' WHERE id=?", [market])?;
|
|
Ok(json!({"phase":"closed"}))
|
|
}
|
|
Command::Finalize { market, winner } => {
|
|
let backing = finalize(tx, &market, &winner)?;
|
|
Ok(json!({"phase":"resolved","winner":winner,"outstanding_cents":backing}))
|
|
}
|
|
Command::Redeem { market, account } => {
|
|
identifier(&account)?;
|
|
phase(tx, &market, &["resolved"])?;
|
|
let paid = redeem(tx, &market, &account)?;
|
|
Ok(json!({"market":market,"account":account,"paid":paid}))
|
|
}
|
|
Command::Resolve { market, winner } => {
|
|
let backing = finalize(tx, &market, &winner)?;
|
|
let mut holders =
|
|
tx.prepare("SELECT DISTINCT account FROM positions WHERE market=? AND quantity>0")?;
|
|
let accounts = holders
|
|
.query_map([&market], |row| row.get::<_, String>(0))?
|
|
.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
let mut paid = 0;
|
|
for account in accounts {
|
|
paid += redeem(tx, &market, &account)?;
|
|
}
|
|
ensure!(backing == paid, "collateral mismatch");
|
|
Ok(json!({"phase":"resolved","paid":paid}))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn finalize(tx: &Transaction, market: &str, winner: &str) -> Result<i64> {
|
|
phase(tx, market, &["closed"])?;
|
|
ensure!(matches!(winner, "YES" | "NO" | "VOID"), "invalid winner");
|
|
// Close releases all outstanding reservations before finality.
|
|
let changed=tx.execute(
|
|
"UPDATE markets SET phase='resolved',winner=?1
|
|
WHERE id=?2 AND collateral=(
|
|
SELECT COALESCE(SUM(quantity * CASE WHEN ?1='VOID' THEN 50 WHEN outcome=?1 THEN 100 ELSE 0 END),0)
|
|
FROM positions WHERE market=?2)",
|
|
params![winner,market])?;
|
|
ensure!(changed == 1, "collateral mismatch");
|
|
Ok(tx.query_row(
|
|
"SELECT collateral FROM markets WHERE id=?",
|
|
[market],
|
|
|row| row.get(0),
|
|
)?)
|
|
}
|
|
|
|
fn redeem(tx: &Transaction, market: &str, account: &str) -> Result<i64> {
|
|
let paid:Option<i64>=tx.query_row(
|
|
"SELECT SUM(p.quantity * CASE WHEN m.winner='VOID' THEN 50 WHEN p.outcome=m.winner THEN 100 ELSE 0 END)
|
|
FROM positions p JOIN markets m ON m.id=p.market
|
|
WHERE p.market=? AND p.account=? AND p.quantity>0",
|
|
params![market,account],|row|row.get(0))?;
|
|
let paid = paid.ok_or_else(|| anyhow::anyhow!("no positions to redeem"))?;
|
|
tx.execute(
|
|
"UPDATE positions SET quantity=0 WHERE market=? AND account=? AND quantity>0",
|
|
params![market, account],
|
|
)?;
|
|
ensure!(
|
|
tx.execute(
|
|
"UPDATE markets SET collateral=collateral-?1 WHERE id=?2 AND collateral>=?1",
|
|
params![paid, market]
|
|
)? == 1,
|
|
"insufficient collateral"
|
|
);
|
|
ledger::cash(tx, account, paid)?;
|
|
Ok(paid)
|
|
}
|