-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
595 lines (489 loc) · 18.5 KB
/
api.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const unirest = require("unirest");
const regression = require('regression');
app = express();
app.use(express.static('public')); //enable all CORS requests
app.use(bodyParser.urlencoded({ extended: true })); //enable POST requests
let COMMAND = process.argv;
if (!fs.existsSync("data")) {
fs.mkdirSync("data");
}
const server = app.listen(3000, () => {
const init = () => {
for (const c of COMMAND) {
console.log(c);
if (c === "live") {
DEBUG = false;
console.log('\x1b[31m%s\x1b[0m', 'YOU ARE TRADING WITH REAL CURRENCY');
console.log('\x1b[33m%s\x1b[0m', 'http://localhost:3000');
} else if (c === "test" || c === "debug") {
DEBUG = true;
console.log('\x1b[33m%s\x1b[0m', 'YOU ARE TRADING WITH PAPER CURRENCY');
console.log('\x1b[33m%s\x1b[0m', 'http://localhost:3000');
}
}
POLYGON_KEY = CONFIG.polygon.apiKey;
const { apiKey, secretKey, baseUrl } = DEBUG ? CONFIG.alpaca.paper : CONFIG.alpaca.live;
CLIENT_ID = apiKey;
CLIENT_SECRET = secretKey;
BASE_URL = baseUrl;
};
init();
});
const storeData = (data, path) => {
try {
fs.writeFileSync(path, JSON.stringify(data))
} catch (err) {
console.error(err)
}
}
const loadData = (path) => {
try {
return fs.readFileSync(path, 'utf8')
} catch (err) {
console.error(err)
return false;
}
}
const CONFIG = JSON.parse(loadData("config.json")); //API keys and stuff
let DEBUG;
let CLIENT_ID;
let CLIENT_SECRET;
let BASE_URL;
const map = function (n, start1, stop1, start2, stop2) {
return ((n - start1) / (stop1 - start1)) * (stop2 - start2) + start2;
};
/*****************************************************************
* API: Alpaca
* Description: Returns status about the active acocount
* Last Modified: 2023-02-09
* Usage: localhost:3000/account
*****************************************************************/
app.get('/account', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
unirest.get(`${BASE_URL}/v2/account`)
.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
})
.then(res => {
const { body } = res;
delete body.id;
delete body.account_number;
delete body.created_at;
response.send(body);
});
});
/*****************************************************************
* API: Alpaca
* Description: Returns all of today's trading activity.
* Last Modified: 2023-02-09
* Usage: localhost:3000/account/activity
*****************************************************************/
app.get('/account/activity', (request, response) => {
let date = new Date();
let today = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().slice(0, 10);
unirest.get(`${BASE_URL}/v2/account/activities?date=` + today)
.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
})
.end((res) => {
response.send(res.body);
});
});
/*****************************************************************
* API: Polygon
* Description: 1. Returns market status of open or closed
* 2. MADE OBSOLETE BY localhost:3000/clock
* Last Modified: 2023-02-09
* Usage: localhost:3000/marketstatus
*****************************************************************/
// app.get('/marketstatus', (request, response) => {
// console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
// let url = CONFIG.polygon.baseUrl + "/v1/marketstatus/now";
// let req = unirest("GET", url);
// req.query({
// "apiKey": POLYGON_KEY
// }).then((res) => {
// if (res == undefined) {
// console.log('\x1b[31m%s\x1b[0m', res);
// response.send({ "market": "error" });
// } else {
// response.send(res.body);
// }
// });
// });
/*****************************************************************
* API: Alpaca
* Description: 1. Returns an object with an "is_open" property.
* Documentation: https://alpaca.markets/docs/api-documentation/api-v2/clock
* Last Modified: 2023-02-09
* Usage: localhost:3000/clock
*****************************************************************/
app.get('/clock', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
unirest.get(`${BASE_URL}/v2/clock`)
.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
})
.then(res => response.send(res.body));
});
/*****************************************************************
* API: Alpaca
* Description: 1. Returns an array of every asset that can be traded on Alapca.
* 2. Saves an array of all tradable stock symbols as /data/symbols.json.
* Documentation: https://alpaca.markets/docs/api-documentation/api-v2/assets/
* Last Modified: 2023-02-09
* Usage: localhost:3000/assets
*****************************************************************/
app.get('/assets', (request, response) => {
console.log(request.url, new Date().toLocaleString());
let url = BASE_URL + "/v2/assets";
let req = unirest("GET", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).then((res) => {
let assets = res.body.filter(asset => asset.tradable);
let symbols = [];
assets.forEach(asset => { symbols.push(asset.symbol); });
storeData(symbols, "data/symbols.json");
response.send(assets);
});
});
app.get('/bracket/:symbol/:quantity/:stopLoss/:takeProfit', (request, response) => {
console.log('\x1b[32m%s\x1b[0m', request.url, new Date().toLocaleString());
const symbol = request.params.symbol;
const quantity = request.params.quantity;
const stopLoss = request.params.stopLoss;
const takeProfit = request.params.takeProfit;
let url = BASE_URL + "/v2/orders";
let req = unirest("POST", url);
let order = JSON.stringify({
"side": "buy",
"symbol": symbol,
"type": "market",
"qty": quantity,
"time_in_force": "day",
"order_class": "bracket",
"take_profit": {
"limit_price": takeProfit
},
"stop_loss": {
"stop_price": stopLoss
}
});
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).send(order).then((res) => {
response.send(res.body);
});
});
app.get('/buy/:symbol/:quantity', (request, response) => {
console.log('\x1b[32m%s\x1b[0m', request.url, new Date().toLocaleString());
const symbol = request.params.symbol;
const quantity = parseInt(request.params.quantity);
let url = BASE_URL + "/v2/orders";
let req = unirest("POST", url);
let order = JSON.stringify({
"symbol": symbol,
"qty": quantity,
"side": "buy",
"type": "market",
"time_in_force": "day"
});
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).send(order).then((res) => {
response.send(res.body);
});
});
app.get('/delete/:id', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let id = request.params.id;
let url = BASE_URL + "/v2/orders/11e8062e-c840-4490-b1ea-ea4b235cfd2f";
let req = unirest("DELETE", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).query({}).then(res => {
response.send(res);
});
});
/**
* Last Modified: 2023-02-09
* Usage: localhost:3000/assets
*/
app.get('/history/debug', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let rawResponse = fs.readFileSync("data/schema.json");
let parsedResponse = JSON.parse(rawResponse);
response.send(parsedResponse);
});
app.get('/history/erase', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let rawdata = fs.readFileSync("data/symbols.json");
let parsed = JSON.parse(rawdata);
const buildSchema = (arrIn) => {
let arrOut = [];
arrIn.forEach(e => {
let obj = {
symbol: e,
price: "",
todaysChangePerc: "",
c: [],
cQuadratic: "",
cR2: "",
cROC: "",
t: [],
v: [],
vQuadratic: "",
vR2: "",
vROC: "",
};
arrOut.push(obj);
});
return arrOut;
}
try {
let processed = buildSchema(parsed);
fs.writeFileSync("data/schema.json", JSON.stringify(processed));
response.status(204).end();
} catch (err) {
console.error(err);
response.status(500).end();
}
});
app.get('/history/save', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let timestamp = new Date().getTime();
let history = fs.readFileSync("data/schema.json");
let parsedJSON = JSON.parse(history);
try {
fs.writeFileSync("data\\" + timestamp + ".json", JSON.stringify(parsedJSON));
response.status(204).end();
} catch (err) {
console.error(err);
response.status(500).end();
}
});
/**********************************************************************************************
* API: Polygon
* Description: !!!THE POLYGON API IS NO LONGER FREE AND THIS FUNCTION IS BROKEN!!!
* Step 1. Get updated data on all tickers. Load the schema. Parse both to JSON.
* Step 2a. Push the most current high, low, open, close, volume and time to the schema arrays.
* Step 2b. If the array is greater than maxSize, shift the array.
* Step 3a. Get the min-max of the closing price and unix time of every stock.
* Step 3b. Normalize the close array and time aray between 0 and 1.
* Step 3c. Conduct a polynomial regression of all points.
* Step 4. Write the updated schema to json file.
* Step 5. Send the updated schema as a response.
**********************************************************************************************/
app.get('/history/update', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let rawSchema = fs.readFileSync("data/schema.json");
let parsedSchema = JSON.parse(rawSchema);
const maxSize = 60;
let url = CONFIG.polygon.baseUrl + "/v2/snapshot/locale/us/markets/stocks/tickers";
let req = unirest("GET", url);
req.query({
"apiKey": CLIENT_ID
}).then((res) => {
for (let i = res.body.tickers.length - 1; i >= 0; i--) {
let a = res.body.tickers[i];
let price = a['min']['c'];
let time = a["updated"];
let volume = a['min']['v'];
for (let j = parsedSchema.length - 1; j >= 0; j--) {
let b = parsedSchema[j];
if (b.symbol == a.ticker && price !== 0 && time !== 0 && volume !== 0) {
//Today's Change Percentage
b.todaysChangePerc = a.todaysChangePerc;
//Current Price
b.price = a.lastTrade.p;
//Last closing price
b['c'].push(price);
if (b['c'].length > maxSize) {
b['c'].shift();
}
//Time
b['t'].push(time);
if (b['t'].length > maxSize) {
b['t'].shift();
}
//Volume
b['v'].push(volume);
if (b['v'].length > maxSize) {
b['v'].shift();
}
break;
}
}
}
try {
fs.writeFileSync("data\\schema.json", JSON.stringify(parsedSchema));
response.status(204).end();
} catch (err) {
console.error(err);
response.status(500).end();
}
});
});
app.get('/orders', (request, response) => {
console.log(request.url, new Date().toLocaleString());
let url = BASE_URL + "/v2/orders";
let req = unirest("GET", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).then(res => {
let filtered = [];
for (element of res.body) {
filtered.push({
qty: element.qty,
symbol: element.symbol,
side: element.side,
created_at: element.created_at,
id: element.id,
asset_id: element.asset_id,
});
}
response.send(filtered);
});
});
app.get('/portfolio/history', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let url = BASE_URL + "/v2/account/portfolio/history";
let req = unirest("GET", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).then((res) => {
response.send(res.body);
});
});
app.get('/positions', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let url = BASE_URL + "/v2/positions";
let req = unirest("GET", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).then(res => {
return res;
}).then(res => {
for (e of res.body) {
e['avg_entry_price'] = parseFloat(e['avg_entry_price']).toFixed(2);
e['unrealized_plpc'] = parseFloat(e['unrealized_pl']).toFixed(2);
delete e['side'];
delete e['asset_id'];
delete e['asset_class'];
delete e['change_today'];
delete e['exchange'];
delete e['unrealized_pl'];
delete e['lastday_price'];
delete e['unrealized_intraday_pl'];
delete e['unrealized_intraday_plpc'];
delete e['current_price'];
delete e['avg_entry_price'];
delete e['cost_basis'];
}
response.send(res.body)
});
});
app.get('/sell/:symbol', (request, response) => {
console.log('\x1b[32m%s\x1b[0m', request.url, new Date().toLocaleString());
const symbol = request.params.symbol;
let url = BASE_URL + "/v2/positions/" + symbol;
let req = unirest("DELETE", url);
req.headers({
"APCA-API-KEY-ID": CLIENT_ID,
"APCA-API-SECRET-KEY": CLIENT_SECRET
}).then((res) => {
response.send(res.body);
});
});
/*****************************************************************
* API: Polygon
* Description: An array of raw tickers data for ALL stock symbols
*****************************************************************/
app.get('/tickers/debug', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
var date = new Date(); // Or the date you'd like converted.
let today = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().slice(0, 10);
let url = CONFIG.polygon.baseUrl + "/v2/snapshot/locale/us/markets/stocks/tickers" + today;
let req = unirest("GET", url);
req.query({
"apiKey": CLIENT_ID
}).then((res) => {
response.send(res.body);
});
});
app.get('/tickers/indicators', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let rawSchema = fs.readFileSync("data/schema.json");
let parsedJSON = JSON.parse(rawSchema);
//i loops through all the symbols
for (let i = parsedJSON.length - 1; i >= 0; i--) {
try {
let symbol = parsedJSON[i];
let cPoints = [];
const closeLow = Math.min(...symbol['c']);
const closeHigh = Math.max(...symbol['c']);
let vPoints = [];
const volumeLow = Math.min(...symbol['v']);
const volumeHigh = Math.max(...symbol['v']);
const timeLow = Math.min(...symbol['t']);
const timeHigh = Math.max(...symbol['t']);
//j loops through the arrays
for (let j = 0; j < symbol['c'].length; j++) {
let time = symbol['t'][j];
let price = symbol['c'][j];
let volume = symbol['v'][j];
let x = map(time, timeLow, timeHigh, 0, 1);
let cy = map(price, closeLow, closeHigh, 0, 1);
let vy = map(volume, volumeLow, volumeHigh, 0, 1);
cPoints.push([x, cy]);
vPoints.push([x, vy]);
}
//CLOSE
//2ax^2+bx+c
const closeRegression = regression.polynomial(cPoints, { order: 2 });
symbol['cQuadratic'] = closeRegression.string;
symbol['cR2'] = closeRegression.r2;
//2ax+b
const cDeriveAndEvaluate = ((2 * closeRegression.equation[0]) + closeRegression.equation[1]).toFixed(2);
symbol['cROC'] = cDeriveAndEvaluate;
//VOLUME
//2ax^2+bx+c
const volumeRegression = regression.polynomial(vPoints, { order: 2 });
symbol['vQuadratic'] = volumeRegression.string;
symbol['vR2'] = volumeRegression.r2;
//2ax+b
const vDeriveAndEvaluate = ((2 * volumeRegression.equation[0]) + volumeRegression.equation[1]).toFixed(2);
symbol['vROC'] = vDeriveAndEvaluate;
delete symbol['c'];
delete symbol['t'];
delete symbol['v'];
} catch (e) {
console.log(e);
}
}
response.send(parsedJSON);
});
/*****************************************************************
* API: N/A
* Description: Loads debug data from a JSON file and sends it as a response.
*****************************************************************/
app.get('/alltickers/debug', (request, response) => {
console.log('\x1b[36m%s\x1b[0m', request.url, new Date().toLocaleString());
let rawSchema = fs.readFileSync("data/alltickers.json");
let parsedJSON = JSON.parse(rawSchema);
response.send(parsedJSON);
});