Distribute negative-risk conversion fees across cash and outcome shares
This commit is contained in:
@@ -7,7 +7,9 @@ CREATE TABLE IF NOT EXISTS wallet_movements (
|
||||
shares INTEGER, cash_delta INTEGER NOT NULL, at_ms INTEGER, UNIQUE(request_id,account)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS activity_by_account ON wallet_movements(account,at_ms,id);
|
||||
CREATE VIEW IF NOT EXISTS receipt_movements AS
|
||||
DROP TRIGGER IF EXISTS record_receipt_movement;
|
||||
DROP VIEW IF EXISTS receipt_movements;
|
||||
CREATE VIEW receipt_movements AS
|
||||
SELECT id AS request_id,json_extract(payload,'$.account') AS account,
|
||||
CASE json_extract(payload,'$.op') WHEN 'fund' THEN 'DEPOSIT' WHEN 'convert' THEN 'CONVERSION'
|
||||
ELSE upper(json_extract(payload,'$.op')) END AS kind,
|
||||
@@ -17,8 +19,9 @@ CREATE VIEW IF NOT EXISTS receipt_movements AS
|
||||
WHEN 'split' THEN -100*json_extract(response,'$.pairs')
|
||||
WHEN 'redeem' THEN json_extract(response,'$.paid')
|
||||
ELSE json_extract(response,'$.released_cents') END AS cash_delta
|
||||
FROM requests WHERE json_extract(payload,'$.op') IN ('fund','split','merge','redeem','convert');
|
||||
CREATE TRIGGER IF NOT EXISTS record_receipt_movement AFTER INSERT ON requests
|
||||
FROM requests WHERE json_extract(payload,'$.op') IN ('fund','split','merge','redeem','convert')
|
||||
AND COALESCE(json_extract(response,'$.noop'),0)=0;
|
||||
CREATE TRIGGER IF NOT EXISTS record_wallet_receipt AFTER INSERT ON requests
|
||||
WHEN json_extract(NEW.payload,'$.op') IN ('fund','split','merge','redeem','convert')
|
||||
BEGIN
|
||||
INSERT INTO wallet_movements(request_id,account,kind,market,group_id,shares,cash_delta,at_ms)
|
||||
|
||||
@@ -42,6 +42,7 @@ pub(crate) enum Command {
|
||||
event: String,
|
||||
markets: Vec<String>,
|
||||
augmented: Option<crate::augmented::Config>,
|
||||
conversion_fee: Option<crate::neg_risk::ConversionFee>,
|
||||
},
|
||||
#[serde(rename = "publish_clarification")]
|
||||
PublishClarification {
|
||||
|
||||
@@ -99,7 +99,7 @@ impl Exchange {
|
||||
db.execute_batch(include_str!("kickoff_schema.sql"))?;
|
||||
}
|
||||
let activity_ready: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='table' AND name='wallet_migration')",
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type='trigger' AND name='record_wallet_receipt')",
|
||||
[], |r| r.get(0),
|
||||
)?;
|
||||
if !activity_ready {
|
||||
@@ -245,6 +245,7 @@ impl Exchange {
|
||||
"fills",
|
||||
"paired_fills",
|
||||
"neg_risk_groups",
|
||||
"neg_risk_conversion_fees",
|
||||
"neg_risk_reserve_remainders",
|
||||
"augmented_results",
|
||||
] {
|
||||
|
||||
@@ -119,8 +119,9 @@ pub(crate) fn apply(
|
||||
event,
|
||||
markets,
|
||||
augmented,
|
||||
conversion_fee,
|
||||
} => {
|
||||
let result = crate::neg_risk::define(tx, &group, &event, &markets)?;
|
||||
let result = crate::neg_risk::define(tx, &group, &event, &markets, conversion_fee)?;
|
||||
if let Some(config) = augmented {
|
||||
config.save(tx, &group, &markets)?;
|
||||
}
|
||||
|
||||
@@ -15,11 +15,19 @@ impl Exchange {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, serde::Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct ConversionFee {
|
||||
bps: i64,
|
||||
vault: String,
|
||||
}
|
||||
|
||||
pub(crate) fn define(
|
||||
tx: &Transaction,
|
||||
group: &str,
|
||||
event: &str,
|
||||
markets: &[String],
|
||||
fee: Option<ConversionFee>,
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(event)?;
|
||||
@@ -44,7 +52,24 @@ pub(crate) fn define(
|
||||
"members must be unused preopen markets of this event with manual resolution"
|
||||
);
|
||||
}
|
||||
Ok(json!({"group":group,"markets":markets}))
|
||||
let mut receipt = json!({"group":group,"markets":markets});
|
||||
if let Some(fee) = fee {
|
||||
identifier(&fee.vault)?;
|
||||
ensure!(
|
||||
(0..=10000).contains(&fee.bps),
|
||||
"conversion fee must be 0 to 10000 bps"
|
||||
);
|
||||
tx.execute(
|
||||
"INSERT INTO accounts(id,cash) VALUES(?,0) ON CONFLICT(id) DO NOTHING",
|
||||
[&fee.vault],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO neg_risk_conversion_fees(group_id,bps,vault) VALUES(?,?,?)",
|
||||
params![group, fee.bps, fee.vault],
|
||||
)?;
|
||||
receipt["conversion_fee"] = json!(fee);
|
||||
}
|
||||
Ok(receipt)
|
||||
}
|
||||
|
||||
pub(crate) fn convert(
|
||||
@@ -58,7 +83,10 @@ pub(crate) fn convert(
|
||||
) -> Result<Value> {
|
||||
identifier(group)?;
|
||||
identifier(account)?;
|
||||
let units = inventory::quantity_units(qty, qty_micros)?;
|
||||
let units = match (qty, qty_micros) {
|
||||
(Some(0), None) | (None, Some(0)) => 0,
|
||||
_ => inventory::quantity_units(qty, qty_micros)?,
|
||||
};
|
||||
let selected: BTreeSet<&str> = no_markets.iter().map(String::as_str).collect();
|
||||
ensure!(
|
||||
!selected.is_empty() && selected.len() == no_markets.len(),
|
||||
@@ -79,21 +107,50 @@ pub(crate) fn convert(
|
||||
.all(|id| members.iter().any(|(market, _)| market.as_str() == *id)),
|
||||
"NO market outside group"
|
||||
);
|
||||
if units == 0 {
|
||||
return Ok(
|
||||
json!({"group":group,"no_markets":no_markets,"yes_markets":[],
|
||||
"qty":0,"qty_micros":0,"released_cents":0,"released_micros":0,"noop":true}),
|
||||
);
|
||||
}
|
||||
ensure!(
|
||||
members.iter().all(|(_, phase)| phase != "resolved"),
|
||||
"group already resolving"
|
||||
);
|
||||
let policy = tx
|
||||
.query_row(
|
||||
"SELECT bps,vault FROM neg_risk_conversion_fees WHERE group_id=?",
|
||||
[group],
|
||||
|row| {
|
||||
Ok(ConversionFee {
|
||||
bps: row.get(0)?,
|
||||
vault: row.get(1)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()?;
|
||||
// The adapter rounds each output before multiplying by the number of cash legs.
|
||||
let bps = policy.as_ref().map_or(0, |fee| fee.bps);
|
||||
let fee_units = i64::try_from(i128::from(units) * i128::from(bps) / 10_000)?;
|
||||
let net_units = units - fee_units;
|
||||
let mut yes_markets = Vec::new();
|
||||
for (market, _) in &members {
|
||||
if selected.contains(market.as_str()) {
|
||||
inventory::position(tx, account, market, "NO", -units)?;
|
||||
inventory::backing(tx, market, -units)?;
|
||||
} else {
|
||||
inventory::position(tx, account, market, "YES", units)?;
|
||||
if net_units > 0 {
|
||||
inventory::position(tx, account, market, "YES", net_units)?;
|
||||
}
|
||||
if let Some(fee) = policy.as_ref().filter(|_| fee_units > 0) {
|
||||
inventory::position(tx, &fee.vault, market, "YES", fee_units)?;
|
||||
}
|
||||
yes_markets.push(market);
|
||||
}
|
||||
}
|
||||
let released = (selected.len() as i64 - 1) * units;
|
||||
let cash_legs = selected.len() as i64 - 1;
|
||||
let released = cash_legs * net_units;
|
||||
let cash_fee = cash_legs * fee_units;
|
||||
let reserve: i64 = tx.query_row(
|
||||
"SELECT micros FROM neg_risk_reserves WHERE id=?",
|
||||
[group],
|
||||
@@ -110,7 +167,14 @@ pub(crate) fn convert(
|
||||
ledger::cash_micros(tx, account, released)?;
|
||||
let mut receipt = json!({"group":group,"qty":inventory::decimal(units.into(),inventory::UNIT),
|
||||
"no_markets":no_markets,"yes_markets":yes_markets,"released_cents":inventory::decimal(released.into(),10000)});
|
||||
if qty_micros.is_some() {
|
||||
if let Some(fee) = &policy {
|
||||
if cash_fee > 0 {
|
||||
ledger::cash_micros(tx, &fee.vault, cash_fee)?;
|
||||
}
|
||||
receipt["conversion_fee"] = json!({"bps":bps,"vault":fee.vault,
|
||||
"cash_micros":cash_fee,"yes_micros_per_market":fee_units});
|
||||
}
|
||||
if qty_micros.is_some() || policy.is_some() {
|
||||
inventory::movement(tx, request, account, group, "CONVERSION", units, released)?;
|
||||
receipt["qty_micros"] = json!(units);
|
||||
receipt["released_micros"] = json!(released);
|
||||
|
||||
@@ -196,6 +196,11 @@ CREATE TABLE IF NOT EXISTS neg_risk_groups (
|
||||
id TEXT PRIMARY KEY, reserve_cents INTEGER NOT NULL DEFAULT 0 CHECK(reserve_cents>=0),
|
||||
winner TEXT REFERENCES markets
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_conversion_fees (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id),
|
||||
bps INTEGER NOT NULL CHECK(bps BETWEEN 0 AND 10000),
|
||||
vault TEXT NOT NULL REFERENCES accounts(id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS neg_risk_reserve_remainders (
|
||||
group_id TEXT PRIMARY KEY REFERENCES neg_risk_groups(id), micros INTEGER NOT NULL CHECK(micros BETWEEN 0 AND 9999)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user