source: docs/P4-Prototype/UseCase0005Implementation.md@ b715712

main
Last change on this file since b715712 was b715712, checked in by Stefan <trsunovstefan@…>, 8 weeks ago

Add the server side and configuration

  • Property mode set to 100644
File size: 1.8 KB
Line 
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
71. **User** chooses `[5] Place market SELL order`.
82. **System** lists markets (same as UC0004 step 2).
93. **User** enters market symbol, e.g. `ETH`, then quantity `0.5`.
104. **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 ![Selling 0.5 ETH at the current market price](screenshots/uc0005_sell.png)
49
505. **System** prints: `Order executed: sell 0.5000 ETH @ 3520.000000 (notional 1760.0000 USD)`.
51
52## Failure path — insufficient holding
53
54If 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```
57Insufficient holding: trying to sell X, hold Y
58```
Note: See TracBrowser for help on using the repository browser.