Preview market sweeps and execute protected share sales
This commit is contained in:
@@ -40,6 +40,8 @@ pub(crate) fn resolve(db: &Connection, request: &mut Value) -> Result<()> {
|
||||
| "history"
|
||||
| "open_orders"
|
||||
| "trades"
|
||||
| "market_sell"
|
||||
| "estimate"
|
||||
| "market_buy"
|
||||
| "cancel_market_orders"
|
||||
)
|
||||
|
||||
@@ -20,7 +20,23 @@ pub(crate) struct NewOrder {
|
||||
pub post_only: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<Value> {
|
||||
pub(crate) struct ShareExecution {
|
||||
pub seq: i64,
|
||||
pub filled: i64,
|
||||
pub status: String,
|
||||
pub gross_cents: i64,
|
||||
}
|
||||
impl ShareExecution {
|
||||
pub fn receipt(&self) -> Value {
|
||||
json!({"order":self.seq,"filled":self.filled,"status":self.status})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn gross_cents(fills: &[Fill]) -> i64 {
|
||||
fills.iter().map(|f| f.price * f.quantity).sum()
|
||||
}
|
||||
|
||||
pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result<ShareExecution> {
|
||||
let NewOrder {
|
||||
market,
|
||||
account,
|
||||
@@ -77,6 +93,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
params![seq, deadline],
|
||||
)?;
|
||||
}
|
||||
let mut gross = 0;
|
||||
if stage == "continuous" {
|
||||
let incoming = Order {
|
||||
seq,
|
||||
@@ -102,6 +119,7 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
tif != TimeInForce::Fak || !fills.is_empty(),
|
||||
"FAK has no matching liquidity"
|
||||
);
|
||||
gross = gross_cents(&fills);
|
||||
settle(tx, &market, &outcome, fills, Some(Taker::Limit(seq)))?;
|
||||
}
|
||||
let (remaining, mut status): (i64, String) = tx.query_row(
|
||||
@@ -113,7 +131,12 @@ pub(crate) fn submit(tx: &Transaction, books: &Books, order: NewOrder) -> Result
|
||||
release(tx, seq, &account, CancelReason::Cancelled)?;
|
||||
status = "cancelled".into();
|
||||
}
|
||||
Ok(json!({"order":seq,"filled":qty-remaining,"status":status}))
|
||||
Ok(ShareExecution {
|
||||
seq,
|
||||
filled: qty - remaining,
|
||||
status,
|
||||
gross_cents: gross,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) struct BudgetBuy {
|
||||
@@ -158,7 +181,7 @@ pub(crate) fn market_buy(tx: &Transaction, books: &Books, order: BudgetBuy) -> R
|
||||
.unwrap_or_default();
|
||||
ensure!(!fills.is_empty(), "no affordable liquidity");
|
||||
let quantity: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
let spent: i64 = fills.iter().map(|f| f.price * f.quantity).sum();
|
||||
let spent = gross_cents(&fills);
|
||||
let unspent = amount_cents - spent;
|
||||
ensure!(
|
||||
tif != TimeInForce::Fok || unspent == 0,
|
||||
|
||||
@@ -141,6 +141,7 @@ impl Listing {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub(crate) enum Query {
|
||||
Estimate(crate::estimate::Request),
|
||||
Resolution {
|
||||
market: String,
|
||||
},
|
||||
@@ -172,8 +173,9 @@ pub(crate) enum Query {
|
||||
},
|
||||
}
|
||||
impl Query {
|
||||
pub fn read(self, db: &Connection) -> Result<Value> {
|
||||
pub fn read(self, db: &Transaction, books: &mut crate::resident::Books) -> Result<Value> {
|
||||
match self {
|
||||
Self::Estimate(request) => request.read(db, books),
|
||||
Self::Resolution { market } => crate::resolution::read(db, &market),
|
||||
Self::Assets { market } => assets::market_assets(db, &market),
|
||||
Self::Positions(filter) => filter.read(db),
|
||||
|
||||
@@ -46,6 +46,15 @@ pub(crate) enum Command {
|
||||
#[serde(default)]
|
||||
post_only: bool,
|
||||
},
|
||||
#[serde(rename = "market_sell")]
|
||||
MarketSell {
|
||||
market: String,
|
||||
account: String,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
min_price: i64,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
#[serde(rename = "market_buy")]
|
||||
MarketBuy {
|
||||
market: String,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::{
|
||||
assets,
|
||||
book::gross_cents,
|
||||
command::TimeInForce,
|
||||
resident::Books,
|
||||
validation::{amount, phase},
|
||||
};
|
||||
use anyhow::{ensure, Result};
|
||||
use matching::{Order, Side};
|
||||
use rusqlite::Transaction;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "side", rename_all = "lowercase", deny_unknown_fields)]
|
||||
pub(crate) enum Request {
|
||||
Buy {
|
||||
market: String,
|
||||
outcome: String,
|
||||
amount_cents: i64,
|
||||
max_price: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
Sell {
|
||||
market: String,
|
||||
outcome: String,
|
||||
qty: i64,
|
||||
min_price: Option<i64>,
|
||||
tif: Option<TimeInForce>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn read(self, tx: &Transaction, books: &mut Books) -> Result<Value> {
|
||||
let (market, outcome, side, requested, limit, tif) = match self {
|
||||
Self::Buy {
|
||||
market,
|
||||
outcome,
|
||||
amount_cents,
|
||||
max_price,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Buy,
|
||||
amount_cents,
|
||||
max_price.unwrap_or(100),
|
||||
tif,
|
||||
),
|
||||
Self::Sell {
|
||||
market,
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
tif,
|
||||
} => (
|
||||
market,
|
||||
outcome,
|
||||
Side::Sell,
|
||||
qty,
|
||||
min_price.unwrap_or(0),
|
||||
tif,
|
||||
),
|
||||
};
|
||||
let tif = tif.unwrap_or(TimeInForce::Fak);
|
||||
amount(requested)?;
|
||||
ensure!(
|
||||
matches!(tif, TimeInForce::Fak | TimeInForce::Fok),
|
||||
"estimate requires FAK or FOK"
|
||||
);
|
||||
ensure!(
|
||||
matches!(outcome.as_str(), "YES" | "NO") && (0..=100).contains(&limit),
|
||||
"invalid outcome or price"
|
||||
);
|
||||
phase(tx, &market, &["continuous"])?;
|
||||
let changes = books.changes(tx)?;
|
||||
books.apply(changes);
|
||||
// The hypothetical incoming order follows all resting orders in time priority.
|
||||
let fills = books
|
||||
.get(&market, &outcome)
|
||||
.map(|b| match side {
|
||||
Side::Buy => b.match_budget_buy(i64::MAX, limit, requested),
|
||||
Side::Sell => b.match_incoming(&Order {
|
||||
seq: i64::MAX,
|
||||
side,
|
||||
price: limit,
|
||||
remaining: requested,
|
||||
}),
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let shares: i64 = fills.iter().map(|f| f.quantity).sum();
|
||||
let gross = gross_cents(&fills);
|
||||
let remainder = requested
|
||||
- match side {
|
||||
Side::Buy => gross,
|
||||
Side::Sell => shares,
|
||||
};
|
||||
let mut result = json!({"asset_id":assets::id(&market,&outcome),"filled_shares":shares,
|
||||
"gross_cents":gross,"best_fill_price":fills.first().map(|f|f.price),
|
||||
"worst_fill_price":fills.last().map(|f|f.price),
|
||||
"average_price_micros":(gross*10000).checked_div(shares),
|
||||
"fully_fillable":remainder==0,"executable":shares>0 && (tif==TimeInForce::Fak || remainder==0)});
|
||||
let key = match side {
|
||||
Side::Buy => "unspent_cents",
|
||||
Side::Sell => "unsold_shares",
|
||||
};
|
||||
result[key] = json!(remainder);
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ mod account_orders;
|
||||
mod account_trades;
|
||||
mod assets;
|
||||
mod catalog;
|
||||
mod estimate;
|
||||
mod expiry;
|
||||
mod twap;
|
||||
mod validation;
|
||||
@@ -42,6 +43,7 @@ impl Exchange {
|
||||
payload["op"].as_str(),
|
||||
Some(
|
||||
"assets"
|
||||
| "estimate"
|
||||
| "catalog"
|
||||
| "history"
|
||||
| "quote"
|
||||
@@ -56,7 +58,7 @@ impl Exchange {
|
||||
let mut request = payload;
|
||||
assets::resolve(&tx, &mut request)?;
|
||||
let query: catalog::Query = serde_json::from_value(request)?;
|
||||
let value = query.read(&tx)?;
|
||||
let value = query.read(&tx, &mut self.books)?;
|
||||
tx.commit()?;
|
||||
return Ok(value);
|
||||
}
|
||||
|
||||
@@ -137,7 +137,44 @@ pub(crate) fn apply(tx: &Transaction, books: &Books, command: Command) -> Result
|
||||
expiration,
|
||||
post_only,
|
||||
},
|
||||
),
|
||||
)
|
||||
.map(|result| result.receipt()),
|
||||
Command::MarketSell {
|
||||
market,
|
||||
account,
|
||||
outcome,
|
||||
qty,
|
||||
min_price,
|
||||
tif,
|
||||
} => {
|
||||
let tif = tif.unwrap_or(crate::command::TimeInForce::Fak);
|
||||
ensure!(
|
||||
matches!(
|
||||
tif,
|
||||
crate::command::TimeInForce::Fak | crate::command::TimeInForce::Fok
|
||||
),
|
||||
"market sell requires FAK or FOK"
|
||||
);
|
||||
let result = book::submit(
|
||||
tx,
|
||||
books,
|
||||
book::NewOrder {
|
||||
market,
|
||||
account,
|
||||
outcome,
|
||||
side: "sell".to_owned(),
|
||||
price: min_price,
|
||||
qty,
|
||||
tif,
|
||||
expiration: None,
|
||||
post_only: false,
|
||||
},
|
||||
)?;
|
||||
let mut receipt = result.receipt();
|
||||
receipt["proceeds_cents"] = json!(result.gross_cents);
|
||||
receipt["unsold_shares"] = json!(qty - result.filled);
|
||||
Ok(receipt)
|
||||
}
|
||||
Command::MarketBuy {
|
||||
market,
|
||||
outcome,
|
||||
|
||||
Reference in New Issue
Block a user