| 1 | # Use-case 0005 Implementation — Sell
|
|---|
| 2 |
|
|---|
| 3 | **Initiating actor:** Trader. **Source file:** `server/trade.go`, function `PlaceOrder(s, "sell")`.
|
|---|
| 4 |
|
|---|
| 5 | ## Scenario (implemented)
|
|---|
| 6 |
|
|---|
| 7 | 1. **User** chooses `[5] Place market SELL order`.
|
|---|
| 8 | 2. **System** lists markets (same as UC0004 step 2).
|
|---|
| 9 | 3. **User** enters market symbol, e.g. `ETH`, then quantity `0.5`.
|
|---|
| 10 | 4. **System** opens a transaction and runs:
|
|---|
| 11 |
|
|---|
| 12 | ```sql
|
|---|
| 13 | BEGIN;
|
|---|
| 14 |
|
|---|
| 15 | INSERT INTO orders
|
|---|
| 16 | (user_id, market_id, side, type, status, quantity, price, executed_at)
|
|---|
| 17 | VALUES
|
|---|
| 18 | ($1, $2, 'sell', 'market', 'executed', $3, $4, now())
|
|---|
| 19 | RETURNING id;
|
|---|
| 20 |
|
|---|
| 21 | SELECT quantity, avg_price FROM holdings
|
|---|
| 22 | WHERE user_id = $1 AND crypto_id = $c FOR UPDATE;
|
|---|
| 23 | -- abort if missing or insufficient
|
|---|
| 24 |
|
|---|
| 25 | UPDATE holdings
|
|---|
| 26 | SET quantity = quantity - $qty, updated_at = now()
|
|---|
| 27 | WHERE user_id = $1 AND crypto_id = $c;
|
|---|
| 28 |
|
|---|
| 29 | UPDATE users
|
|---|
| 30 | SET available_balance = available_balance + $notional,
|
|---|
| 31 | invested_balance = GREATEST(invested_balance - ($avg * $qty), 0),
|
|---|
| 32 | updated_at = now()
|
|---|
| 33 | WHERE id = $1;
|
|---|
| 34 |
|
|---|
| 35 | INSERT INTO transactions
|
|---|
| 36 | (user_id, type, amount, currency, related_order, description)
|
|---|
| 37 | VALUES
|
|---|
| 38 | ($1, 'sell', $notional, 'USD', $orderId, 'Market sell ...');
|
|---|
| 39 |
|
|---|
| 40 | INSERT INTO market_trades
|
|---|
| 41 | (market_id, executed_at, price, quantity, side, source)
|
|---|
| 42 | VALUES
|
|---|
| 43 | ($2, now(), $price, $qty, 'sell', 'user');
|
|---|
| 44 |
|
|---|
| 45 | COMMIT;
|
|---|
| 46 | ```
|
|---|
| 47 |
|
|---|
| 48 | 
|
|---|
| 49 |
|
|---|
| 50 | 5. **System** prints: `Order executed: sell 0.5000 ETH @ 3520.000000 (notional 1760.0000 USD)`.
|
|---|
| 51 |
|
|---|
| 52 | ## Failure path — insufficient holding
|
|---|
| 53 |
|
|---|
| 54 | If the holding does not exist or `quantity < requested`, the `defer tx.Rollback()` in `server/trade.go` reverts every statement above and the user sees:
|
|---|
| 55 |
|
|---|
| 56 | ```
|
|---|
| 57 | Insufficient holding: trying to sell X, hold Y
|
|---|
| 58 | ```
|
|---|