forked from NickAz123/stonks_back
/
server.js
365 lines (353 loc) · 10.8 KB
/
server.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
const Express = require("express");
const App = Express();
const BodyParser = require("body-parser");
const PORT = 8080;
require("dotenv").config();
const fs = require("fs");
const axios = require("axios");
const WebSocket = require("ws");
//Database connection configuration
const { Pool } = require("pg");
const dbParams = require("./lib/db.js");
const db = new Pool(dbParams);
// console.log(dbParams)
db.connect();
let socket = new WebSocket(`wss://ws.finnhub.io?token=${process.env.API_KEY}`);
// socket.addEventListener('open', function (event) {
// socket.send(JSON.stringify({'type':'subscribe', 'symbol': 'GOOG'}))
// socket.send(JSON.stringify({'type':'subscribe', 'symbol': 'AAPL'}))
// socket.send(JSON.stringify({'type':'subscribe', 'symbol': 'IC MARKETS:1'}))
// });
// // Listen for messages
// socket.addEventListener('message', function (event) {
// console.log('Message from server ', event.data);
// });
// Express Configuration
App.use(BodyParser.urlencoded({ extended: false }));
App.use(BodyParser.json());
App.use(Express.static("public"));
//DATABASE AND JSON REQUESTS
// Get Route for current logged in user
App.get("/api/users", (req, res) => {
db.query(`SELECT * FROM users WHERE id=1;`)
.then((data) => {
const users = data.rows;
res.json({ users });
})
.catch((err) => {
res.status(500).json({ error: err.message });
});
});
//Gets users owned stocks
App.get("/api/owned-stocks", (req, res) => {
db.query(`SELECT * FROM owned WHERE user_id=1`)
.then((data) => {
const owned = data.rows;
res.json({ owned });
})
.catch((err) => {
console.log(err);
});
});
//Get route for transactions for logged in user
App.get("/api/transactions", (req, res) => {
db.query(`SELECT * FROM transactions WHERE user_id=1;`)
.then((data) => {
const transactions = data.rows;
res.json({ transactions });
})
.catch((err) => {
res.status(500).json({ error: err.message });
});
});
//Get route for current logged in user tutorial history
App.get("/api/tutorials", (req, res) => {
db.query(`SELECT * FROM tutorials WHERE user_id=1;`)
.then((data) => {
const tutorials = data.rows;
res.json({ tutorials });
})
.catch((err) => {
res.status(500).json({ error: err.message });
});
});
//Get route for entire stock list
App.get("/api/all-stocks", (req, res) => {
let allstocks = fs.readFileSync("nyse_full_tickers.json");
let stocks = JSON.parse(allstocks);
//Seperates the unregistered stocks
stocks.forEach((stock, index) => {
if (stock.symbol.includes("^")) {
stocks.splice(index, 1);
}
});
res.json({ stocks });
});
//Post route for buying a stock
App.post(`/api/buy-stock`, (req, res) => {
const obj = req.body;
return db
.query(
`INSERT INTO transactions (user_id, cost, shares, type, symbol)
VALUES(1, ${obj.cost}, ${obj.amount}, ${obj.type}, '${obj.symbol}');`
)
.then(() => {
return db
.query(
`SELECT * FROM owned WHERE user_id = 1 AND symbol = '${obj.symbol}';`
)
.then((data) => {
if (data.rows.length === 0) {
return db.query(
`INSERT INTO owned (user_id, symbol, amount) VALUES(1, '${obj.symbol}', ${obj.amount});`
);
} else {
return db.query(
`UPDATE owned SET amount = ${
parseFloat(obj.amount) + parseFloat(data.rows[0].amount)
} WHERE symbol = '${obj.symbol}' AND user_id = 1`
);
}
})
.then(() => {
return db
.query(`SELECT * FROM users WHERE id = 1;`)
.then((data) => {
return db.query(
`UPDATE users SET balance = ${
parseFloat(data.rows[0].balance) -
parseFloat(obj.amount) * parseFloat(obj.cost)
} WHERE id = 1;`
);
})
.then(() => {
res.json({ completed: true });
});
});
});
});
//Post route for selling a stock
App.post(`/api/sell-stock`, (req, res) => {
const obj = req.body;
let finalAmount;
return db
.query(
`INSERT INTO transactions (user_id, cost, shares, type, symbol)
VALUES(1, ${obj.cost}, ${obj.amount}, ${obj.type}, '${obj.symbol}');`
)
.then(() => {
return db
.query(
`SELECT * FROM owned WHERE user_id = 1 AND symbol = '${obj.symbol}';`
)
.then((data) => {
finalAmount = data.rows[0].amount - obj.amount;
if (finalAmount > 0) {
finalAmount = obj.amount;
return db.query(
`UPDATE owned SET amount = ${
parseFloat(data.rows[0].amount) - parseFloat(obj.amount)
} WHERE symbol = '${obj.symbol}' AND user_id = 1;`
);
} else {
finalAmount = parseFloat(data.rows[0].amount);
return db.query(
`DELETE FROM owned WHERE symbol = '${obj.symbol}' AND user_id = 1;`
);
}
})
.then(() => {
return db.query(`SELECT * FROM users WHERE id = 1`).then((data) => {
return db
.query(
`UPDATE users SET balance = ${
parseFloat(data.rows[0].balance) +
finalAmount * parseFloat(obj.cost)
};`
)
.then(() => {
res.json({ completed: true });
});
});
});
});
});
// Post request for updating completed tutorials
App.post('/api/complete-tutorial/:column', (req, res) => {
db.query(`UPDATE tutorials SET ${req.params.column} = true WHERE user_id = 1;`).then(() => {
db.query(`SELECT * FROM tutorials WHERE user_id = 1;`).then((data)=> {
const tutorials = data.rows;
res.json({ tutorials });
})
}).catch((err) => {
console.log(err)
})
})
//Get request for btc history
App.get('/api/get-btc', (req, res) => {
let history = fs.readFileSync("btc_1month.json");
let btc = JSON.parse(history);
let element = btc
res.json({element})
})
//FINNHUB API REQUESTS
//Get Route for Todays News
App.get("/api/all-news", (req, res) => {
axios
.get(
`https://finnhub.io/api/v1/news?category=general&token=${process.env.API_KEY}`
)
.then((news) => {
const allnews = news.data.slice(0, 10);
res.json({ allnews });
});
});
//Get prices for selected ticker
App.get(`/api/ticker-prices/:ticker`, (req, res) => {
axios
.get(
`https://finnhub.io/api/v1/quote?symbol=${req.params.ticker}&token=${process.env.API_KEY}`
)
.then((prices) => {
const allprices = prices.data;
res.json({ allprices });
})
.catch((err) => {
console.log(err);
});
});
//COINMARKET CRYPTO API REQUESTS
//Gets all crypto
const urlc = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=${process.env.CRYPTO_API}`;
App.get(`/api/crypto-all`, (req, res) => {
axios
.get(urlc)
.then((crypto) => {
const allcrypto = crypto.data.data;
res.json({ allcrypto });
})
.catch((err) => {
console.log(err);
});
});
//ALPHAVANTAGE API REQUESTS
//Get Company Data for specified ticker
App.get(`/api/company-data/:ticker`, (req, res) => {
axios
.get(
`https://www.alphavantage.co/query?function=OVERVIEW&symbol=${req.params.ticker}&apikey=${process.env.YAHOO_KEY}`
)
.then((data) => {
const companyData = data.data;
res.json({ companyData });
})
.catch((err) => {
console.log(err);
});
});
//Get 2 year history for specific ticker
App.get(`/api/all-history/:ticker`, (req, res) => {
axios
.get(
`https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY_ADJUSTED&symbol=${req.params.ticker}&apikey=${process.env.YAHOO_KEY}`
)
.then((history) => {
if (!history.data["Weekly Adjusted Time Series"]) {
let file = JSON.parse(fs.readFileSync("all_history.json"));
console.log("all history JSON sent")
res.json(file);
} else {
resultsObj = {};
const allhistory = history.data["Weekly Adjusted Time Series"];
for (const [key, value] of Object.entries(allhistory)) {
if (key.slice(0, 4) === "2019") {
break;
} else {
resultsObj[key] = value;
}
}
console.log("all history api triggered")
res.json(resultsObj);
}
})
.catch((err) => {
console.log(err);
});
});
// Get 30 day history for specific ticker
App.get(`/api/30-history/:ticker`, (req, res) => {
axios
.get(
`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${req.params.ticker}&outputsize=compact&apikey=${process.env.YAHOO_KEY}`
)
.then((history) => {
if (!history.data["Time Series (Daily)"]) {
let file = JSON.parse(fs.readFileSync('30_history.json'))
console.log("30 day json triggered")
res.json(file)
} else {
resultsObj = {};
let index = 0;
const allhistory = history.data["Time Series (Daily)"];
for (const [key, value] of Object.entries(allhistory)) {
if (index === 30) {
break;
} else {
resultsObj[key] = value;
index++;
}
}
console.log("30 day api triggered")
res.json(resultsObj);
index = 0;
}
})
.catch((err) => {
console.log(err);
});
});
//Get a full day resolution 5 min intervals for specific ticker
App.get(`/api/oneday-history/:ticker`, (req, res) => {
axios
.get(
`https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${req.params.ticker}&interval=5min&apikey=${process.env.YAHOO_KEY}`
)
.then((history) => {
if (!history.data["Time Series (5min)"]) {
let file = JSON.parse(fs.readFileSync('one_day_history.json'))
console.log("one day json triggered")
res.json(file)
} else {
console.log("one day api triggered")
res.json(history.data["Time Series (5min)"]);
}
})
.catch((err) => {
console.log(err);
});
});
//POLYGON.IO API REQUESTS
//News for specific ticker
App.get("/api/single-news/:ticker", (req, res) => {
axios
.get(
`https://api.polygon.io/v2/reference/news?limit=10&order=descending&sort=published_utc&ticker=${req.params.ticker}&published_utc.gte=2021-04-26&apiKey=${process.env.POLY_API}`
)
.then((news) => {
if (news.data.length = 0)
{
let cryptonews = fs.readFileSync("btc_news.json");
let btcnews = JSON.parse(cryptonews);
res.json(btcnews)
} else {
const results = news.data;
res.json(results);
}
});
});
//APP LISTEN
App.listen(PORT, () => {
console.log(
`Express seems to be listening on port ${PORT} so that's pretty good 👍`
);
});