Reconstruct trade-only position basis and realized results
This commit is contained in:
@@ -1444,6 +1444,8 @@ flowchart LR
|
||||
positions --> sql["portfolio/positions.sql"]
|
||||
sql --> activity["成交、钱包流水及分侧赎回时间"]
|
||||
positions --> mark["portfolio.rs 中的估值"]
|
||||
positions --> cost["portfolio/economics.rs"]
|
||||
cost --> fills["portfolio/economics.sql"]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
mod economics;
|
||||
pub(crate) mod http;
|
||||
pub(crate) mod positions;
|
||||
mod protocol;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use crate::{inventory::decimal, lots};
|
||||
use rusqlite::{params, Connection};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const DOLLAR: i64 = 1_000_000;
|
||||
|
||||
// Dollars rounded to four places for position basis and PnL. Fees retain the
|
||||
// exact ledger precision separately, and total cost sums the served columns.
|
||||
pub(super) fn round_money(micros: i128) -> i128 {
|
||||
micros.signum() * ((micros.abs() + 50) / 100) * 100
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Cost {
|
||||
held_lots: i128,
|
||||
bought_lots: i128,
|
||||
principal: i128,
|
||||
entry_fees: i128,
|
||||
realized: i128,
|
||||
}
|
||||
|
||||
impl Cost {
|
||||
fn fill(&mut self, side: &str, quantity: i64, price: i64, fee: i64) -> Option<()> {
|
||||
let qty = i128::from(quantity);
|
||||
let amount = qty * i128::from(price);
|
||||
let fee = i128::from(fee);
|
||||
match side {
|
||||
"buy" => {
|
||||
self.held_lots += qty;
|
||||
self.bought_lots += qty;
|
||||
self.principal += amount;
|
||||
self.entry_fees += fee;
|
||||
self.realized -= fee;
|
||||
}
|
||||
"sell" if qty > 0 && qty <= self.held_lots => {
|
||||
let basis = self.principal.checked_mul(qty)? / self.held_lots;
|
||||
let entry_fees = self.entry_fees.checked_mul(qty)? / self.held_lots;
|
||||
self.held_lots -= qty;
|
||||
self.principal -= basis;
|
||||
self.entry_fees -= entry_fees;
|
||||
self.realized += amount - basis - fee;
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn fields(&self, current_value: Option<i128>) -> Value {
|
||||
let basis = round_money(self.principal);
|
||||
let realized = round_money(self.realized);
|
||||
let unrealized = current_value.map(|v| round_money(v) - basis);
|
||||
let avg = (self.held_lots > 0).then(|| {
|
||||
let scale = i128::from(lots::PER_SHARE);
|
||||
round_money((self.principal * scale + self.held_lots / 2) / self.held_lots)
|
||||
});
|
||||
json!({
|
||||
"avg_price": avg.map(|v| decimal(v,DOLLAR)),
|
||||
"total_size": decimal(self.bought_lots,lots::PER_SHARE),
|
||||
"entry_cost_usdc":decimal(basis,DOLLAR),
|
||||
"entry_fees_usdc":decimal(self.entry_fees,DOLLAR),
|
||||
"total_cost_usdc":decimal(basis+self.entry_fees,DOLLAR),
|
||||
"realized_pnl":decimal(realized,DOLLAR),
|
||||
"unrealized_pnl":unrealized.map(|v|decimal(v,DOLLAR)),
|
||||
"total_pnl":unrealized.map(|v|decimal(v+realized,DOLLAR)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconstruct basis only when the recorded fills explain the actual holding.
|
||||
pub(super) fn read(
|
||||
db: &Connection,
|
||||
account: &str,
|
||||
market: &str,
|
||||
outcome: &str,
|
||||
current_size: i64,
|
||||
current_value: Option<i128>,
|
||||
) -> rusqlite::Result<Value> {
|
||||
let mut stmt = db.prepare_cached(include_str!("economics.sql"))?;
|
||||
let mut rows = stmt.query(params![account, market, outcome])?;
|
||||
let mut cost = Cost::default();
|
||||
while let Some(row) = rows.next()? {
|
||||
let side: String = row.get(0)?;
|
||||
if cost
|
||||
.fill(&side, row.get(2)?, row.get(1)?, row.get(3)?)
|
||||
.is_none()
|
||||
{
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
}
|
||||
if cost.bought_lots == 0
|
||||
|| cost.held_lots * i128::from(lots::MICROS) != i128::from(current_size)
|
||||
{
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
Ok(cost.fields(current_value))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prorates_entry_basis_and_fees_after_a_partial_sale() {
|
||||
let mut cost = Cost::default();
|
||||
cost.fill("buy", 600, 4000, 600).unwrap();
|
||||
cost.fill("buy", 400, 6500, 400).unwrap();
|
||||
cost.fill("sell", 300, 8000, 300).unwrap();
|
||||
assert_eq!(
|
||||
cost.fields(Some(4_200_000)),
|
||||
json!({
|
||||
"avg_price":0.5, "total_size":10, "entry_cost_usdc":3.5,
|
||||
"entry_fees_usdc":0.0007, "total_cost_usdc":3.5007,
|
||||
"realized_pnl":0.8987, "unrealized_pnl":0.7, "total_pnl":1.5987
|
||||
})
|
||||
);
|
||||
assert!(cost.fill("sell", 701, 5000, 0).is_none());
|
||||
cost.fill("sell", 700, 5000, 0).unwrap();
|
||||
assert_eq!(cost.fields(Some(0))["entry_cost_usdc"], 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
SELECT t.side,t.price,t.quantity,COALESCE(f.fee_micros,0)
|
||||
FROM wallet_trade_legs t
|
||||
LEFT JOIN execution_fees f ON f.execution=t.execution AND f.taker_order=t.order_seq
|
||||
WHERE t.account=?1 AND t.market=?2 AND t.outcome=?3
|
||||
-- A fill-only reconstruction cannot assign basis to these custody changes.
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM wallet_movements w
|
||||
WHERE w.account=?1 AND w.market=?2 AND w.kind IN ('SPLIT','MERGE','REDEEM')
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM neg_risk_members n WHERE n.market=?2 AND (
|
||||
EXISTS (SELECT 1 FROM wallet_movements w
|
||||
WHERE w.account=?1 AND w.group_id=n.group_id AND w.kind='CONVERSION')
|
||||
OR EXISTS (SELECT 1 FROM neg_risk_conversion_fees f
|
||||
WHERE f.group_id=n.group_id AND f.vault=?1)
|
||||
)
|
||||
)
|
||||
ORDER BY t.execution,t.order_seq
|
||||
@@ -327,20 +327,20 @@ impl Exchange {
|
||||
} else {
|
||||
"OPEN"
|
||||
};
|
||||
page.insert(key, json!({
|
||||
page.insert(key, (json!({
|
||||
"proxy_wallet": account, "condition_id": market,
|
||||
"token_id": assets::id(&market,&outcome), "opposite_token_id": assets::id(&market,opposite),
|
||||
"current_size": decimal(size.into(),UNIT),
|
||||
"last_event_at":last_event_at, "first_entry_at":first_entry_at,
|
||||
"current_price": mark.map(|p| decimal(p.into(),UNIT)),
|
||||
"current_value": value.map(|v| decimal(v,UNIT)),
|
||||
"current_value": value.map(|v| decimal(super::economics::round_money(v),UNIT)),
|
||||
"status": status, "redeemable": redeemable, "mergeable": row.get::<_, bool>(7)?,
|
||||
"archived": row.get::<_, bool>(6)?, "negative_risk": row.get::<_, bool>(12)?,
|
||||
"title": row.get::<_, String>(8)?, "slug": row.get::<_, String>(9)?,
|
||||
"outcome": row.get::<_, String>(if yes {10} else {11})?,
|
||||
"opposite_outcome": row.get::<_, String>(if yes {11} else {10})?,
|
||||
"outcome_index": if yes {0} else {1}
|
||||
}));
|
||||
}), size, value));
|
||||
if page.len() > limit as usize + 1 {
|
||||
page.pop_last();
|
||||
}
|
||||
@@ -360,7 +360,28 @@ impl Exchange {
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let data: Vec<_> = page.into_values().collect();
|
||||
let mut data = Vec::with_capacity(page.len());
|
||||
for ((_, _, account, market, outcome), (mut row, size, value)) in page {
|
||||
let fields = super::economics::read(&tx, &account, &market, &outcome, size, value)?;
|
||||
let row_fields = row.as_object_mut().expect("position is an object");
|
||||
if let Value::Object(fields) = fields {
|
||||
row_fields.extend(fields);
|
||||
} else {
|
||||
for key in [
|
||||
"avg_price",
|
||||
"entry_cost_usdc",
|
||||
"entry_fees_usdc",
|
||||
"total_cost_usdc",
|
||||
"total_size",
|
||||
"realized_pnl",
|
||||
"unrealized_pnl",
|
||||
"total_pnl",
|
||||
] {
|
||||
row_fields.insert(key.into(), Value::Null);
|
||||
}
|
||||
}
|
||||
data.push(row);
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(
|
||||
json!({"data":data,"pagination":{"limit":limit,"offset":offset,"has_more":has_more,"next_cursor":next}}),
|
||||
|
||||
@@ -4293,3 +4293,32 @@ fn public_positions_walk_a_mergeable_pair_and_held_settlement() {
|
||||
let closed = read(&e, json!({"user":"alice","status":"CLOSED"})).unwrap();
|
||||
assert_eq!(closed["data"].as_array().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_positions_reconstructs_trade_basis_after_a_partial_sale() {
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
setup(&mut e);
|
||||
for cmd in [
|
||||
json!({"op":"fund","id":"fund-trader","account":"trader","cents":2000}),
|
||||
json!({"op":"open","id":"open","market":"e"}),
|
||||
order("ask", "alice", "sell", 40, 10),
|
||||
order("entry", "trader", "buy", 40, 10),
|
||||
order("exit", "trader", "sell", 80, 3),
|
||||
order("buyer", "bob", "buy", 80, 3),
|
||||
] {
|
||||
e.execute(cmd).unwrap();
|
||||
}
|
||||
let read = |user| {
|
||||
e.public_positions(serde_json::from_value(json!({"user":user})).unwrap())
|
||||
.unwrap()
|
||||
};
|
||||
let page = read("trader");
|
||||
let row = &page["data"][0];
|
||||
assert_eq!(row["current_size"], 7);
|
||||
assert_eq!(row["total_size"], 10);
|
||||
assert_eq!(row["entry_cost_usdc"], 2.8);
|
||||
assert_eq!(row["realized_pnl"], 1.2);
|
||||
assert_eq!(row["unrealized_pnl"], 2.8);
|
||||
assert_eq!(row["total_pnl"], 4);
|
||||
assert!(read("alice")["data"][0]["entry_cost_usdc"].is_null());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user