Cancel outstanding orders when their trading key misses its heartbeat
This commit is contained in:
@@ -45,7 +45,8 @@ impl Filter {
|
||||
"SELECT seq,market,outcome,side,price,quantity,remaining,status,
|
||||
(SELECT expiration FROM order_deadlines d WHERE d.seq=orders.seq),
|
||||
b.amount_cents,b.spent_cents,
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq) FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
(SELECT COALESCE(SUM(fee_micros),0) FROM execution_fees WHERE taker_order=orders.seq),
|
||||
(SELECT key_id FROM order_keys WHERE order_seq=orders.seq) FROM orders LEFT JOIN budget_buys b ON b.order_seq=orders.seq
|
||||
WHERE account=?1 AND (?2 IS NULL OR market=?2) AND (?3 IS NULL OR outcome=?3)
|
||||
AND seq>?4 AND {scope} ORDER BY seq LIMIT ?5"
|
||||
);
|
||||
@@ -78,7 +79,7 @@ impl Filter {
|
||||
"price_micros":row.get::<_,i64>(4)?*10000,"original_size":quantity,
|
||||
"size_matched":quantity-remaining,"open_size":if status=="live"{remaining}else{0},
|
||||
"status":status,"expiration":row.get::<_,Option<i64>>(8)?,
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?,"fee_micros":row.get::<_,i64>(11)?}),
|
||||
"amount_cents":row.get::<_,Option<i64>>(9)?,"spent_cents":row.get::<_,Option<i64>>(10)?,"fee_micros":row.get::<_,i64>(11)?,"key_id":row.get::<_,Option<String>>(12)?}),
|
||||
);
|
||||
last_id = Some(id);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ use serde_json::{json, Value};
|
||||
pub(crate) struct NewOrder {
|
||||
pub market: String,
|
||||
pub account: String,
|
||||
pub key_id: Option<String>,
|
||||
pub outcome: String,
|
||||
pub side: String,
|
||||
pub price: i64,
|
||||
@@ -45,6 +46,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
let NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
@@ -92,6 +94,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
}
|
||||
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();
|
||||
crate::heartbeat::record_key(tx, seq, key_id.as_deref())?;
|
||||
if let Some(deadline) = deadline {
|
||||
tx.execute(
|
||||
"INSERT INTO order_deadlines(seq,expiration) VALUES(?,?)",
|
||||
@@ -151,6 +154,7 @@ pub(crate) struct BudgetBuy {
|
||||
pub market: String,
|
||||
pub outcome: String,
|
||||
pub account: String,
|
||||
pub key_id: Option<String>,
|
||||
pub amount_cents: i64,
|
||||
pub max_price: i64,
|
||||
pub tif: TimeInForce,
|
||||
@@ -158,6 +162,7 @@ pub(crate) struct BudgetBuy {
|
||||
|
||||
pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> Result<Value> {
|
||||
let BudgetBuy {
|
||||
key_id,
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
@@ -183,6 +188,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
params![account, market, outcome, max_price],
|
||||
)?;
|
||||
let seq = tx.last_insert_rowid();
|
||||
crate::heartbeat::record_key(tx, seq, key_id.as_deref())?;
|
||||
let mut fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| b.match_budget_buy(seq, max_price, amount_cents))
|
||||
|
||||
@@ -54,6 +54,7 @@ pub(crate) enum Command {
|
||||
Order {
|
||||
market: String,
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
outcome: String,
|
||||
side: String,
|
||||
price: i64,
|
||||
@@ -68,6 +69,7 @@ pub(crate) enum Command {
|
||||
MarketSell {
|
||||
market: String,
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
min_price: i64,
|
||||
@@ -78,6 +80,7 @@ pub(crate) enum Command {
|
||||
market: String,
|
||||
outcome: String,
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
amount_cents: i64,
|
||||
max_price: i64,
|
||||
tif: Option<TimeInForce>,
|
||||
|
||||
@@ -13,6 +13,7 @@ pub(crate) fn transaction(
|
||||
let due: bool = tx.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)
|
||||
OR EXISTS(SELECT 1 FROM twap_markets WHERE pending_close=1 AND end_at<=unixepoch())
|
||||
OR EXISTS(SELECT 1 FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER))
|
||||
OR EXISTS(SELECT 1 FROM quote_pending)",
|
||||
[], |row| row.get(0),
|
||||
)?;
|
||||
@@ -45,6 +46,7 @@ pub(crate) fn transaction(
|
||||
for market in markets {
|
||||
crate::market::close_market(&write, &market)?;
|
||||
}
|
||||
crate::heartbeat::expire(&write)?;
|
||||
crate::quotes::flush(&write)?;
|
||||
write.commit()?;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
use crate::{
|
||||
book::{self, CancelReason},
|
||||
validation::identifier,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use rusqlite::{params, OptionalExtension, Transaction};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Beat {
|
||||
account: String,
|
||||
key_id: Option<String>,
|
||||
heartbeat_id: String,
|
||||
}
|
||||
|
||||
impl Beat {
|
||||
pub(crate) fn accept(self, tx: &Transaction) -> Result<Value> {
|
||||
identifier(&self.account)?;
|
||||
if let Some(key) = &self.key_id {
|
||||
identifier(key)?;
|
||||
}
|
||||
let key = self.key_id.as_deref().unwrap_or("");
|
||||
let expected: Option<String> = tx
|
||||
.query_row(
|
||||
"SELECT heartbeat_id FROM order_heartbeats WHERE account=? AND key_id=?",
|
||||
params![self.account, key],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
let expected = expected.as_deref().unwrap_or("");
|
||||
if expected != self.heartbeat_id {
|
||||
return Ok(json!({"error_msg":"Invalid Heartbeat ID","heartbeat_id":expected}));
|
||||
}
|
||||
let (id, deadline): (String,i64) = tx.query_row(
|
||||
"INSERT INTO order_heartbeats(account,key_id,heartbeat_id,deadline_ms)
|
||||
VALUES(?1,?2,lower(hex(randomblob(16))),CAST(unixepoch('subsec')*1000 AS INTEGER)+10000)
|
||||
ON CONFLICT(account,key_id) DO UPDATE SET heartbeat_id=excluded.heartbeat_id,deadline_ms=excluded.deadline_ms
|
||||
RETURNING heartbeat_id,deadline_ms",
|
||||
params![self.account,key],
|
||||
|r| Ok((r.get(0)?,r.get(1)?)),
|
||||
)?;
|
||||
Ok(json!({"heartbeat_id":id,"deadline_ms":deadline}))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn record_key(tx: &Transaction, order: i64, key: Option<&str>) -> Result<()> {
|
||||
if let Some(key) = key {
|
||||
identifier(key)?;
|
||||
tx.execute("INSERT INTO order_keys VALUES(?,?)", params![order, key])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn expire(tx: &Transaction) -> Result<()> {
|
||||
// Capture registrations at one instant. A session becoming due during
|
||||
// the refunds stays registered until the next pass.
|
||||
let mut stmt = tx.prepare(
|
||||
"DELETE FROM order_heartbeats WHERE deadline_ms<=CAST(unixepoch('subsec')*1000 AS INTEGER)
|
||||
RETURNING account,key_id",
|
||||
)?;
|
||||
let due = stmt
|
||||
.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for (account, key) in due {
|
||||
let mut orders = tx.prepare_cached(
|
||||
"SELECT o.seq FROM orders o LEFT JOIN order_keys k ON k.order_seq=o.seq
|
||||
WHERE o.account=? AND o.status='live' AND COALESCE(k.key_id,'')=? ORDER BY o.seq",
|
||||
)?;
|
||||
let ids = orders
|
||||
.query_map(params![account, key], |r| r.get::<_, i64>(0))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
for order in ids {
|
||||
book::release(tx, order, &account, CancelReason::Cancelled)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,6 +7,7 @@ mod catalog;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod fees;
|
||||
mod heartbeat;
|
||||
mod holders;
|
||||
mod twap;
|
||||
mod validation;
|
||||
@@ -70,7 +71,27 @@ impl Exchange {
|
||||
Ok(Self { db, books })
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
/// Run expiry and synchronize the resident book while the transport is idle.
|
||||
pub fn maintain(&mut self) -> Result<()> {
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Deferred)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, mut payload: Value) -> Result<Value> {
|
||||
if payload["op"].as_str() == Some("heartbeat") {
|
||||
payload
|
||||
.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("op");
|
||||
let beat: heartbeat::Beat = serde_json::from_value(payload)?;
|
||||
let tx = expiry::transaction(&self.db, TransactionBehavior::Immediate)?;
|
||||
let response = beat.accept(&tx)?;
|
||||
tx.commit()?;
|
||||
return Ok(response);
|
||||
}
|
||||
if matches!(
|
||||
payload["op"].as_str(),
|
||||
Some(
|
||||
|
||||
@@ -117,6 +117,7 @@ pub(crate) fn apply(
|
||||
Command::Order {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
@@ -130,6 +131,7 @@ pub(crate) fn apply(
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side,
|
||||
price,
|
||||
@@ -149,6 +151,7 @@ pub(crate) fn apply(
|
||||
Command::MarketSell {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
@@ -168,6 +171,7 @@ pub(crate) fn apply(
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
key_id,
|
||||
outcome,
|
||||
side: "sell".to_owned(),
|
||||
price: min_price,
|
||||
@@ -190,6 +194,7 @@ pub(crate) fn apply(
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
key_id,
|
||||
amount_cents,
|
||||
max_price,
|
||||
tif,
|
||||
@@ -200,6 +205,7 @@ pub(crate) fn apply(
|
||||
market,
|
||||
outcome,
|
||||
account,
|
||||
key_id,
|
||||
amount_cents,
|
||||
max_price,
|
||||
tif: tif.unwrap_or(crate::command::TimeInForce::Fak),
|
||||
|
||||
@@ -245,3 +245,13 @@ CREATE TABLE IF NOT EXISTS execution_fees (
|
||||
taker_order INTEGER NOT NULL REFERENCES orders(seq), fee_micros INTEGER NOT NULL CHECK(fee_micros>0)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS fees_by_order ON execution_fees(taker_order);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS order_keys (
|
||||
order_seq INTEGER PRIMARY KEY REFERENCES orders(seq), key_id TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS order_heartbeats (
|
||||
account TEXT NOT NULL REFERENCES accounts(id), key_id TEXT NOT NULL,
|
||||
heartbeat_id TEXT NOT NULL, deadline_ms INTEGER NOT NULL,
|
||||
PRIMARY KEY(account,key_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS heartbeat_deadlines ON order_heartbeats(deadline_ms);
|
||||
|
||||
Reference in New Issue
Block a user