Changeset 9577c79 for docs/P3-UseCaseModel/UseCase0004.md
- Timestamp:
- 09/16/26 23:37:15 (13 days ago)
- Branches:
- main
- Children:
- 8b447ef
- Parents:
- df05838
- File:
-
- 1 edited
-
docs/P3-UseCaseModel/UseCase0004.md (modified) (4 diffs)
Legend:
- Unmodified
- Added
- Removed
-
docs/P3-UseCaseModel/UseCase0004.md
rdf05838 r9577c79 37 37 BEGIN; 38 38 39 -- (a) record intent — no trade has happened yet. 39 40 INSERT INTO project.orders 40 (user_id, market_id, side, type, status, quantity, price , executed_at)41 (user_id, market_id, side, type, status, quantity, price) 41 42 VALUES 42 ($user_id, $market_id, 'buy', 'market', ' executed', $qty, $price, now())43 ($user_id, $market_id, 'buy', 'market', 'open', $qty, $price) 43 44 RETURNING id; -- captured as $order_id 44 45 46 -- (b) lock and check the user balance 45 47 SELECT available_balance FROM project.users WHERE id = $user_id FOR UPDATE; 46 48 -- abort if available_balance < notional 47 49 50 -- (c) move cash from available to invested. A buy never reserves crypto 51 -- the way a sell does — it only ever adds to the position, so there 52 -- is nothing on the holdings side to commit before settling. 48 53 UPDATE project.users 49 54 SET available_balance = available_balance - $notional, … … 52 57 WHERE id = $user_id; 53 58 54 -- Upsert holding with running weighted-average price:59 -- (d) upsert holding with running weighted-average price: 55 60 SELECT quantity, avg_price 56 61 FROM project.holdings … … 61 66 -- new_avg = (old_qty*old_avg + $qty*$price) / (old_qty + $qty) 62 67 68 -- (e) ledger entry 63 69 INSERT INTO project.transactions 64 70 (user_id, type, amount, currency, related_order, description) … … 66 72 ($user_id, 'buy', -$notional, 'USD', $order_id, 'Market buy ...'); 67 73 74 -- (f) record the resulting market trade 68 75 INSERT INTO project.market_trades 69 76 (market_id, executed_at, price, quantity, side, source) 70 77 VALUES 71 78 ($market_id, now(), $price, $qty, 'buy', 'user'); 79 80 -- (g) settle the order itself — it has now actually been filled. 81 UPDATE project.orders 82 SET status = 'executed', executed_at = now() 83 WHERE id = $order_id; 72 84 73 85 COMMIT;
Note:
See TracChangeset
for help on using the changeset viewer.
