Ignore:
Timestamp:
09/16/26 23:37:15 (13 days ago)
Author:
Stefan <trsunovstefan@…>
Branches:
main
Children:
8b447ef
Parents:
df05838
Message:

add reserved_quantity and modify the phases, add v_03.png and v_03.xml for P1

File:
1 edited

Legend:

Unmodified
Added
Removed
  • docs/P3-UseCaseModel/UseCase0004.md

    rdf05838 r9577c79  
    3737   BEGIN;
    3838
     39   -- (a) record intent — no trade has happened yet.
    3940   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)
    4142   VALUES
    42        ($user_id, $market_id, 'buy', 'market', 'executed', $qty, $price, now())
     43       ($user_id, $market_id, 'buy', 'market', 'open', $qty, $price)
    4344   RETURNING id;  -- captured as $order_id
    4445
     46   -- (b) lock and check the user balance
    4547   SELECT available_balance FROM project.users WHERE id = $user_id FOR UPDATE;
    4648   -- abort if available_balance < notional
    4749
     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.
    4853   UPDATE project.users
    4954      SET available_balance = available_balance - $notional,
    … …  
    5257    WHERE id = $user_id;
    5358
    54    -- Upsert holding with running weighted-average price:
     59   -- (d) upsert holding with running weighted-average price:
    5560   SELECT quantity, avg_price
    5661     FROM project.holdings
    … …  
    6166   -- new_avg = (old_qty*old_avg + $qty*$price) / (old_qty + $qty)
    6267
     68   -- (e) ledger entry
    6369   INSERT INTO project.transactions
    6470       (user_id, type, amount, currency, related_order, description)
    … …  
    6672       ($user_id, 'buy', -$notional, 'USD', $order_id, 'Market buy ...');
    6773
     74   -- (f) record the resulting market trade
    6875   INSERT INTO project.market_trades
    6976       (market_id, executed_at, price, quantity, side, source)
    7077   VALUES
    7178       ($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;
    7284
    7385   COMMIT;
Note: See TracChangeset for help on using the changeset viewer.