-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
53 lines (41 loc) · 1.29 KB
/
server.ts
File metadata and controls
53 lines (41 loc) · 1.29 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
import express from "express";
import { v4 as uuid } from "uuid";
import Database from "better-sqlite3";
const app = express();
app.use(express.json());
const db = new Database("orders.db");
db.prepare(
"CREATE TABLE IF NOT EXISTS orders (id TEXT, side TEXT, price REAL, quantity REAL, status TEXT)"
).run();
app.post("/orders",(req,res)=>{
const side=req.body.side;
const price=req.body.price;
const quantity=req.body.quantity;
if(!side||!price||!quantity){
res.status(400).json({error:"invalid input"});
return;
}
const id=uuid();
const status="OPEN";
db.prepare(
"INSERT INTO orders VALUES (?,?,?,?,?)"
).run(id,side,price,quantity,status);
let match;
if(side==="BUY"){
match=db.prepare(
"SELECT * FROM orders WHERE side='SELL' AND status='OPEN' AND price<=? ORDER BY price ASC LIMIT 1"
).get(price);
}else{
match=db.prepare(
"SELECT * FROM orders WHERE side='BUY' AND status='OPEN' AND price>=? ORDER BY price DESC LIMIT 1"
).get(price);
}
if(match){
db.prepare("UPDATE orders SET status='FILLED' WHERE id=?").run(id);
db.prepare("UPDATE orders SET status='FILLED' WHERE id=?").run(match.id);
}
res.json({orderId:id,status:match?"FILLED":"OPEN"});
});
app.listen(3000,()=>{
console.log("server running on 3000");
});