-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmarket.js
More file actions
291 lines (255 loc) · 10.1 KB
/
market.js
File metadata and controls
291 lines (255 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
// ┃ Copyright (c) 2017, the Perspective Authors. ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃ This file is part of the Perspective library, distributed under the terms ┃
// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
import "/node_modules/@perspective-dev/viewer/dist/cdn/perspective-viewer.js";
import "/node_modules/@perspective-dev/viewer-datagrid/dist/cdn/perspective-viewer-datagrid.js";
import "/node_modules/@perspective-dev/viewer-d3fc/dist/cdn/perspective-viewer-d3fc.js";
import perspective from "/node_modules/@perspective-dev/client/dist/cdn/perspective.js";
const MSG_BATCH_TIMEOUT = 50;
const MSG_PER_BATCH = 10;
const MSG_TIME_DELTA = 20 * (100 / MSG_PER_BATCH);
const MARKET_OPEN_PRICE = 20;
const MARKET_MAX_TRADES = 20000;
const MARKET_MIN_TRADES = 5000;
const MARKET_OPEN = performance.now();
const TRADE_EXPIRATION = 10;
const SCHEMA = {
id: "integer",
side: "string",
security: "string",
price: "float",
timestamp: "datetime",
status: "string",
};
async function query_columns(table, config) {
const view = await table.view(config);
const columns = await view.to_columns();
await view.delete();
return columns;
}
class OrderBook {
constructor(table, side) {
this._memo = undefined;
this._side = side;
this._table = table;
this._price_view = table.view({
columns: ["price"],
group_by: ["security"],
aggregates: { price: side === "buy" ? "max" : "min" },
filter: [
["side", "==", side],
["status", "==", "open"],
],
});
}
async best_open_price() {
if (this._memo === undefined) {
const view = await this._price_view;
const { price } = await view.to_columns({ leaves_only: true });
this._memo = price.length === 0 ? MARKET_OPEN_PRICE : price[0];
}
return this._memo;
}
async matched_orders(price) {
const sort_dir = this._side === "buy" ? "desc" : "asc";
const op = this._side === "buy" ? ">" : "<";
return await query_columns(this._table, {
columns: ["id"],
filter: [
["side", "==", this._side],
["status", "==", "open"],
["price", op, price],
],
sort: [
["price", sort_dir],
["timestamp", "asc"],
],
});
}
reset() {
this._memo = undefined;
}
}
class Channel {
async consume() {
await new Promise((resolve) => {
this._resolve = resolve;
});
}
emit() {
if (this._resolve) {
this._resolve();
this._resolve = undefined;
}
}
}
class Market {
constructor(table, model) {
this._id = 1;
this._table = table;
this._model = model;
this._buy_book = new OrderBook(table, "buy");
this._sell_book = new OrderBook(table, "sell");
this._stop_signal = new Channel();
}
async stop() {
if (this._id < MARKET_MAX_TRADES) {
this._id = MARKET_MAX_TRADES;
await this._stop_signal.consume();
}
this._id = 1;
}
async poll(progress) {
await this._run_market_step();
while (this._id < MARKET_MIN_TRADES) {
await this._run_market_step(progress);
}
progress?.();
this._stop_signal.emit();
if (this._id < MARKET_MAX_TRADES) {
setTimeout(this.poll.bind(this), MSG_BATCH_TIMEOUT);
}
}
async _run_market_step(progress) {
if (await this._generate_trades()) {
await this._clear_trades();
await this._expire_trades();
}
this._buy_book.reset();
this._sell_book.reset();
progress?.(this._id / MARKET_MIN_TRADES);
}
async _generate_trades() {
const trades = [];
const timestamp = new Date(MARKET_OPEN + this._id * MSG_TIME_DELTA);
for (let i = 0; i < MSG_PER_BATCH; i++) {
const { side, discount } = this._model();
const book = side === "buy" ? this._sell_book : this._buy_book;
const best_open_price = await book.best_open_price();
trades.push({
security: "Prospective Co",
status: "open",
id: this._id++,
price: discount + best_open_price,
side,
timestamp,
});
}
if (trades.length > 0) {
await this._table.update(trades);
return true;
}
}
async _clear_trades() {
const sell_price = await this._sell_book.best_open_price();
const buy_price = await this._buy_book.best_open_price();
const { id: buys } = await this._buy_book.matched_orders(sell_price);
const { id: sells } = await this._sell_book.matched_orders(buy_price);
const num_clear = Math.min(buys.length, sells.length);
const status = Array(num_clear * 2).fill("closed");
const id = buys.slice(0, num_clear).concat(sells.slice(0, num_clear));
if (id.length > 0) {
await this._table.update({ status, id });
}
}
async _expire_trades() {
const expired = await query_columns(this._table, {
columns: ["id"],
filter: [
["status", "==", "open"],
["id", "<", this._id - MSG_PER_BATCH * TRADE_EXPIRATION],
],
});
if (expired.id.length > 0) {
expired.status = Array(expired.id.length).fill("expired");
await this._table.update(expired);
}
}
}
const SKEW_MODEL_OFFSET = 2;
const SKEW_MODEL_STDDEV = 2;
const SKEW_MODEL_SKEW = 0;
function random_skew_normal(bias) {
const u3 = Math.random(),
u2 = Math.random();
const R = Math.sqrt(-2.0 * Math.log(u3));
const O = 2.0 * Math.PI * u2;
const u0 = R * Math.cos(O);
const v = R * Math.sin(O);
if (SKEW_MODEL_SKEW === 0) {
return bias * SKEW_MODEL_OFFSET + SKEW_MODEL_STDDEV * u0;
} else {
const n = -bias * SKEW_MODEL_SKEW;
const s = n / Math.sqrt(1 + Math.pow(SKEW_MODEL_SKEW, 2));
const u1 = s * u0 + Math.sqrt(1 - s * s) * v;
const z = u0 >= 0 ? u1 : -u1;
return bias * SKEW_MODEL_OFFSET + SKEW_MODEL_STDDEV * z;
}
}
function skew_model() {
const [side, bias] = Math.random() > 0.5 ? ["buy", -1] : ["sell", 1];
const discount = random_skew_normal(bias);
return { side, discount };
}
function progress(x) {
const button = document.querySelector("button");
if (x !== undefined) {
const y = (x * 10).toFixed(0) * 10;
button.textContent = `Generating trades ${y}%`;
} else {
button.textContent = "Reset";
}
}
async function reset_tables(market, market_table, gui_table) {
await market.stop();
await gui_table.size();
await market_table.clear();
await gui_table.clear();
await market.poll(progress);
}
async function init_tables() {
const market_worker = await perspective.worker();
const gui_worker = await perspective.worker();
const market_table = await market_worker.table(SCHEMA, { index: "id" });
const market_view = await market_table.view();
const gui_table = await gui_worker.table(market_view, {
index: "id",
name: "gui",
});
return { market_table, gui_table };
}
async function init_layouts() {
const req = await fetch("layouts.json");
return await req.json();
}
const INIT_TASK = [init_tables(), init_layouts()];
const [{ market_table, gui_table }, layouts] = await Promise.all(INIT_TASK);
const market = new Market(market_table, skew_model);
const settings = !/(iPad|iPhone|iPod)/g.test(navigator.userAgent);
const select = document.querySelector("select");
const button = document.querySelector("button");
const viewer = document.querySelector("perspective-viewer");
viewer.load(gui_table);
viewer.restore({ theme: "Pro Dark", table: "gui", settings, ...layouts[0] });
await market.poll(progress);
for (const layout of layouts) {
const option = document.createElement("option");
option.value = layout.title;
option.textContent = layout.title;
select.appendChild(option);
}
button.addEventListener("click", () => {
reset_tables(market, market_table, gui_table);
});
select.addEventListener("change", async (event) => {
const layout = layouts.find((x) => x.title === event.target.value);
await viewer.restore(layout);
});