source: docs/P1-ConceptualModel/ERModel.md@ df05838

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

Zip files

  • Property mode set to 100644
File size: 12.4 KB
Line 
1# Entity-Relationship Model v.02
2
3## Diagram
4
5![ERModel_v02](ERModel_v02.png)
6
7
8Notation: Chen. Rectangles are entity sets, diamonds are relationships, ellipses
9are attributes, underlined ellipses are primary keys, the dashed ellipse is a
10derived attribute. A double line between an entity set and a relationship marks
11**total participation** (every instance of that entity set must participate); a
12single line marks partial participation.
13
14Two deliberate modeling decisions worth stating up front:
15
16- **No foreign keys appear in the diagram.** Connections between entity sets are
17 expressed as relationships, per the notation. Foreign-key columns appear only
18 in the relational model in [RelationalDesign](../P2-RelationalDesign/RelationalDesign.md).
19- **`Holds` and `Contains` are relationships, not entity sets.** Both are M:N and
20 both carry their own attributes, which is exactly what a Chen relationship is
21 for. They become tables (`holdings`, `watchlist_items`) only in P2.
22
23## Data requirements
24
25### Entity sets
26
27#### Users
28Registered participants of the platform. Every action in the simulation is
29attributed to a user, and the two balance attributes are what makes the
30simulation work: cash that is free to trade is tracked separately from cash that
31is currently committed to open positions, so the platform can refuse a purchase
32without having to recompute the whole portfolio first.
33
34- **Candidate keys:** `{id}`, `{username}`, `{email}`. Primary key: **`id`**.
35 A surrogate UUID was chosen because it is opaque and stable — `username` and
36 `email` are both things a user may legitimately want to change later, and
37 every relationship in the diagram points at `Users`, so a mutable key would
38 propagate changes across the whole database.
39- **Attributes:**
40 - `id` — UUID, required, primary key.
41 - `username` — text, max 50, required, unique.
42 - `email` — text, max 255, required, unique, must contain `@`.
43 - `full_name` — text, max 200, optional.
44 - `password_hash` — text, max 255, required. Never the password itself; the
45 prototype stores a SHA-256 hex digest.
46 - `available_balance` — numeric(18,4), required, default 0, must be ≥ 0.
47 - `invested_balance` — numeric(18,4), required, default 0, must be ≥ 0.
48 - `created_at` — timestamp with time zone, required, defaults to now.
49 - `updated_at` — timestamp with time zone, optional (null until first change).
50
51#### Cryptos
52The catalog of crypto assets the platform knows about. Kept separate from
53`Markets` because an asset exists independently of the pairs it is traded in —
54the same asset can be quoted against several currencies, and a user's holding is
55in the *asset*, not in a particular pair.
56
57- **Candidate keys:** `{id}`, `{symbol}`. Primary key: **`id`**, for the same
58 reason as in `Users`; `symbol` is kept as a unique natural key because that is
59 what users type and see.
60- **Attributes:**
61 - `id` — UUID, required, primary key.
62 - `symbol` — text, max 20, required, unique (e.g. `BTC`).
63 - `name` — text, max 255, required (e.g. `Bitcoin`).
64 - `created_at` — timestamptz, required, defaults to now.
65
66#### Markets
67A tradeable pair: one crypto asset quoted in one currency, e.g. BTC/USD. This is
68where prices live, and it is the thing an order is placed *on*. Modeled as its
69own entity set rather than an attribute of `Cryptos` because a market has its own
70lifecycle — it can be deactivated without deleting the asset — and because
71trades, candles and orders all reference the pair, not the asset.
72
73- **Candidate keys:** `{id}`, `{crypto_id, quote_currency}` — that pair is
74 unique by definition, since a given asset can only be quoted once per
75 currency. Primary key: **`id`**, so that the many entity sets referencing a
76 market carry one narrow column instead of a composite key.
77- **Attributes:**
78 - `id` — UUID, required, primary key.
79 - `quote_currency` — text, exactly 3 characters, required, default `USD`.
80 - `is_active` — boolean, required, default true. Inactive markets are hidden
81 from the trading menus but keep their history.
82 - `created_at` — timestamptz, required, defaults to now.
83
84#### Orders
85A user's instruction to buy or sell on a market. Needed as a separate entity set
86because an order is a record of *intent* that outlives its execution: it keeps
87the requested quantity and price even after it has been filled, which is what
88makes the ledger auditable.
89
90- **Candidate keys:** `{id}` only. There is no natural key — the same user can
91 place two identical orders on the same market in the same second, and both are
92 legitimately distinct. Primary key: **`id`**.
93- **Attributes:**
94 - `id` — UUID, required, primary key.
95 - `side` — text, required, restricted to `buy` or `sell`.
96 - `type` — text, required, restricted to `market` or `limit`. The prototype
97 executes only `market` orders; `limit` exists so the model does not have to
98 change when limit orders are implemented.
99 - `status` — text, required, restricted to `open`, `executed`, `cancelled`.
100 - `quantity` — numeric(20,4), required, must be > 0.
101 - `price` — numeric(18,6), optional — null for a market order until it fills,
102 then the fill price.
103 - `placed_at` — timestamptz, required, defaults to now.
104 - `executed_at` — timestamptz, optional, set when the order fills.
105
106#### Transactions
107The financial ledger: every movement of virtual cash, in one place. This exists
108so that a balance is never just a number someone edited — it is the sum of an
109auditable list of entries, which is also what the "explain every step" goal of
110the project needs.
111
112- **Candidate keys:** `{id}` only. Primary key: **`id`**.
113- **Attributes:**
114 - `id` — UUID, required, primary key.
115 - `type` — text, required, restricted to `deposit`, `buy`, `sell`, `fee`.
116 - `amount` — numeric(18,4), required. Signed: negative for money leaving the
117 cash balance, positive for money arriving.
118 - `currency` — text, exactly 3 characters, required, default `USD`.
119 - `created_at` — timestamptz, required, defaults to now.
120 - `description` — text, optional, free-form human-readable explanation.
121
122#### MarketTrades
123Individual executed trades on a market, from the user's own fills and from the
124market simulator. This is the single source of truth for the current price: the
125price of a market is the price of its most recent trade, never a column someone
126writes directly.
127
128- **Candidate keys:** `{id}`. In principle `{market_id, executed_at}` looks
129 unique, but two trades can share a timestamp, so it is not a safe key.
130 Primary key: **`id`** (a plain auto-incrementing integer here rather than a
131 UUID, because this is the highest-volume entity set and it is only ever read
132 in timestamp order, never referenced by anything else).
133- **Attributes:**
134 - `id` — integer, required, primary key, auto-generated.
135 - `executed_at` — timestamptz, required.
136 - `price` — numeric(18,6), required, must be > 0.
137 - `quantity` — numeric(20,6), required, must be > 0.
138 - `side` — text, optional, `buy` or `sell`.
139 - `source` — text, max 50, required, default `simulation`. Distinguishes a
140 simulated trade from a user's own fill (`user`).
141
142#### MarketCandles
143OHLCV aggregates per market and timeframe — the data a price chart is drawn
144from. Stored rather than computed on the fly because the point of the project is
145a chart-driven interface, and re-aggregating the whole trade history for every
146screen refresh does not scale.
147
148- **Candidate keys:** `{id}`, and `{market_id, timeframe, candle_time}` — a
149 market has exactly one candle per timeframe per time bucket. Primary key:
150 **`id`**; the composite is enforced as a uniqueness rule because it is the
151 real-world constraint and it is what prevents duplicate candles.
152- **Attributes:**
153 - `id` — integer, required, primary key, auto-generated.
154 - `timeframe` — text, required, restricted to `1m`, `5m`, `1h`, `1d`.
155 - `open`, `high`, `low`, `close` — numeric(18,6), all required.
156 - `volume` — numeric(20,6), required.
157 - `candle_time` — timestamptz, required — the start of the bucket.
158
159#### Watchlists
160A named list of assets a user wants to monitor. A separate entity set rather than
161a flag on the relationship between users and assets, because a user may want
162several lists ("long term", "watching today") and each needs its own name.
163
164- **Candidate keys:** `{id}`. `{user_id, name}` would also work if list names
165 are required to be unique per user; the model does not impose that, so it is
166 not listed as a candidate key. Primary key: **`id`**.
167- **Attributes:**
168 - `id` — UUID, required, primary key.
169 - `name` — text, max 100, required.
170 - `created_at` — timestamptz, required, defaults to now.
171
172### Relationships
173
174#### QuotedOn — Cryptos (1) : Markets (N), total on Markets
175Ties a market to the asset it trades. One asset can be quoted in many markets;
176every market must have exactly one asset, hence total participation on the
177`Markets` side. No attributes of its own.
178
179#### PlacedOn — Markets (1) : Orders (N), total on Orders
180Records which market an order was placed on. Every order must name a market;
181a market may have no orders yet. No attributes.
182
183#### Places — Users (1) : Orders (N), total on Orders
184Records who placed an order. Every order belongs to exactly one user; a new user
185has no orders. No attributes.
186
187#### Records — Users (1) : Transactions (N), total on Transactions
188Attributes each ledger entry to a user. Every entry belongs to exactly one user.
189No attributes.
190
191#### Settles — Orders (1) : Transactions (N), partial on both sides
192Links a ledger entry to the order that caused it. Partial on the `Transactions`
193side because deposits have no originating order, and partial on the `Orders` side
194because an order that never executes never produces a ledger entry. This is why
195the corresponding column is nullable in P2. No attributes.
196
197#### Fills — Markets (1) : MarketTrades (N), total on MarketTrades
198Every executed trade happened on exactly one market. No attributes.
199
200#### Aggregates — Markets (1) : MarketCandles (N), total on MarketCandles
201Every candle summarises trades of exactly one market. No attributes.
202
203#### Owns — Users (1) : Watchlists (N), total on Watchlists
204Every watchlist belongs to exactly one user. No attributes.
205
206#### Holds — Users (M) : Cryptos (N), partial on both sides, **with attributes**
207A user's position in an asset. M:N because one user holds many assets and one
208asset is held by many users, and partial on both sides because a user may hold
209nothing and an asset may be held by nobody. Modeled as a relationship rather
210than an entity set because a position has no identity of its own — it is
211entirely described by *which user*, *which asset*, and how much.
212
213- **Attributes:**
214 - `quantity` — numeric(20,4), required, must be ≥ 0.
215 - `avg_price` — numeric(18,6), required, ≥ 0, **derived** (dashed ellipse):
216 the weighted average of the prices at which the position was accumulated.
217 It is derivable from the buy history, and is stored anyway so that
218 unrealised P/L can be shown without replaying the whole ledger.
219 - `created_at` — timestamptz, required, defaults to now.
220 - `updated_at` — timestamptz, optional.
221
222#### Contains — Watchlists (M) : Cryptos (N), partial on both sides, **with attribute**
223Which assets are on which watchlist. M:N: a list holds many assets, an asset
224appears on many lists. Partial on both sides — an empty list is valid and an
225asset need not be on any list.
226
227- **Attributes:**
228 - `added_at` — timestamptz, required, defaults to now. Recorded so a list can
229 be shown in the order the user built it.
230
231## Entity-Relationship Model History
232
233- **v01** — First complete version. Built from the entity notes in
234 [`ep-diagram.md`](ep-diagram.md) (the initial hand-written model), with three
235 changes made to that initial model while drawing it:
236 1. `Markets` was promoted from an implied attribute of the asset to its own
237 entity set, so that prices, orders, trades and candles can all reference a
238 pair rather than an asset.
239 2. `holdings` and `watchlist_items` were re-expressed as the M:N relationships
240 `Holds` and `Contains` with their own attributes, instead of entity sets
241 with foreign keys — the initial notes listed them as tables, which is a
242 relational concept that does not belong in a Chen ERD.
243 3. `avg_price` was marked as a derived attribute rather than a plain one, to
244 make the denormalisation explicit rather than hidden.
245
246Reasoning for the AI-assisted part of this phase, and the full interaction log,
247are on [ERModelAIUsage](ERModelAIUsage.md).
Note: See TracBrowser for help on using the repository browser.