-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
340 lines (318 loc) · 8.66 KB
/
db.js
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
var crypto = require("crypto");
const { v4: uuidv4 } = require("uuid");
const yahooFinance = require("yahoo-finance");
const Person = require("./models/person");
/**
* Creates a new person in the database.
* @param {*} username
* @param {*} password
* @param {*} callback (err: true | false)
*/
module.exports.createPerson = (username, password, callback) => {
// create person
let hashedPassword = hash(password);
let newPerson = new Person({
username,
password: hashedPassword,
});
newPerson
.save()
.then((d) => callback(null))
.catch((err) => callback(err));
};
/**
* Is the username/password combo correct.
* @param {*} username
* @param {*} password
* @param {*} callback (err, isCorrect: boolean)
*/
module.exports.passwordIsCorrect = (username, password, callback) => {
Person.findOne({ username }, (err, doc) => {
if (err) {
callback(err, null);
} else {
if (!doc) {
callback(err, null);
} else {
let passwordCorrect = doc.password;
if (hash(password) == passwordCorrect) {
callback(null, true);
} else {
callback(null, false);
}
}
}
});
};
/**
* Complete the selling of holdings:
* - find the total of the amount of money the shares are worth
* - remove them from the holdings
* - add new sell transaction to the list
* - add the money to the account balance
* @param {*} username
* List of Order Ids of the holdings they want to sell:
* @param {*} listOfSellingOrderIds = ['40ac7bd7-31ca-430c-b894-d91117c03b30','bca354dd-3bcc-468d-bac3-723af394276e',...]
* @param {*} callback = function(err)
*/
module.exports.completeSelling = async (
username,
listOfSellingOrderIds,
callback,
) => {
if (!listOfSellingOrderIds || !(listOfSellingOrderIds.length >= 1)) {
callback("ERROR: No selling options selected.");
return;
}
Person.findOne({ username }, async (err, doc) => {
if (err) {
console.log(err);
callback(err);
} else {
let { totalSellingPrice, holdingsToSell } = await getTotalSellingPrice(
doc.holdings,
listOfSellingOrderIds,
);
let newMoney = doc.money + totalSellingPrice;
// update money and transactions
Person.updateOne(
{ username },
{
money: newMoney,
$push: {
transactions: { transactionType: "sell", stocks: holdingsToSell },
},
},
(err, affected, resp) => {
if (err) {
console.log(err);
callback(err);
} else {
// remove holdings
Person.updateOne(
{ username },
{
$pull: {
holdings: { orderId: { $in: listOfSellingOrderIds } },
},
},
(err, doc) => {
if (err) {
console.log(err);
callback(err);
} else {
callback(null);
}
},
);
}
},
);
}
});
};
/**
* Takes a person's cart and
* - adds cart to holdings
* - subtracts total amount from the person's money
* - update TRANSACTIONS
* @param {*} username
* @param {*} cart -- already has the cart[i].currentPriceOfOneShare
* @param {*} callback(err)
*/
module.exports.completePurchase = (username, cart, totalPrice, callback) => {
Person.updateOne(
{ username },
{
$inc: { money: -totalPrice },
$addToSet: { holdings: { $each: cart } },
$push: { transactions: { transactionType: "buy", stocks: cart } },
},
(err, doc) => {
if (err) {
console.log(err);
callback(err);
} else {
callback(null);
}
},
);
};
/**
* Send back person given a username.
* Add the current stock prices to their holdings.
* @param {*} username
* @param {*} callback (err, person)
*/
module.exports.getPerson = (username, callback) => {
Person.findOne({ username }, async (err, doc) => {
if (err) {
callback(err, null);
} else {
let person = doc;
// set current prices
for (let i = 0; i < person.holdings.length; i++) {
try {
person.holdings[i].currentPriceOfOneShare = (
await getQuote(person.holdings[i].ticker)
).toFixed(2);
} catch (err) {
console.log(err);
person.holdings[i].currentPriceOfOneShare = 0;
}
}
callback(null, person);
}
});
};
/**
* Add/subtract balance.
* If the new balance will be negative, set it to zero.
* @param {*} username
* @param {*} addOrSubtract
* @param {*} amount
* @param {*} callback(err)
*/
module.exports.addOrSubtractMoney = (
username,
addOrSubtract,
amount,
callback,
) => {
// set amount to negative if subtracting
if (addOrSubtract == "subtract") {
amount = -amount;
}
Person.updateOne(
{ username },
{
$inc: { money: amount },
},
(err, doc) => {
if (err) {
callback(err);
} else {
callback(null);
}
},
);
};
function hash(text) {
return crypto.createHash("sha512").update(text).digest("hex");
}
// callback (err, price)
// can be promises or callbacks
function getQuote(ticker, callback = null) {
if (callback) {
yahooFinance.quote(
{ symbol: ticker, modules: ["price"] },
(err, quotes) => {
let price = quotes.price.regularMarketPrice;
if (err) {
console.log(err);
callback(err, null);
} else {
callback(null, price);
}
},
);
} else {
return new Promise((resolve, reject) => {
yahooFinance.quote(
{ symbol: ticker, modules: ["price"] },
(err, quotes) => {
if (err) {
console.log(err);
reject(err);
} else {
let price = quotes.price.regularMarketPrice;
resolve(price);
}
},
);
});
}
}
/**
* Function is started when the server starts up.
* Goes through each person and checks if their limit or stop holdings are done.
* If so, they sell the shares.
*/
module.exports.searchForLimitOrStopOrders = () => {
let checkEvery = 1000 * 4; // check every 4 seconds
setInterval(async () => {
console.log("checking...");
// go through all holdings of each person.
Person.find({}, async (err, docs) => {
if (err) {
console.log(err);
return;
}
// TODO: fix this crude way of doing it.
let database = docs;
for (let i = 0; i < database.length; i++) {
for (let j = 0; j < database[i].holdings.length; j++) {
const order = database[i].holdings[j];
const currentPriceOfOneShare = await getQuote(order.ticker);
if (order.limit) {
// this is a limit order
if (currentPriceOfOneShare >= order.limit) {
// sell the stock
this.completeSelling(
database[i].username,
[order.orderId],
(err) => {
if (err) {
console.log(err);
console.log("^^^Error in checking for limit order^^^");
} else {
console.log("sold limit order!");
}
},
);
}
} else if (order.stop) {
// this is a stop order
if (currentPriceOfOneShare <= order.stop) {
// sell the stock
this.completeSelling(
database[i].username,
[order.orderId],
(err) => {
if (err) {
console.log(err);
console.log("^^^Error in checking for stop order^^^");
} else {
console.log("sold stop order!");
}
},
);
}
}
}
}
});
}, checkEvery);
};
async function getTotalSellingPrice(holdings, listOfSellingOrderIds) {
// get total price
let holdingsToSell = holdings.filter((order) =>
listOfSellingOrderIds.includes(order.orderId),
);
// get current prices
for (let j = 0; j < holdingsToSell.length; j++) {
holdingsToSell[j].currentPriceOfOneShare = await getQuote(
holdingsToSell[j].ticker,
);
}
// console.log("---------------\nHoldings to sell\n\n\n");
// console.log(holdingsToSell);
// console.log("---------------\nHoldings to sell\n\n\n");
// set total price
let totalSellingPrice = 0;
holdingsToSell.map((order) => {
totalSellingPrice += order.currentPriceOfOneShare * order.quantity;
return "";
});
return { totalSellingPrice, holdingsToSell };
}