From 4921cef044cd85ccba9e2766aae5ae5d075cec55 Mon Sep 17 00:00:00 2001 From: Luis Fernando Molina Date: Tue, 6 Mar 2018 20:39:34 +0100 Subject: [PATCH] Error handling major refactoring --- .vs/AACloudPlatform/v15/.suo | Bin 69632 -> 71680 bytes AACloudPlatform.njsproj | 3 + Assistant.js | 121 ++++++++++---------- Context.js | 82 +++++++------- Datasource.js | 43 +++---- ExchangeAPI.js | 58 +++++----- Interval Executor.js | 9 -- Run.js | 60 +++++++++- TradingBot.js | 213 +++++++++++++++++++++++++++++++++++ 9 files changed, 425 insertions(+), 164 deletions(-) create mode 100644 TradingBot.js diff --git a/.vs/AACloudPlatform/v15/.suo b/.vs/AACloudPlatform/v15/.suo index a076f695ae1c87a73ee20ddb481769c78edc2afe..650fa4136801c4d527693ca236dd5cc898e84fe2 100644 GIT binary patch delta 3296 zcmcImdr*{B6#wqG-@<;dD2O~#WEWU*1;ho>*3<&r6eNWu%Kj*WQp^`1?y7?(pCyXV zWKXMGITNjqKO8gKOJNh)Hrj(SAJao7az#ZnEr`?Ap=T0hf+Nz}qhmBLctnko})n&_5FE#ym@#tihh5Ag^h43Ua3B5q*s zp;!+`Bq2s3Ob8k^ScYLc0Wk!jL1ZGxMv)p&UX2)qh(}N)WE+e12t;mQJJ~l5g$aEP zvil~6$b~J|v=Nqo;$f_(A*LgW1G-f(QZ8k+V3(&$cGQ7aHY7EmKp~9AIu@}8(TGqG z4so%3Wo$*)3rN`gHwoicMHM4*!qdh_p<6V9g3)8GMhr&i5VXn|L>eLok%#cJ*J6!r zB)X_muuQ@>(HMbsdWena3i^x>k(Y$XWT!QRmO&x*F(_*TZ8O#n(C(4*2)H2W)Fc&Q zOl%gUs7JBIP^_M}0h zOCns)>{9y=5mCl_v$V{iKLSU@9O%`TNt7mJ09#5aDS2;-R&);&J=H}_qJ+OW<$q5Ta8%I0x<@@D4H z=|P{d`=9m#uBDYoaz6=%Qkmfv_~^$I9FX@Kw9GwObj(VUn^C_Ju?Z72jh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J4AX~ J76hQD=2wi9ck}=N diff --git a/AACloudPlatform.njsproj b/AACloudPlatform.njsproj index a9b5c3925..91da2bf4b 100644 --- a/AACloudPlatform.njsproj +++ b/AACloudPlatform.njsproj @@ -39,6 +39,9 @@ + + Code + diff --git a/Assistant.js b/Assistant.js index 359ad47d5..e780a16bf 100644 --- a/Assistant.js +++ b/Assistant.js @@ -50,20 +50,21 @@ function onDone(err) { try { - switch (err) { - case null: { - callBackFunction(null); - } - break; - case 'Retry Later': { // 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.message); + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { + callBackFunction(DEFAULT_OK_RESPONSE); return; } break; - case 'Retry Later': { // This is an unexpected exception that we do not know how to handle. + case 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; + } + break; + case 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.message); + callBackFunction(err); return; } break; @@ -71,14 +72,14 @@ } catch (err) { logger.write("[ERROR] initialize -> onDone -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -98,21 +99,22 @@ function onResponse(err, pExchangePositions) { - switch (err) { - case null: { // Everything went well, we have the information requested. + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. exchangePositions = pExchangePositions; ordersExecutionCheck(callBack); - } - break; - case 'Retry Later': { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] getPositionsAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); - callBack(err.message); return; } break; - case 'Operation Failed': { // This is an unexpected exception that we do not know how to handle. + case DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. + logger.write("[ERROR] getPositionsAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); + callBack(err); + return; + } + break; + case DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. logger.write("[ERROR] getPositionsAtExchange -> onResponse -> Operation Failed. Aborting the process."); - callBack(err.message); + callBack(err); return; } break; @@ -120,10 +122,10 @@ } } catch (err) { logger.write("[ERROR] getPositionsAtExchange -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } - + function ordersExecutionCheck(callBack) { try { @@ -227,7 +229,7 @@ botContext.executionContext.positions[i].amountB !== sumAssetB ) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> Cannot be confirmed that a partially execution was done well."); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); return; } @@ -262,7 +264,7 @@ } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasPartiallyExecuted -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); return; } } @@ -304,7 +306,7 @@ botContext.executionContext.positions[i].amountB !== sumAssetB ) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> Cannot be confirmed that the order was executed. It must be manually cancelled by the user or cancelled by the exchange itself."); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); return; } @@ -337,7 +339,7 @@ } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); return; } } @@ -356,38 +358,38 @@ function onResponse(err, pTrades) { try { - switch (err) { - case null: { // Everything went well, we have the information requested. + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. innerCallBack(pTrades); } break; - case 'Retry Later': { // Something bad happened, but if we retry in a while it might go through the next time. + case DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); - callBack('Retry Later'); + callBack(DEFAULT_RETRY_RESPONSE); return; } break; - case 'Operation Failed': { // This is an unexpected exception that we do not know how to handle. + case DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> Operation Failed. Aborting the process."); - callBack('Operation Failed'); + callBack(DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> onResponse -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> getPositionTradesAtExchange -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> loopBody -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); return; } } @@ -414,12 +416,12 @@ function final() { - callBack(null); + callBack(DEFAULT_OK_RESPONSE); } } catch (err) { logger.write("[ERROR] ordersExecutionCheck -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -431,8 +433,8 @@ function onResponse(err, pPositionId) { try { - switch (err) { - case null: { // Everything went well, we have the information requested. + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. let position = { id: pPositionId, @@ -457,30 +459,31 @@ botContext.newHistoryRecord.newPositions++; botContext.newHistoryRecord.rate = pRate; - callBack(null); - } - break; - case 'Retry Later': { // Something bad happened, but if we retry in a while it might go through the next time. - logger.write("[ERROR] putPositionAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); - callBack('Retry Later'); + callBack(DEFAULT_OK_RESPONSE); return; } break; - case 'Operation Failed': { // This is an unexpected exception that we do not know how to handle. + case DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. + logger.write("[ERROR] putPositionAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); + callBack(DEFAULT_RETRY_RESPONSE); + return; + } + break; + case DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. logger.write("[ERROR] putPositionAtExchange -> onResponse -> Operation Failed. Aborting the process."); - callBack('Operation Failed'); + callBack(DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { logger.write("[ERROR] putPositionAtExchange -> onResponse -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] putPositionAtExchange -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -492,8 +495,8 @@ function onResponse(err, pPositionId) { try { - switch (err) { - case null: { // Everything went well, we have the information requested. + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { // Everything went well, we have the information requested. let newPosition = { id: pPositionId, @@ -531,30 +534,30 @@ botContext.newHistoryRecord.movedPositions++; botContext.newHistoryRecord.rate = pNewRate; - callBack(null); + callBack(DEFAULT_OK_RESPONSE); } break; - case 'Retry Later': { // Something bad happened, but if we retry in a while it might go through the next time. + case DEFAULT_RETRY_RESPONSE.result: { // Something bad happened, but if we retry in a while it might go through the next time. logger.write("[ERROR] movePositionAtExchange -> onResponse -> Retry Later. Requesting Execution Retry."); - callBack('Retry Later'); + callBack(DEFAULT_RETRY_RESPONSE); return; } break; - case 'Operation Failed': { // This is an unexpected exception that we do not know how to handle. + case DEFAULT_FAIL_RESPONSE.result: { // This is an unexpected exception that we do not know how to handle. logger.write("[ERROR] movePositionAtExchange -> onResponse -> Operation Failed. Aborting the process."); - callBack('Operation Failed'); + callBack(DEFAULT_FAIL_RESPONSE); return; } break; } } catch (err) { logger.write("[ERROR] movePositionAtExchange -> onResponse -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] movePositionAtExchange -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } }; \ No newline at end of file diff --git a/Context.js b/Context.js index 6ba1b35d8..68cfa73c8 100644 --- a/Context.js +++ b/Context.js @@ -87,20 +87,21 @@ function onDone(err) { try { - switch (err) { - case null: { - callBackFunction(null); - } - break; - case 'Retry Later': { // 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.message); + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { + callBackFunction(DEFAULT_OK_RESPONSE); return; } break; - case 'Retry Later': { // This is an unexpected exception that we do not know how to handle. + case 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; + } + break; + case 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.message); + callBackFunction(err); return; } break; @@ -108,7 +109,7 @@ } catch (err) { logger.write("[ERROR] initialize -> onDone -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -149,12 +150,12 @@ */ logger.write("[ERROR] initialize -> getStatusReport -> Bot cannot execute without the Status report. -> Err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> getExecutionHistory -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -184,12 +185,12 @@ */ logger.write("[ERROR] initialize -> getExecutionHistory -> Bot cannot execute without the Execution History. -> Err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> getExecutionHistory -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -212,7 +213,7 @@ thisObject.executionContext.transactions = []; // We record here the transactions that happened duting this execution. - callBack(null); + callBack(DEFAULT_OK_RESPONSE); } catch (err) { @@ -225,13 +226,13 @@ */ logger.write("[ERROR] initialize -> getExecutionContext -> Bot cannot execute without the Execution Context. -> Err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> getExecutionContext -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -260,17 +261,17 @@ transactions: [] }; - callBack(null); + callBack(DEFAULT_OK_RESPONSE); } catch (err) { logger.write("[ERROR] initialize -> createConext -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -283,20 +284,21 @@ function onDone(err) { try { - switch (err) { - case null: { - callBackFunction(null); - } - break; - case 'Retry Later': { // 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.message); + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { + callBackFunction(DEFAULT_OK_RESPONSE); return; } break; - case 'Retry Later': { // This is an unexpected exception that we do not know how to handle. + case 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 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.message); + callBackFunction(err); return; } break; @@ -304,7 +306,7 @@ } catch (err) { logger.write("[ERROR] saveThemAll -> onDone -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -341,14 +343,14 @@ } catch (err) { logger.write("[ERROR] saveThemAll -> writeExecutionContext -> onFolderCreated -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] saveThemAll -> writeExecutionContext -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -390,14 +392,14 @@ } catch (err) { logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> onFolderCreated -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] saveThemAll -> writeExucutionHistory -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -430,26 +432,26 @@ logger.write("[INFO] saveThemAll -> writeStatusReport -> onFolderCreated -> Content written = " + fileContent); } - callBack(null); + callBack(DEFAULT_OK_RESPONSE); return; } } catch (err) { logger.write("[ERROR] saveThemAll -> writeStatusReport -> onFolderCreated -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] saveThemAll -> writeStatusReport -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] saveThemAll -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } diff --git a/Datasource.js b/Datasource.js index 86f78163c..df2fed165 100644 --- a/Datasource.js +++ b/Datasource.js @@ -68,20 +68,21 @@ function onDone(err) { try { - switch (err) { - case null: { - callBackFunction(null); - } - break; - case 'Retry Later': { // 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.message); + switch (err.result) { + case DEFAULT_OK_RESPONSE.result: { + callBackFunction(DEFAULT_OK_RESPONSE); return; } break; - case 'Retry Later': { // This is an unexpected exception that we do not know how to handle. + case 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; + } + break; + case 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.message); + callBackFunction(err); return; } break; @@ -89,7 +90,7 @@ } catch (err) { logger.write("[ERROR] initialize -> onDone -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -131,7 +132,7 @@ } } catch (err) { logger.write("[ERROR] getCandles -> getMarketFiles -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -158,7 +159,7 @@ } } catch (err) { logger.write("[ERROR] getCandles -> getDailyFiles -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -221,13 +222,13 @@ } } catch (err) { logger.write("[ERROR] getCandles -> getCandlesWeAreIn -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] getCandles -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -268,7 +269,7 @@ } } catch (err) { logger.write("[ERROR] getPatterns -> getMarketFiles -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -295,7 +296,7 @@ } } catch (err) { logger.write("[ERROR] getPatterns -> getDailyFiles -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -354,19 +355,19 @@ if (counter === thisObject.stairsFiles.size) { - callBack(null); + callBack(DEFAULT_OK_RESPONSE); } } } catch (err) { logger.write("[ERROR] getPatterns -> getStairsWeAreIn -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] getPatterns -> err = " + err.message); - callBack("Operation Failed"); + callBack(DEFAULT_FAIL_RESPONSE); } } @@ -415,7 +416,7 @@ } catch (err) { logger.write("[ERROR] initialize -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } }; \ No newline at end of file diff --git a/ExchangeAPI.js b/ExchangeAPI.js index 33585a37a..0651d9333 100644 --- a/ExchangeAPI.js +++ b/ExchangeAPI.js @@ -32,7 +32,7 @@ let apiKey = readApiKey(); poloniexApiClient = new POLONIEX_CLIENT_MODULE(apiKey.Key, apiKey.Secret); - callBackFunction(null); + callBackFunction(DEFAULT_OK_RESPONSE); function readApiKey() { @@ -47,14 +47,14 @@ logger.write("[HINT] The file must have the keys to access your poloniex account, in this format -> " + '{ "Key" : "4FB9TMEB-234VH2W1-BYJIXHGM-GL15DSA1", "Secret" : "1a24298skdjdf734uuyhbdagdasdtyut276587256hdsdas765asdasdasd76asdasda765asdasfas6asfda57657asd5a76sd5a7s65d7a6sd57as65d7as65d"}'); logger.write("[HINT] You get this key logging in to your Poloniex web account, enabling API keys and getting a new one. "); logger.write("[HINT] Be sure not to allow withdrawls with this Key. When asked at the exchange key page, say no. "); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] initialize -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -74,7 +74,7 @@ if (err.message.indexOf("ETIMEDOUT") > 0) { logger.write("[WARN] getOpenPositions -> onExchangeCallReturned -> Timeout reached while trying to access the Exchange API. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { @@ -82,19 +82,19 @@ if (err.message.indexOf("ECONNRESET") > 0) { logger.write("[WARN] getOpenPositions -> onExchangeCallReturned -> The exchange reseted the connection. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { logger.write("[ERROR] getOpenPositions -> onExchangeCallReturned -> Unexpected error trying to contact the Exchange. This will halt this bot process. : ERROR = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { logger.write("[ERROR] getOpenPositions -> onExchangeCallReturned -> exchangeResponse.error = " + exchangeResponse.error); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } @@ -136,12 +136,12 @@ } catch (err) { logger.write("[ERROR] getOpenPositions -> onExchangeCallReturned -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] getOpenPositions -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -161,7 +161,7 @@ if (err.message.indexOf("ETIMEDOUT") > 0) { logger.write("[WARN] getExecutedTrades -> onExchangeCallReturned -> Timeout reached while trying to access the Exchange API. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { @@ -169,19 +169,19 @@ if (err.message.indexOf("ECONNRESET") > 0) { logger.write("[WARN] getExecutedTrades -> onExchangeCallReturned -> The exchange reseted the connection. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { logger.write("[ERROR] getExecutedTrades -> onExchangeCallReturned -> Unexpected error trying to contact the Exchange. This will halt this bot process. : ERROR = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { logger.write("[ERROR] getExecutedTrades -> onExchangeCallReturned -> exchangeResponse.error = " + exchangeResponse.error); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } } else { @@ -229,12 +229,12 @@ } catch (err) { logger.write("[ERROR] getExecutedTrades -> onExchangeCallReturned -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] getExecutedTrades -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -253,7 +253,7 @@ } logger.write("[ERROR] putPosition -> pType must be either 'buy' or 'sell'."); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; function onExchangeCallReturned(err, exchangeResponse) { @@ -266,7 +266,7 @@ if (err.message.indexOf("ETIMEDOUT") > 0) { logger.write("[WARN] putPosition -> onExchangeCallReturned -> Timeout reached while trying to access the Exchange API. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { @@ -274,19 +274,19 @@ if (err.message.indexOf("ECONNRESET") > 0) { logger.write("[WARN] putPosition -> onExchangeCallReturned -> The exchange reseted the connection. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { logger.write("[ERROR] putPosition -> onExchangeCallReturned -> Unexpected error trying to contact the Exchange. This will halt this bot process. : ERROR = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { logger.write("[ERROR] putPosition -> onExchangeCallReturned -> exchangeResponse.error = " + exchangeResponse.error); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } @@ -316,13 +316,13 @@ } catch (err) { logger.write("[ERROR] putPosition -> onExchangeCallReturned -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] putPosition -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } @@ -342,7 +342,7 @@ if (err.message.indexOf("ETIMEDOUT") > 0) { logger.write("[WARN] movePosition -> onExchangeCallReturned -> Timeout reached while trying to access the Exchange API. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { @@ -350,19 +350,19 @@ if (err.message.indexOf("ECONNRESET") > 0) { logger.write("[WARN] movePosition -> onExchangeCallReturned -> The exchange reseted the connection. Requesting new execution later. : ERROR = " + err.message); - callBackFunction("Retry Later"); + callBackFunction(DEFAULT_RETRY_RESPONSE); return; } else { logger.write("[ERROR] movePosition -> onExchangeCallReturned -> Unexpected error trying to contact the Exchange. This will halt this bot process. : ERROR = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } } } catch (err) { logger.write("[ERROR] movePosition -> onExchangeCallReturned -> exchangeResponse.error = " + exchangeResponse.error); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } @@ -370,7 +370,7 @@ if (exchangeResponse.success !== 1) { logger.write("[ERROR] movePosition -> onExchangeCallReturned -> exchangeResponse.success = " + exchangeResponse.success); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); return; } /* @@ -397,13 +397,13 @@ } catch (err) { logger.write("[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } } catch (err) { logger.write("[ERROR] movePosition -> err = " + err.message); - callBackFunction("Operation Failed"); + callBackFunction(DEFAULT_FAIL_RESPONSE); } } }; \ No newline at end of file diff --git a/Interval Executor.js b/Interval Executor.js index 6338cd8eb..22c29800b 100644 --- a/Interval Executor.js +++ b/Interval Executor.js @@ -202,12 +202,3 @@ } } }; - -/* - - const NEXT_BOT_EXECUTION = 10 * 1000; // If something fails and we need to retry after a few seconds, we will use this amount of time to request a new execution of this bot code. - - -let processDatetime = new Date(); // This will be considered the process date and time, so as to have it consistenly all over the execution. -processDatetime = new Date(processDatetime.valueOf() - 30 * 24 * 60 * 60 * 1000); // we go 30 days back in time since candles are currently not up to date. -*/ diff --git a/Run.js b/Run.js index f606a0b46..2e37de4ec 100644 --- a/Run.js +++ b/Run.js @@ -43,14 +43,8 @@ botConfig.bot; /* Now we will run according to what we see at the config file. */ const ROOT_DIR = './'; - const MODULE_NAME = "Run"; -const START_ALL_MONTHS = false; -const START_ONE_MONTH = true; - -const INTERVAL_EXECUTOR_MODULE = require('./Interval Executor'); - const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); const logger = DEBUG_MODULE.newDebugLog(); logger.fileName = MODULE_NAME; @@ -70,6 +64,60 @@ process.on('exit', function (code) { logger.write('About to exit with code:' + code); }); +const DEFAULT_OK_RESPONSE = { + result: "Ok", + message: "Operation Succeeded" +}; + +const DEFAULT_FAIL_RESPONSE = { + result: "Fail", + message: "Operation Failed" +}; + +const DEFAULT_RETRY_RESPONSE = { + result: "Retry", + message: "Retry Later" +}; + +if (bot.type === "trading") { + + let tradingBot = newTradingBot(bot, botConfig); + tradingBot.initialize(onInitializeReady); + + function onInitializeReady(err) { + + if (err === null) { + + tradingBot.start(whenStartFinishes); + + function whenStartFinishes() { + + if (err === null) { + + logger.write("[INFO] trading bot -> onInitializeReady -> whenStartFinishes -> Bot execution finished sucessfully. :-)"); + + } else { + + logger.write("[ERR] trading bot -> onInitializeReady -> whenStartFinishes -> err = " + err.message); + logger.write("[ERR] trading bot -> onInitializeReady -> whenStartFinishes -> Execution will be stopped. "); + logger.write("[ERR] trading bot -> onInitializeReady -> whenStartFinishes -> Bye. :-("); + } + } + + } else { + logger.write("[ERR] trading bot -> onInitializeReady -> err = " + err.message); + logger.write("[ERR] trading bot -> onInitializeReady -> Bot will not be started. " ); + } + + } + return; +} + +const START_ALL_MONTHS = false; +const START_ONE_MONTH = true; + +const INTERVAL_EXECUTOR_MODULE = require('./Interval Executor'); + /* Now we will see which are the script Arguments. We expect the name of the process to run, since that is what it should be defined at the Task Scheduller. */ let processToRun = process.argv[2]; diff --git a/TradingBot.js b/TradingBot.js new file mode 100644 index 000000000..9eb871ec9 --- /dev/null +++ b/TradingBot.js @@ -0,0 +1,213 @@ +exports.newTradingBot = function newTradingBot(BOT, CONFIG) { + + let bot = BOT; + const ROOT_DIR = './'; + + const MODULE_NAME = "Interval Executor"; + const LOG_INFO = true; + + let INTERVAL_MODULE; + + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const logger = DEBUG_MODULE.newDebugLog(); + logger.fileName = MODULE_NAME; + logger.bot = bot; + + intervalExecutor = { + initialize: initialize, + start: start + }; + + const SHUTDOWN_EVENT = require(ROOT_DIR + 'Azure Web Job Shutdown'); + let shutdownEvent = SHUTDOWN_EVENT.newShutdownEvent(bot); + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + let utilities = UTILITIES.newUtilities(bot); + + let year; + let month; + + let processConfig; + + return intervalExecutor; + + function initialize(pBotPath, pProcessConfig, pYear, pMonth, callBackFunction) { + + try { + + processConfig = pProcessConfig; + + year = pYear; + month = pMonth; + + let logText; + + if (year !== undefined) { + + month = utilities.pad(month, 2); // Adding a left zero when needed. + logger.fileName = MODULE_NAME + "-" + year + "-" + month; + logText = "[INFO] initialize - Entering function 'initialize' " + " @ " + year + "-" + month; + + } else { + + logger.fileName = MODULE_NAME; + logText = "[INFO] initialize - Entering function 'initialize' "; + + } + + console.log(logText); + logger.write(logText); + + INTERVAL_MODULE = require(pBotPath + "/" + pProcessConfig.name + "/" + 'Interval'); + + callBackFunction(); + + } catch (err) { + + const logText = "[ERROR] initialize - ' ERROR : " + err.message; + console.log(logText); + logger.write(logText); + logger.write(err.stack); + + } + } + + + function start() { + + try { + + if (year !== undefined) { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start', with year = " + year + " and month = " + month); + } + + } else { + + if (LOG_INFO === true) { + logger.write("[INFO] Entering function 'start'."); + } + + } + + + + let intervalId; + + if (processConfig.intervalMaxLoops === 0) { + + intervalId = setInterval(startNewInterval, processConfig.intervalLapse); + + } + + let intervalLoopCounter = 0; + + startNewInterval(); // First, inmadiate run. + + function startNewInterval() { + + try { + + if (LOG_INFO === true) { + + if (processConfig.intervalMaxLoops !== 0) { + + logger.write("[INFO] Entering function 'startNewInterval', next execution inmediately after the current Interval finishes."); + + } else { + + logger.write("[INFO] Entering function 'startNewInterval', next execution in " + processConfig.intervalLapse / 1000 / 60 + " minutes."); + + } + + } + + + if (shutdownEvent.isShuttingDown() === false) { + + const UTILITIES = require(ROOT_DIR + 'Utilities'); + const AZURE_FILE_STORAGE = require(ROOT_DIR + 'Azure File Storage'); + const MARKETS_MODULE = require(ROOT_DIR + 'Markets'); + const DEBUG_MODULE = require(ROOT_DIR + 'Debug Log'); + const POLONIEX_CLIENT_MODULE = require(ROOT_DIR + 'Poloniex API Client'); + + let fileProcessingInterval = INTERVAL_MODULE.newInterval(bot, UTILITIES, AZURE_FILE_STORAGE, DEBUG_MODULE, MARKETS_MODULE, POLONIEX_CLIENT_MODULE); + + fileProcessingInterval.initialize(year, month, onReadyToStart); + + function onReadyToStart() { + + fileProcessingInterval.start(loopControl); + + } + + } + else { + + clearInterval(intervalId); + + const logText = "[INFO] requestNewData - Terminating Set Interval - About to exit gracefully the process. "; + console.log(logText); + logger.write(logText); + + } + + } + catch (err) { + const logText = "[ERROR] 'startNewInterval' - ERROR : " + err.message; + logger.write(logText); + } + } + + function loopControl(moreIntervalExecutionsNeeded, nextIntervalLapse) { + + if (moreIntervalExecutionsNeeded === true) { + + intervalLoopCounter++; + + if (intervalLoopCounter === processConfig.intervalMaxLoops) { + + const logText = "[WARN] 'processConfig.intervalMaxLoops' reached. Stopping execution. "; + logger.write(logText); + + } else { + + const logText = "[WARN] 'loopControl'. Staring new Interval. "; + logger.write(logText); + + if (nextIntervalLapse === undefined) { + + setTimeout(startNewInterval, processConfig.intervalLapse);// Looped Execution. + + } else { + + setTimeout(startNewInterval, nextIntervalLapse); + + } + } + + } else { + + logger.write("[WARN] Received the signal from last Interval execution to not call it anymore. Stopping execution. "); + + } + + } + + } + catch (err) { + const logText = "[ERROR] 'Start' - ERROR : " + err.message; + logger.write(logText); + } + } +}; + +/* + + const NEXT_BOT_EXECUTION = 10 * 1000; // If something fails and we need to retry after a few seconds, we will use this amount of time to request a new execution of this bot code. + + +let processDatetime = new Date(); // This will be considered the process date and time, so as to have it consistenly all over the execution. +processDatetime = new Date(processDatetime.valueOf() - 30 * 24 * 60 * 60 * 1000); // we go 30 days back in time since candles are currently not up to date. +*/