245 lines
7.7 KiB
Rust
245 lines
7.7 KiB
Rust
use crate::{command::TimeInForce, resident::Books};
|
|
use crate::{
|
|
ledger,
|
|
validation::{amount, identifier, phase},
|
|
};
|
|
use anyhow::{ensure, Result};
|
|
use matching::{Fill, Order, Side};
|
|
use rusqlite::{params, Transaction};
|
|
use serde_json::{json, Value};
|
|
|
|
pub(crate) struct NewOrder {
|
|
pub market: String,
|
|
pub account: String,
|
|
pub outcome: String,
|
|
pub side: String,
|
|
pub price: i64,
|
|
pub qty: i64,
|
|
pub tif: TimeInForce,
|
|
pub expiration: Option<i64>,
|
|
pub post_only: bool,
|
|
}
|
|
|
|
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<Value> {
|
|
let NewOrder {
|
|
market,
|
|
account,
|
|
outcome,
|
|
side,
|
|
price,
|
|
qty,
|
|
tif,
|
|
expiration,
|
|
post_only,
|
|
} = order;
|
|
identifier(&account)?;
|
|
amount(qty)?;
|
|
let stage = phase(tx, &market, &["preopen", "continuous"])?;
|
|
ensure!(
|
|
matches!(outcome.as_str(), "YES" | "NO") && matches!(side.as_str(), "buy" | "sell"),
|
|
"invalid instrument or side"
|
|
);
|
|
ensure!((0..=100).contains(&price), "invalid price");
|
|
ensure!(
|
|
tif == TimeInForce::Gtc || stage == "continuous",
|
|
"unsupported time in force"
|
|
);
|
|
ensure!(
|
|
!post_only || (stage == "continuous" && matches!(tif, TimeInForce::Gtc | TimeInForce::Gtd)),
|
|
"post-only requires continuous GTC or GTD"
|
|
);
|
|
let deadline = match tif {
|
|
TimeInForce::Gtd => {
|
|
let expiration =
|
|
expiration.ok_or_else(|| anyhow::anyhow!("GTD requires expiration"))?;
|
|
let now: i64 = tx.query_row("SELECT unixepoch()", [], |r| r.get(0))?;
|
|
ensure!(
|
|
expiration >= now + 180,
|
|
"GTD expiration must be at least 180 seconds ahead"
|
|
);
|
|
Some(expiration)
|
|
}
|
|
_ => {
|
|
ensure!(expiration.unwrap_or(0) == 0, "expiration requires GTD");
|
|
None
|
|
}
|
|
};
|
|
if side == "buy" {
|
|
ledger::cash(tx, &account, -price * qty)?;
|
|
} else {
|
|
ledger::position(tx, &account, &market, &outcome, -qty)?;
|
|
}
|
|
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 let Some(deadline) = deadline {
|
|
tx.execute(
|
|
"INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)",
|
|
params![seq, deadline],
|
|
)?;
|
|
}
|
|
if stage == "continuous" {
|
|
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 matches!(tif, TimeInForce::Ioc | TimeInForce::Fak) && remaining > 0 {
|
|
release(tx, seq, &account, CancelReason::Cancelled)?;
|
|
status = "cancelled".into();
|
|
}
|
|
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
|
|
}
|
|
|
|
struct ExecutedLeg {
|
|
seq: i64,
|
|
outcome: String,
|
|
side: String,
|
|
price: i64,
|
|
}
|
|
|
|
fn book_leg(
|
|
tx: &Transaction,
|
|
market: &str,
|
|
view: &str,
|
|
fill: &Fill,
|
|
seq: i64,
|
|
) -> Result<ExecutedLeg> {
|
|
let (account, outcome, side, limit): (String, String, String, i64) = tx.query_row(
|
|
"SELECT account,outcome,side,price FROM orders
|
|
WHERE seq=? AND market=? AND status='live' AND remaining>=?",
|
|
params![seq, market, fill.quantity],
|
|
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
|
|
)?;
|
|
let price = if outcome == view {
|
|
fill.price
|
|
} else {
|
|
100 - fill.price
|
|
};
|
|
if side == "buy" {
|
|
ensure!(price <= limit, "buy limit exceeded");
|
|
ledger::cash(tx, &account, (limit - price) * fill.quantity)?;
|
|
ledger::position(tx, &account, market, &outcome, fill.quantity)?;
|
|
} else {
|
|
ensure!(price >= limit, "sell limit exceeded");
|
|
ledger::cash(tx, &account, price * fill.quantity)?;
|
|
}
|
|
Ok(ExecutedLeg {
|
|
seq,
|
|
outcome,
|
|
side,
|
|
price,
|
|
})
|
|
}
|
|
|
|
pub(crate) fn settle(
|
|
tx: &Transaction,
|
|
market: &str,
|
|
outcome: &str,
|
|
fills: Vec<Fill>,
|
|
) -> 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 (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])?;
|
|
} else {
|
|
ensure!(first.side == second.side, "invalid complementary legs");
|
|
let mint = first.side == "buy";
|
|
let delta = if mint {
|
|
100 * f.quantity
|
|
} else {
|
|
-100 * f.quantity
|
|
};
|
|
ensure!(
|
|
tx.execute(
|
|
"UPDATE markets SET collateral=collateral+?1 WHERE id=?2 AND collateral+?1>=0",
|
|
params![delta, market]
|
|
)? == 1,
|
|
"insufficient collateral"
|
|
);
|
|
let (yes, no) = if first.outcome == "YES" {
|
|
(first, second)
|
|
} else {
|
|
(second, first)
|
|
};
|
|
tx.execute(
|
|
"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",
|
|
params![
|
|
market,
|
|
if mint { "mint" } else { "merge" },
|
|
yes.seq,
|
|
no.seq,
|
|
yes.price,
|
|
f.quantity
|
|
],
|
|
)?;
|
|
}
|
|
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])?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) enum CancelReason {
|
|
Cancelled,
|
|
Expired,
|
|
}
|
|
|
|
pub(crate) fn release(
|
|
tx: &Transaction,
|
|
seq: i64,
|
|
owner: &str,
|
|
reason: CancelReason,
|
|
) -> Result<i64> {
|
|
let (market,outcome,side,price,qty):(String,String,String,i64,i64)=tx.query_row("SELECT market,outcome,side,price,remaining FROM orders WHERE seq=? AND account=? AND status='live'",params![seq,owner],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
|
|
if side == "buy" {
|
|
ledger::cash(tx, owner, price * qty)?;
|
|
} else {
|
|
ledger::position(tx, owner, &market, &outcome, qty)?;
|
|
}
|
|
let status = match reason {
|
|
CancelReason::Cancelled => "cancelled",
|
|
CancelReason::Expired => "expired",
|
|
};
|
|
tx.execute(
|
|
"UPDATE orders SET status=? WHERE seq=?",
|
|
params![status, seq],
|
|
)?;
|
|
Ok(qty)
|
|
}
|