-
Notifications
You must be signed in to change notification settings - Fork 4
/
Context.js
553 lines (401 loc) · 25.3 KB
/
Context.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
exports.newContext = function newContext(BOT, DEBUG_MODULE, FILE_STORAGE, UTILITIES, STATUS_REPORT) {
const FULL_LOG = true;
const LOG_FILE_CONTENT = false;
/*
This module allows deals with keeping the context between different executions of the bot.
It deals with these 3 different files that helps the bot process remember where it is standing:
1. The Status Report.
2. The Execution History.
3. The Execution Context.
*/
const MODULE_NAME = "Context";
/*
Here we will keep the last status report, to be available during the whole process. The Status Report is a file the bot process
reads and saves again after each execution. Its main purpose is to know when the last execution was in order to locate the execution
context. When the bot runs for the first time it takes some vital parameters from there and it checks them through its lifecycle to see
if they changed. The Status Report file can eventually be manipulated by the bot operators / developers in order to change those parameters
or to point the last execution to a different date. Humans are not supose to manipulate the Execution Histroy or the execution Context files.
The Execution History is basically an index with dates of all the executions the bot did across its history. It allows the bot plotter
to know which datetimes have informacion about the bots execution in order to display it.
The Execution Context file records all the context information of the bot at the moment of execution and the final state of all of its
positions on the market.
*/
let thisObject = {
statusReport: undefined, // Here is the information that defines which was the last sucessfull execution and some other details.
executionHistory: [], // This is the record of bot execution.
executionContext: undefined, // Here is the business information of the last execution of this bot process.
newHistoryRecord : {
date: undefined,
buyAvgRate: 0,
sellAvgRate: 0,
marketRate: 0,
newPositions: 0,
newTrades: 0,
movedPositions: 0,
profitsAssetA: 0,
profitsAssetB: 0,
combinedProfitsA: 0,
combinedProfitsB: 0
},
initialize: initialize,
saveThemAll: saveThemAll
};
/*
During the process we will create a new History Record. This will go to the Context History file which essentially mantains an
index of all the bots executions. This file will later be plotted by the bot s plotter on the timeline, allowing end users to
know where there is information related to the actions taken by the bot.
*/
let bot = BOT;
let statusReportModule;
const logger = DEBUG_MODULE.newDebugLog();
logger.fileName = MODULE_NAME;
logger.bot = bot;
/* Utilities needed. */
let utilities = UTILITIES.newUtilities(bot);
/* Storage account to be used here. */
let cloudStorage = FILE_STORAGE.newFileStorage(bot);
let dependencies;
return thisObject;
function initialize(pDependencies, callBackFunction) {
try {
if (FULL_LOG === true) { logger.write("[INFO] initialize -> Entering function."); }
dependencies = pDependencies;
/*
Here we get the positions the bot did and that are recorded at the bot storage account. We will use them through out the rest
of the process.
*/
initializeStorage();
function initializeStorage() {
cloudStorage.initialize(bot.codeName, onInizialized);
function onInizialized(err) {
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
thisObject.newHistoryRecord.date = bot.processDatetime;
getStatusReport(onDone);
} else {
logger.write("[ERROR] initialize -> initializeStorage -> onInizialized -> err = " + err.message);
callBackFunction(err);
}
}
}
function onDone(err) {
try {
switch (err.result) {
case global.DEFAULT_OK_RESPONSE.result: {
logger.write("[INFO] initialize -> onDone -> Execution finished well. :-)");
callBackFunction(global.DEFAULT_OK_RESPONSE);
return;
}
case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time.
logger.write("[ERROR] initialize -> onDone -> Retry Later. Requesting Execution Retry.");
callBackFunction(err);
return;
}
case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle.
logger.write("[ERROR] initialize -> onDone -> Operation Failed. Aborting the process.");
callBackFunction(err);
return;
}
default: {
logger.write("[ERROR] initialize -> onDone -> Operation Failed with custom response.");
callBackFunction(err);
}
}
} catch (err) {
logger.write("[ERROR] initialize -> onDone -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
function getStatusReport(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getStatusReport -> Entering function."); }
let key = bot.devTeam + "-" + bot.codeName + "-" + bot.process + "-" + bot.dataSetVersion;
statusReportModule = dependencies.statusReports.get(key);
thisObject.statusReport = statusReportModule.file;
if (thisObject.statusReport.lastExecution !== undefined) {
getExecutionHistory(callBack); // Happens when the Status Report exists.
} else {
createConext(callBack); // Happens when the Status Report does NOT exists.
}
} catch (err) {
logger.write("[ERROR] initialize -> getStatusReport -> err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
function getExecutionHistory(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionHistory -> Entering function."); }
let fileName = "Execution.History.json";
let filePath = bot.filePathRoot + "/Output/" + bot.process;
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionHistory -> fileName = " + fileName); }
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionHistory -> filePath = " + filePath); }
cloudStorage.getTextFile(filePath, fileName, onFileReceived);
function onFileReceived(err, text) {
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] initialize -> getExecutionHistory -> onFileReceived -> err = " + err.message);
callBack(err);
return;
}
if (LOG_FILE_CONTENT === true) {
logger.write("[INFO] initialize -> getExecutionHistory -> onFileReceived -> Content received = " + text);
}
try {
thisObject.executionHistory = JSON.parse(text);
/* Move some values to the new record, in case there are no transactions that re-calculate them. */
thisObject.newHistoryRecord.buyAvgRate = thisObject.executionHistory[1];
thisObject.newHistoryRecord.sellAvgRate = thisObject.executionHistory[2];
getExecutionContext(callBack);
} catch (err) {
/*
It might happen that the file content is corrupt or it does not exist. The bot can not run without an Execution Hitory,
since it is risky to ignore its own history, so even for first time execution, a file with the right format
is needed.
*/
logger.write("[ERROR] initialize -> getExecutionHistory -> onFileReceived -> Bot cannot execute without the Execution History. -> Err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
} catch (err) {
logger.write("[ERROR] initialize -> getExecutionHistory -> err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
function getExecutionContext(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionContext -> Entering function."); }
let date = new Date(thisObject.statusReport.lastExecution);
let fileName = "Execution.Context.json";
let dateForPath = date.getUTCFullYear() + '/' + utilities.pad(date.getUTCMonth() + 1, 2) + '/' + utilities.pad(date.getUTCDate(), 2) + '/' + utilities.pad(date.getUTCHours(), 2) + '/' + utilities.pad(date.getUTCMinutes(), 2);
let filePath = bot.filePathRoot + "/Output/" + bot.process + '/' + dateForPath;
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionContext -> fileName = " + fileName); }
if (FULL_LOG === true) { logger.write("[INFO] initialize -> getExecutionContext -> filePath = " + filePath); }
cloudStorage.getTextFile(filePath, fileName, onFileReceived);
function onFileReceived(err, text) {
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] initialize -> getExecutionContext -> onFileReceived -> err = " + err.message);
callBack(err);
return;
}
if (FULL_LOG === true) {
logger.write("[INFO] initialize -> getExecutionContext -> onFileReceived -> Content received = " + text);
}
try {
thisObject.executionContext = JSON.parse(text);
thisObject.executionContext.transactions = []; // We record here the transactions that happened duting this execution.
/* Update the new History Record, in case there are no trades during this execution that updates it. */
thisObject.newHistoryRecord.profitsAssetA = thisObject.executionContext.profits.assetA;
thisObject.newHistoryRecord.profitsAssetB = thisObject.executionContext.profits.assetB;
thisObject.newHistoryRecord.combinedProfitsA = thisObject.executionContext.combinedProfits.assetA;
thisObject.newHistoryRecord.combinedProfitsB = thisObject.executionContext.combinedProfits.assetB;
callBack(global.DEFAULT_OK_RESPONSE);
} catch (err) {
/*
It might happen that the file content is corrupt or it does not exist. The bot can not run without a Status Report,
since it is risky to ignore its own history, so even for first time execution, a status report with the right format
is needed.
*/
logger.write("[ERROR] initialize -> getExecutionContext -> onFileReceived -> Bot cannot execute without the Execution Context. -> Err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
} catch (err) {
logger.write("[ERROR] initialize -> getExecutionContext -> err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
function createConext(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] initialize -> createConext -> Entering function."); }
/*
When the bot is executed for the very first time, there are a few files that do not exist and need to be created, and that
content is what we are going to set up now.
*/
thisObject.statusReport = {};
thisObject.executionHistory = [];
/*
In the current release, the platform is going to be used for the first competition, so we have a few parameters just for that. They will be removed later
once we advance into multiple competitions scheme.
*/
const INITIAL_INVESTMENT = 0.0001; // This is just for this release of the platform.
thisObject.executionContext = {
investment: { // This is used to calculate profits.
assetA: 0,
assetB: INITIAL_INVESTMENT
},
balance: { // This is the total balance that includes positions at the order book + funds available to be traded.
assetA: 0,
assetB: INITIAL_INVESTMENT // It starts with the initial investment.
},
availableBalance: { // This is the balance the bot has at any moment in time available to be traded (not in positions at the order book).
assetA: 0,
assetB: INITIAL_INVESTMENT // It starts with the initial investment.
},
profits: {
assetA: 0,
assetB: 0
},
combinedProfits: {
assetA: 0,
assetB: 0
},
positions: [],
transactions: []
};
callBack(global.DEFAULT_OK_RESPONSE);
} catch (err) {
logger.write("[ERROR] initialize -> createConext -> err = " + err.message);
callBack(global.DEFAULT_FAIL_RESPONSE);
}
}
} catch (err) {
logger.write("[ERROR] initialize -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
function saveThemAll(callBackFunction) {
try {
writeExecutionContext(onDone);
function onDone(err) {
try {
switch (err.result) {
case global.DEFAULT_OK_RESPONSE.result: {
logger.write("[INFO] saveThemAll -> onDone -> Execution finished well. :-)");
callBackFunction(global.DEFAULT_OK_RESPONSE);
return;
}
break;
case global.DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time.
logger.write("[ERROR] saveThemAll -> onDone -> Retry Later. Requesting Execution Retry.");
callBackFunction(err);
return;
}
break;
case global.DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle.
logger.write("[ERROR] saveThemAll -> onDone -> Operation Failed. Aborting the process.");
callBackFunction(err);
return;
}
break;
}
} catch (err) {
logger.write("[ERROR] saveThemAll -> onDone -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
function writeExecutionContext(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> Entering function."); }
let fileName = "Execution.Context.json";
let dateForPath = bot.processDatetime.getUTCFullYear() + '/' + utilities.pad(bot.processDatetime.getUTCMonth() + 1, 2) + '/' + utilities.pad(bot.processDatetime.getUTCDate(), 2) + '/' + utilities.pad(bot.processDatetime.getUTCHours(), 2) + '/' + utilities.pad(bot.processDatetime.getUTCMinutes(), 2);
let filePath = bot.filePathRoot + "/Output/" + bot.process + '/' + dateForPath;
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> fileName = " + fileName); }
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> filePath = " + filePath); }
utilities.createFolderIfNeeded(filePath, cloudStorage, onFolderCreated);
function onFolderCreated(err) {
try {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> Entering function."); }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message);
callBack(err);
return;
}
let fileContent = JSON.stringify(thisObject.executionContext);
cloudStorage.createTextFile(filePath, fileName, fileContent + '\n', onFileCreated);
function onFileCreated(err) {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Entering function."); }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> err = " + err.message);
callBack(err);
return;
}
if (FULL_LOG === true) {
logger.write("[INFO] saveThemAll -> writeExecutionContext -> onFolderCreated -> onFileCreated -> Content written = " + fileContent);
}
writeExucutionHistory(callBack);
return;
}
}
catch (err) {
logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
}
catch (err) {
logger.write("[ERROR] saveThemAll -> writeExecutionContext -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
function writeExucutionHistory(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> Entering function."); }
let fileName = "Execution.History.json";
let filePath = bot.filePathRoot + "/Output/" + bot.process;
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> fileName = " + fileName); }
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> filePath = " + filePath); }
utilities.createFolderIfNeeded(filePath, cloudStorage, onFolderCreated);
function onFolderCreated(err) {
try {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> Entering function."); }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message);
callBack(err);
return;
}
let newRecord = [
thisObject.newHistoryRecord.date.valueOf(),
thisObject.newHistoryRecord.buyAvgRate,
thisObject.newHistoryRecord.sellAvgRate,
thisObject.newHistoryRecord.marketRate,
thisObject.newHistoryRecord.newPositions,
thisObject.newHistoryRecord.newTrades,
thisObject.newHistoryRecord.movedPositions,
thisObject.newHistoryRecord.profitsAssetA,
thisObject.newHistoryRecord.profitsAssetB,
thisObject.newHistoryRecord.combinedProfitsA,
thisObject.newHistoryRecord.combinedProfitsB
];
thisObject.executionHistory.push(newRecord);
let fileContent = JSON.stringify(thisObject.executionHistory);
cloudStorage.createTextFile(filePath, fileName, fileContent + '\n', onFileCreated);
function onFileCreated(err) {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Entering function."); }
if (err.result !== global.DEFAULT_OK_RESPONSE.result) {
logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> err = " + err.message);
callBack(err);
return;
}
if (LOG_FILE_CONTENT === true) {
logger.write("[INFO] saveThemAll -> writeExucutionHistory -> onFolderCreated -> onFileCreated -> Content written = " + fileContent);
}
writeStatusReport(callBack);
return;
}
}
catch (err) {
logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
}
catch (err) {
logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
function writeStatusReport(callBack) {
try {
if (FULL_LOG === true) { logger.write("[INFO] saveThemAll -> writeStatusReport -> Entering function."); }
statusReportModule.file.lastExecution = bot.processDatetime;
statusReportModule.save(callBack);
}
catch (err) {
logger.write("[ERROR] saveThemAll -> writeStatusReport -> err = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
} catch (err) {
logger.write("[ERROR] saveThemAll -> Error = " + err.message);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
}
}
};