Draft multi exchange and binance client
This commit is contained in:
1 parent
acfcad623c
commit
306f39d513
5 files changed
+744
-300
No files matched your search
+12
-5
@@ -89,7 +89,7 @@
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> getMarketRateFromExchange -> Entering function."); }
|
||||
|
||||
exchangeAPI.getTicker(global.MARKET.assetA + '_' + global.MARKET.assetB, onTicker);
|
||||
exchangeAPI.getTicker(global.MARKET, onTicker);
|
||||
|
||||
return;
|
||||
|
||||
@@ -663,10 +663,10 @@
|
||||
sumAssetB = thisObject.truncDecimals(sumAssetB);
|
||||
|
||||
if (position.amountB !== sumAssetB) {
|
||||
logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> position.amountB = " + position.amountB);
|
||||
logger.write(MODULE_NAME, "[ERROR] ordersExecutionCheck -> loopBody -> sumAssetB = " + sumAssetB);
|
||||
logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> position.amountB = " + position.amountB);
|
||||
logger.write(MODULE_NAME, "[INFO] ordersExecutionCheck -> loopBody -> sumAssetB = " + sumAssetB);
|
||||
|
||||
logger.write(MODULE_NAME, "[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.");
|
||||
logger.write(MODULE_NAME, "[INFO] 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.");
|
||||
logger.write(MODULE_NAME, "[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> If the process was abruptally cancelled and then restarted, it is possible that now is not sincronized with the exchange.");
|
||||
logger.write(MODULE_NAME, "[HINT] ordersExecutionCheck -> loopBody -> confirmOrderWasExecuted -> In any case, to continue, you must manually delete the orders at the exchange.");
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
@@ -1230,6 +1230,13 @@
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
function getPublicTradeHistory(assetA, assetB, startTime, endTime, callback) {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTradeHistory -> Entering function."); }
|
||||
|
||||
exchangeAPI.getPublicTradeHistory(assetA, assetB, startTime, endTime, callback);
|
||||
}
|
||||
|
||||
function recalculateRateAverages() {
|
||||
|
||||
@@ -1409,7 +1416,7 @@
|
||||
|
||||
function truncDecimals(pFloatValue) {
|
||||
|
||||
return parseFloat(parseFloat(pFloatValue).toFixed(8));
|
||||
return parseFloat(parseFloat(pFloatValue).toFixed(6)); //TODO Number of decimals depends on the exchange
|
||||
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,540 @@
|
||||
exports.newBinanceAPIClient = function newBinanceAPIClient(pKey, pSecret, logger) {
|
||||
|
||||
const FULL_LOG = true;
|
||||
const LOG_FILE_CONTENT = true;
|
||||
const MODULE_NAME = "Binance API Client";
|
||||
|
||||
// MAX Decimal numers: 6
|
||||
/*
|
||||
/* ATENTION: This Library is used both a the cloud (AACloud) and also at the AAWeb on the server side without any modifications.
|
||||
/* There is a second version, stripped of all the inner functionality that runs at AAWeb browser side, which channels the requests to the server side one.
|
||||
/*
|
||||
/* Documentation @ https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
|
||||
/* @ https://support.binance.com/hc/en-us/articles/115000594711-Trading-Rule
|
||||
*/
|
||||
|
||||
let EMPTY_RESPONSE = "";
|
||||
let NOT_IMPLEMENTED = "Method not implemented yet.";
|
||||
|
||||
let newFunction = new API(pKey, pSecret);
|
||||
|
||||
let thisObject = {
|
||||
API: newFunction
|
||||
};
|
||||
|
||||
return thisObject;
|
||||
|
||||
function API(key, secret) {
|
||||
'use strict';
|
||||
|
||||
// Module dependencies
|
||||
var crypto = require('crypto'),
|
||||
request = require('request');
|
||||
|
||||
// Constants
|
||||
var recvWindow = '10000',
|
||||
API_URL = 'https://api.binance.com';
|
||||
|
||||
// Helper methods
|
||||
function joinCurrencies(currencyA, currencyB) {
|
||||
// If only one arg, then return the first
|
||||
if (typeof currencyB !== 'string') {
|
||||
return currencyA;
|
||||
}
|
||||
|
||||
return currencyB + '' + currencyA;
|
||||
}
|
||||
|
||||
function getDate() {
|
||||
let localDate = new Date();
|
||||
let date = new Date(Date.UTC(
|
||||
localDate.getUTCFullYear(),
|
||||
localDate.getUTCMonth(),
|
||||
localDate.getUTCDate(),
|
||||
localDate.getUTCHours(),
|
||||
localDate.getUTCMinutes(),
|
||||
localDate.getUTCSeconds(),
|
||||
localDate.getUTCMilliseconds()));
|
||||
return date.valueOf();
|
||||
}
|
||||
|
||||
function truncDecimals(pFloatValue) {
|
||||
|
||||
return parseFloat(parseFloat(pFloatValue).toFixed(6));
|
||||
|
||||
}
|
||||
|
||||
// Generate headers signed by thisObject user's key and secret.
|
||||
// The secret is encapsulated and never exposed
|
||||
function _getSignature(parameters) {
|
||||
var paramString, signature;
|
||||
|
||||
if (!key || !secret) {
|
||||
throw 'Binance: Error. API key and secret required';
|
||||
}
|
||||
|
||||
// Convert to `arg1=foo&arg2=bar`
|
||||
paramString = Object.keys(parameters).map(function (param) {
|
||||
return encodeURIComponent(param) + '=' + encodeURIComponent(parameters[param]);
|
||||
}).join('&');
|
||||
|
||||
signature = crypto.createHmac('sha256', secret).update(paramString).digest('hex');
|
||||
|
||||
return {
|
||||
signature: signature
|
||||
};
|
||||
};
|
||||
|
||||
// Currently, thisObject fails with `Error: CERT_UNTRUSTED`
|
||||
// Binance.STRICT_SSL can be set to `false` to avoid thisObject. Use with caution.
|
||||
// Will be removed in future, once thisObject is resolved.
|
||||
const STRICT_SSL = true;
|
||||
|
||||
// Prototype
|
||||
let thisObject = {
|
||||
|
||||
// Make an API request
|
||||
_request: function (options, callback) {
|
||||
if (!('headers' in options)) {
|
||||
options.headers = {};
|
||||
}
|
||||
|
||||
options.json = true;
|
||||
options.headers['X-MBX-APIKEY'] = key;
|
||||
options.strictSSL = STRICT_SSL;
|
||||
if (LOG_FILE_CONTENT === true) { logger.write(MODULE_NAME, "[INFO] request -> options = " + JSON.stringify(options)); }
|
||||
|
||||
request(options, function (err, response, body) {
|
||||
|
||||
if (LOG_FILE_CONTENT === true) { logger.write(MODULE_NAME, "[INFO] response -> err = " + JSON.stringify(err) + ". response: " + JSON.stringify(response) + ". body:" + JSON.stringify(body)); }
|
||||
|
||||
// Empty response
|
||||
if (!err && (typeof body === 'undefined' || body === null)) {
|
||||
err = 'Empty response';
|
||||
}
|
||||
|
||||
thisObject.analizeResponse(err, body, callback);
|
||||
});
|
||||
|
||||
return thisObject;
|
||||
},
|
||||
|
||||
// Make an API request MARKET_DATA or USER_STREAM: Endpoint requires sending a valid API-Key.
|
||||
_public: function (command, parameters, callback) {
|
||||
var options;
|
||||
|
||||
if (typeof parameters === 'function') {
|
||||
callback = parameters;
|
||||
parameters = {};
|
||||
}
|
||||
|
||||
parameters || (parameters = {});
|
||||
options = {
|
||||
method: 'GET',
|
||||
url: API_URL + command,
|
||||
qs: parameters
|
||||
};
|
||||
|
||||
return thisObject._request(options, callback);
|
||||
},
|
||||
|
||||
// Make an API request MARKET_DATA or USER_STREAM: Endpoint requires sending a valid API-Key.
|
||||
_signed: function (command, parameters, callback) {
|
||||
var options;
|
||||
|
||||
if (typeof parameters === 'function') {
|
||||
callback = parameters;
|
||||
parameters = {};
|
||||
}
|
||||
|
||||
parameters || (parameters = {});
|
||||
options = {
|
||||
method: 'GET',
|
||||
url: API_URL + command,
|
||||
qs: parameters
|
||||
};
|
||||
options.qs.signature = _getSignature(parameters).signature;
|
||||
return thisObject._request(options, callback);
|
||||
},
|
||||
|
||||
// Make an API request TRADE or USER_DATA: Endpoint requires sending a valid API-Key and signature.
|
||||
_private: function (command, parameters, callback, pMethod) {
|
||||
var options;
|
||||
let method;
|
||||
|
||||
if (typeof parameters === 'function') {
|
||||
callback = parameters;
|
||||
parameters = {};
|
||||
}
|
||||
|
||||
if (pMethod === 'DELETE') {
|
||||
method = pMethod;
|
||||
} else {
|
||||
method = 'POST'; // Default value
|
||||
}
|
||||
|
||||
parameters || (parameters = {});
|
||||
options = {
|
||||
method: method,
|
||||
url: API_URL + command,
|
||||
form: parameters,
|
||||
qs: _getSignature(parameters)
|
||||
};
|
||||
|
||||
return thisObject._request(options, callback);
|
||||
},
|
||||
|
||||
/////// NON SIGNED METHODS
|
||||
|
||||
returnTicker: function (currencyA, currencyB, callback) {
|
||||
var parameters = {
|
||||
symbol: joinCurrencies(currencyA, currencyB)
|
||||
};
|
||||
|
||||
thisObject._public('/api/v1/ticker/24hr', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let ticker;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
ticker = {
|
||||
bid: Number(response.bidPrice),
|
||||
ask: Number(response.askPrice),
|
||||
last: Number(response.lastPrice)
|
||||
};
|
||||
}
|
||||
callback(err, ticker);
|
||||
}
|
||||
},
|
||||
|
||||
return24hVolume: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED , callback);
|
||||
},
|
||||
|
||||
returnOrderBook: function (currencyA, currencyB, depth, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnOrderBooks: function (depth, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnPublicTradeHistory: function (currencyA, currencyB, start, end, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnChartData: function (currencyA, currencyB, period, start, end, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnCurrencies: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnLoanOrders: function (currency, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
/////// SIGNED METHODS
|
||||
|
||||
returnBalances: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnCompleteBalances: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnDepositAddresses: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
generateNewAddress: function (currency, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnDepositsWithdrawals: function (start, end, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnOpenOrders: function (currencyA, currencyB, callback) {
|
||||
var parameters = {
|
||||
symbol: joinCurrencies(currencyA, currencyB),
|
||||
recvWindow: recvWindow,
|
||||
timestamp: getDate().valueOf()
|
||||
};
|
||||
|
||||
thisObject._signed('/api/v3/openOrders', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let exchangePositions = [];
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
for (let i = 0; i < response.length; i++) {
|
||||
let openPosition = {
|
||||
id: response[i].orderId,
|
||||
type: response[i].side.toLowerCase(),
|
||||
rate: Number(response[i].price),
|
||||
amountA: truncDecimals(response[i].origQty * response[i].price),
|
||||
amountB: Number(response[i].origQty),
|
||||
date: (new Date(response[i].time)).valueOf()
|
||||
};
|
||||
exchangePositions.push(openPosition);
|
||||
}
|
||||
}
|
||||
callback(err, exchangePositions);
|
||||
}
|
||||
},
|
||||
|
||||
returnTradeHistory: function (currencyA, currencyB, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnOrderTrades: function (orderNumber, callback) {
|
||||
|
||||
var parameters = {
|
||||
symbol: joinCurrencies('USDT', 'BTC'), // TODO add parameters
|
||||
timestamp: getDate().valueOf()
|
||||
};
|
||||
|
||||
thisObject._signed('/api/v3/myTrades', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let exchangeTrades = [];
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
for (let i = 0; i < response.length; i++) {
|
||||
if (response[i].orderId === orderNumber) {
|
||||
let type = "sell"
|
||||
if (response[i].isBuyer === true) {
|
||||
type = "buy";
|
||||
}
|
||||
let trade = {
|
||||
id: response[i].orderId,
|
||||
type: type,
|
||||
rate: Number(response[i].price),
|
||||
amountA: truncDecimals(response[i].qty * response[i].price),
|
||||
amountB: Number(response[i].qty),
|
||||
fee: Number(response[i].commission),
|
||||
date: (new Date(response[i].time)).valueOf()
|
||||
};
|
||||
exchangeTrades.push(trade);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
callback(err, exchangeTrades);
|
||||
}
|
||||
},
|
||||
|
||||
buy: function (currencyA, currencyB, rate, amount, callback) {
|
||||
thisObject._putOrder(currencyA, currencyB, rate, amount, 'BUY', callback);
|
||||
},
|
||||
|
||||
sell: function (currencyA, currencyB, rate, amount, callback) {
|
||||
thisObject._putOrder(currencyA, currencyB, rate, amount, 'SELL', callback);
|
||||
},
|
||||
|
||||
_putOrder: function (currencyA, currencyB, rate, amount, side, callback) {
|
||||
|
||||
// TODO ERROR management, if total < 10 return error on sells
|
||||
|
||||
var parameters = {
|
||||
symbol: joinCurrencies(currencyA, currencyB),
|
||||
side: side,
|
||||
type: 'LIMIT',
|
||||
quantity: truncDecimals(amount),
|
||||
price: rate,
|
||||
timestamp: getDate().valueOf(),
|
||||
timeInForce: 'GTC'
|
||||
};
|
||||
|
||||
thisObject._private('/api/v3/order', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let orderNumber;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
orderNumber = response.orderId;
|
||||
}
|
||||
callback(err, orderNumber);
|
||||
}
|
||||
},
|
||||
|
||||
cancelOrder: function (currencyA, currencyB, orderNumber, callback) {
|
||||
var parameters = {
|
||||
symbol: joinCurrencies(currencyA, currencyB),
|
||||
orderId: orderNumber,
|
||||
timestamp: getDate().valueOf(),
|
||||
};
|
||||
|
||||
thisObject._private('/api/v3/order', parameters, processResponse, 'DELETE');
|
||||
|
||||
function processResponse(err, response) {
|
||||
let orderNumber;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
orderNumber = response.orderId;
|
||||
}
|
||||
callback(err, orderNumber);
|
||||
}
|
||||
},
|
||||
|
||||
moveOrder: function (position, rate, amount, callback) {
|
||||
thisObject.cancelOrder('USDT', 'BTC', orderNumber, processResponse); //TODO Maybe we will need to query the order to check executedQty
|
||||
|
||||
function processResponse(err, response) {
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
if (position.type === "buy")
|
||||
thisObject.buy('USDT', 'BTC', rate, truncDecimals(amount), callback);
|
||||
else
|
||||
thisObject.sell('USDT', 'BTC', rate, truncDecimals(amount), callback);
|
||||
} else {
|
||||
callback(err);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
withdraw: function (currency, amount, address, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnFeeInfo: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnAvailableAccountBalances: function (account, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnTradableBalances: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
transferBalance: function (currency, amount, fromAccount, toAccount, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnMarginAccountSummary: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
marginBuy: function (currencyA, currencyB, rate, amount, lendingRate, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
marginSell: function (currencyA, currencyB, rate, amount, lendingRate, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
getMarginPosition: function (currencyA, currencyB, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
closeMarginPosition: function (currencyA, currencyB, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
createLoanOffer: function (currency, amount, duration, autoRenew, lendingRate, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
cancelLoanOffer: function (orderNumber, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnOpenLoanOffers: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnActiveLoans: function (callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
returnLendingHistory: function (start, end, limit, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
toggleAutoRenew: function (orderNumber, callback) {
|
||||
analizeResponse(EMPTY_RESPONSE, NOT_IMPLEMENTED, callback);
|
||||
},
|
||||
|
||||
analizeResponse: function (exchangeErr, exchangeResponse, callBack) {
|
||||
/* This function analizes the different situations we might encounter trying to access Binance and returns appropiate standard errors. */
|
||||
|
||||
let stringExchangeResponse = JSON.stringify(exchangeResponse);
|
||||
let stringExchangeErr = JSON.stringify(exchangeErr);
|
||||
|
||||
try {
|
||||
|
||||
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeErr = " + stringExchangeErr); }
|
||||
if (LOG_FILE_CONTENT === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeResponse = " + stringExchangeResponse); }
|
||||
|
||||
if (stringExchangeErr.indexOf("ETIMEDOUT") > 0 ||
|
||||
stringExchangeErr.indexOf("ENOTFOUND") > 0 ||
|
||||
stringExchangeErr.indexOf("ECONNREFUSED") > 0 ||
|
||||
stringExchangeErr.indexOf("ESOCKETTIMEDOUT") > 0 ||
|
||||
stringExchangeErr.indexOf("ECONNRESET") > 0 ||
|
||||
(stringExchangeResponse !== undefined && (
|
||||
stringExchangeResponse.indexOf("Connection timed out") > 0 ||
|
||||
stringExchangeResponse.indexOf("Connection Error") > 0 ||
|
||||
stringExchangeResponse.indexOf("Bad gateway") > 0 ||
|
||||
stringExchangeResponse.indexOf("Internal error. Please try again") > 0))) {
|
||||
|
||||
logger.write(MODULE_NAME, "[WARN] analizeResponse -> Timeout reached or connection problem while trying to access the Exchange API. Requesting new execution later.");
|
||||
logger.write(MODULE_NAME, "[WARN] analizeResponse -> stringExchangeErr = " + stringExchangeErr);
|
||||
|
||||
callBack(global.DEFAULT_RETRY_RESPONSE);
|
||||
return;
|
||||
|
||||
} else {
|
||||
|
||||
if (stringExchangeResponse.indexOf("code") > 0) {
|
||||
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected response from the Exchange.");
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> JSON.stringify(exchangeErr) = " + stringExchangeErr);
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> JSON.stringify(exchangeResponse) = " + stringExchangeResponse);
|
||||
|
||||
/* {"error":"Not enough USDT.","success":0}*/
|
||||
|
||||
if (stringExchangeResponse.indexOf("Not enough") > 0) {
|
||||
|
||||
let err = {
|
||||
resutl: global.CUSTOM_FAIL_RESPONSE.result,
|
||||
message: exchangeResponse.error
|
||||
};
|
||||
|
||||
callBack(err);
|
||||
|
||||
} else {
|
||||
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (exchangeErr) {
|
||||
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected error trying to contact the Exchange.");
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeErr = " + stringExchangeErr);
|
||||
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
|
||||
} else {
|
||||
|
||||
logger.write(MODULE_NAME, "[INFO] analizeResponse -> No problem found.");
|
||||
callBack(global.DEFAULT_OK_RESPONSE, exchangeResponse);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> err.message = " + err.message);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return thisObject;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+1
-1
@@ -329,7 +329,7 @@
|
||||
*/
|
||||
|
||||
const INITIAL_INVESTMENT_A = 0; // This is just for this release of the platform.
|
||||
const INITIAL_INVESTMENT_B = .001; // This is just for this release of the platform.
|
||||
const INITIAL_INVESTMENT_B = .002; // This is just for this release of the platform.
|
||||
|
||||
thisObject.executionContext = {
|
||||
investment: { // This is used to calculate profits.
|
||||
|
||||
+91
-268
@@ -16,7 +16,8 @@
|
||||
getExecutedTrades: getExecutedTrades,
|
||||
putPosition: putPosition,
|
||||
movePosition: movePosition,
|
||||
getTicker: getTicker
|
||||
getTicker: getTicker,
|
||||
getPublicTradeHistory: getPublicTradeHistory
|
||||
};
|
||||
|
||||
let poloniexApiClient;
|
||||
@@ -24,12 +25,12 @@
|
||||
return thisObject;
|
||||
|
||||
function initialize(callBackFunction) {
|
||||
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] initialize -> Entering function."); }
|
||||
|
||||
poloniexApiClient = POLONIEX_CLIENT_MODULE.newPoloniexAPIClient(global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Key, global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Secret);
|
||||
//poloniexApiClient = POLONIEX_CLIENT_MODULE.newPoloniexAPIClient(global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Key, global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Secret, logger);
|
||||
poloniexApiClient = POLONIEX_CLIENT_MODULE.newBinanceAPIClient(global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Key, global.EXCHANGE_KEYS[global.EXCHANGE_NAME].Secret, logger);
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE);
|
||||
|
||||
@@ -40,147 +41,65 @@
|
||||
}
|
||||
}
|
||||
|
||||
function getOpenPositions(pMarket, callBackFunction) {
|
||||
|
||||
/*
|
||||
* Returns the open positions ath the exchange for a given market and user account.
|
||||
* The object returned is an array of positions:
|
||||
* position = {
|
||||
* id,
|
||||
* type,
|
||||
* rate,
|
||||
* amountA,
|
||||
* amountB,
|
||||
* fee, (not required)
|
||||
* datetime
|
||||
* };
|
||||
*/
|
||||
function getOpenPositions(pMarket, callBack) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> pMarket = " + JSON.stringify(pMarket)); }
|
||||
|
||||
poloniexApiClient.API.returnOpenOrders(pMarket.assetA, pMarket.assetB, onExchangeCallReturned);
|
||||
poloniexApiClient.API.returnOpenOrders(pMarket.assetA, pMarket.assetB, callBack);
|
||||
|
||||
function onExchangeCallReturned(err, exchangeResponse) {
|
||||
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> err = " + err); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] getOpenPositions -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); }
|
||||
|
||||
poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk);
|
||||
|
||||
function onResponseOk() {
|
||||
|
||||
/*
|
||||
|
||||
This is what we receive from the exchange. We will convert this to our standard format for later use.
|
||||
|
||||
[ { orderNumber: '151918418632',
|
||||
type: 'sell',
|
||||
rate: '20000.00000000',
|
||||
startingAmount: '0.00010000',
|
||||
amount: '0.00010000',
|
||||
total: '2.00000000',
|
||||
date: '2018-02-24 11:14:17',
|
||||
margin: 0 } ]
|
||||
|
||||
*/
|
||||
|
||||
let exchangePositions = [];
|
||||
|
||||
for (let i = 0; i < exchangeResponse.length; i++) {
|
||||
|
||||
let openPosition = {
|
||||
id: exchangeResponse[i].orderNumber,
|
||||
type: exchangeResponse[i].type,
|
||||
rate: exchangeResponse[i].rate,
|
||||
amountA: exchangeResponse[i].total,
|
||||
amountB: exchangeResponse[i].amount,
|
||||
date: (new Date(exchangeResponse[i].date)).valueOf()
|
||||
};
|
||||
|
||||
exchangePositions.push(openPosition);
|
||||
}
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE, exchangePositions);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] getOpenPositions -> onExchangeCallReturned -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] getOpenPositions -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
function getExecutedTrades(pPositionId, callBackFunction) {
|
||||
|
||||
/*
|
||||
* Returns the trades for a given order number.
|
||||
* The object returned is an array of positions:
|
||||
* position = {
|
||||
* id,
|
||||
* type,
|
||||
* rate,
|
||||
* amountA,
|
||||
* amountB,
|
||||
* fee,
|
||||
* datetime
|
||||
* };
|
||||
*/
|
||||
function getExecutedTrades(pPositionId, callBack) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> pPositionId = " + pPositionId); }
|
||||
|
||||
poloniexApiClient.API.returnOrderTrades(pPositionId, onExchangeCallReturned);
|
||||
poloniexApiClient.API.returnOrderTrades(pPositionId, callBack);
|
||||
|
||||
function onExchangeCallReturned(err, exchangeResponse) {
|
||||
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> err = " + err); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] getExecutedTrades -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); }
|
||||
|
||||
poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk);
|
||||
|
||||
function onResponseOk() {
|
||||
|
||||
/*
|
||||
|
||||
This is what we receive from the exchange. We will convert this to our standard format for later use.
|
||||
|
||||
[
|
||||
{
|
||||
"globalTradeID": 20825863,
|
||||
"tradeID": 147142,
|
||||
"currencyPair":
|
||||
"BTC_XVC",
|
||||
"type": "buy",
|
||||
"rate": "0.00018500",
|
||||
"amount": "455.34206390",
|
||||
"total": "0.08423828",
|
||||
"fee": "0.00200000",
|
||||
"date": "2016-03-14 01:04:36"
|
||||
},
|
||||
...]
|
||||
|
||||
*/
|
||||
|
||||
let trades = [];
|
||||
|
||||
for (let i = 0; i < exchangeResponse.length; i++) {
|
||||
|
||||
let trade = {
|
||||
id: exchangeResponse[i].tradeID,
|
||||
type: exchangeResponse[i].type,
|
||||
rate: exchangeResponse[i].rate,
|
||||
amountA: exchangeResponse[i].total,
|
||||
amountB: exchangeResponse[i].amount,
|
||||
fee: exchangeResponse[i].fee,
|
||||
date: (new Date(exchangeResponse[i].date)).valueOf()
|
||||
}
|
||||
|
||||
trades.push(trade);
|
||||
}
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE, trades);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] getExecutedTrades -> onExchangeCallReturned -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] getExecutedTrades -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
function putPosition(pMarket, pType, pRate, pAmountA, pAmountB, callBackFunction) {
|
||||
|
||||
/*
|
||||
* Creates a new buy or sell order.
|
||||
* The orderNumber is returned.
|
||||
*/
|
||||
function putPosition(pMarket, pType, pRate, pAmountA, pAmountB, callBack) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> Entering function."); }
|
||||
@@ -191,186 +110,90 @@
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> pAmountB = " + pAmountB); }
|
||||
|
||||
if (pType === "buy") {
|
||||
poloniexApiClient.API.buy(pMarket.assetA, pMarket.assetB, pRate, pAmountB, onExchangeCallReturned);
|
||||
poloniexApiClient.API.buy(pMarket.assetA, pMarket.assetB, pRate, pAmountB, callBack);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pType === "sell") {
|
||||
poloniexApiClient.API.sell(pMarket.assetA, pMarket.assetB, pRate, pAmountB, onExchangeCallReturned);
|
||||
poloniexApiClient.API.sell(pMarket.assetA, pMarket.assetB, pRate, pAmountB, callBack);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.write(MODULE_NAME, "[ERROR] putPosition -> pType must be either 'buy' or 'sell'.");
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
|
||||
function onExchangeCallReturned(err, exchangeResponse) {
|
||||
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> err = " + err); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] putPosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); }
|
||||
|
||||
poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk);
|
||||
|
||||
function onResponseOk() {
|
||||
|
||||
/*
|
||||
|
||||
This is what we can receive from the exchange.
|
||||
|
||||
{
|
||||
"orderNumber":31226040,
|
||||
"resultingTrades":
|
||||
[{
|
||||
"amount":"338.8732",
|
||||
"date":"2014-10-18 23:03:21",
|
||||
"rate":"0.00000173",
|
||||
"total":"0.00058625",
|
||||
"tradeID":"16164",
|
||||
"type":"buy"
|
||||
}]
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE, exchangeResponse.orderNumber);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] putPosition -> onExchangeCallReturned -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] putPosition -> err = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
function movePosition(pPosition, pNewRate, pNewAmountB, callBackFunction) {
|
||||
|
||||
/*
|
||||
* Move an existing position to the new rate.
|
||||
* The new orderNumber is returned.
|
||||
*/
|
||||
function movePosition(pPosition, pNewRate, pNewAmountB, callBack) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pPosition = " + JSON.stringify(pPosition)); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> pNewRate = " + pNewRate); }
|
||||
|
||||
poloniexApiClient.API.moveOrder(pPosition.id, pNewRate, pNewAmountB, onExchangeCallReturned);
|
||||
|
||||
function onExchangeCallReturned(err, exchangeResponse) {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> err = " + err); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); }
|
||||
|
||||
try {
|
||||
|
||||
poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk);
|
||||
|
||||
function onResponseOk() {
|
||||
|
||||
if (exchangeResponse.success !== 1) {
|
||||
logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> exchangeResponse.success = " + exchangeResponse.success);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
}
|
||||
/*
|
||||
|
||||
This is what we can receive from the exchange.
|
||||
|
||||
{
|
||||
"orderNumber":31226040,
|
||||
"resultingTrades":
|
||||
[{
|
||||
"amount":"338.8732",
|
||||
"date":"2014-10-18 23:03:21",
|
||||
"rate":"0.00000173",
|
||||
"total":"0.00058625",
|
||||
"tradeID":"16164",
|
||||
"type":"buy"
|
||||
}]
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE, exchangeResponse.orderNumber);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
poloniexApiClient.API.moveOrder(pPosition, pNewRate, pNewAmountB, callBack);
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] movePosition -> err = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
function getTicker(pMarket, callBackFunction) {
|
||||
|
||||
/*
|
||||
* Returns the price for a given pair of assets.
|
||||
* The object returned is an array of trades:
|
||||
* ticker = {
|
||||
* bid,
|
||||
* ask,
|
||||
* last
|
||||
* };
|
||||
*/
|
||||
function getTicker(pMarket, callBack) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTicker -> Entering function."); }
|
||||
|
||||
poloniexApiClient.API.returnTicker(onExchangeCallReturned);
|
||||
|
||||
function onExchangeCallReturned(err, exchangeResponse) {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> Entering function."); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> err = " + err); }
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logContent === true) { logger.write(MODULE_NAME, "[INFO] movePosition -> onExchangeCallReturned -> exchangeResponse = " + JSON.stringify(exchangeResponse)); }
|
||||
|
||||
try {
|
||||
|
||||
poloniexApiClient.API.analizeResponse(logger, err, exchangeResponse, callBackFunction, onResponseOk);
|
||||
|
||||
function onResponseOk() {
|
||||
|
||||
/*
|
||||
|
||||
This is what we can receive from the exchange.
|
||||
|
||||
{"BTC_LTC":{ "last":"0.0251",
|
||||
"lowestAsk":"0.02589999",
|
||||
"highestBid":"0.0251",
|
||||
"percentChange":"0.02390438",
|
||||
"baseVolume":"6.16485315",
|
||||
"quoteVolume":"245.82513926"
|
||||
},
|
||||
"BTC_NXT":{ "last":"0.00005730",
|
||||
"lowestAsk":"0.00005710",
|
||||
"highestBid":"0.00004903",
|
||||
"percentChange":"0.16701570",
|
||||
"baseVolume":"0.45347489",
|
||||
"quoteVolume":"9094"
|
||||
},
|
||||
... }
|
||||
|
||||
*/
|
||||
|
||||
let ticker = {
|
||||
bid: Number(exchangeResponse[pMarket].highestBid),
|
||||
ask: Number(exchangeResponse[pMarket].lowestAsk),
|
||||
last: Number(exchangeResponse[pMarket].last)
|
||||
};
|
||||
|
||||
callBackFunction(global.DEFAULT_OK_RESPONSE, ticker);
|
||||
}
|
||||
}
|
||||
catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] movePosition -> onExchangeCallReturned -> Error = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
poloniexApiClient.API.returnTicker(pMarket.assetA, pMarket.assetB, callBack);
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] movePosition -> err = " + err.message);
|
||||
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns all the trade history from the Exchange since startTime to endTime orderd by tradeId.
|
||||
* It's possible that the exchange doesn't support this method.
|
||||
* The object returned is an array of trades:
|
||||
* trade = {
|
||||
* tradeIdAtExchange,
|
||||
* marketIdAtExchange,
|
||||
* type,
|
||||
* rate,
|
||||
* amountA,
|
||||
* amountB,
|
||||
* datetime
|
||||
* };
|
||||
*/
|
||||
function getPublicTradeHistory(assetA, assetB, startTime, endTime, callback) {
|
||||
try {
|
||||
|
||||
if (global.LOG_CONTROL[MODULE_NAME].logInfo === true) { logger.write(MODULE_NAME, "[INFO] getTradeHistory -> Entering function."); }
|
||||
|
||||
poloniexApiClient.API.returnPublicTradeHistory(assetA, assetB, startTime, endTime, callback);
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] getTradeHistory -> err = " + err.message);
|
||||
callback(global.DEFAULT_FAIL_RESPONSE);
|
||||
}
|
||||
}
|
||||
};
|
||||
+100
-26
@@ -1,4 +1,6 @@
|
||||
exports.newPoloniexAPIClient = function newPoloniexAPIClient(pKey, pSecret) {
|
||||
exports.newPoloniexAPIClient = function newPoloniexAPIClient(pKey, pSecret, logger) {
|
||||
|
||||
// MAX Decimal numers: 8
|
||||
|
||||
/*
|
||||
/* ATENTION: This Library is used both a the cloud (AACloud) and also at the AAWeb on the server side without any modifications.
|
||||
@@ -84,7 +86,7 @@
|
||||
err = 'Empty response';
|
||||
}
|
||||
|
||||
callback(err, body);
|
||||
thisObject.analizeResponse(err, body, callback);
|
||||
});
|
||||
|
||||
return thisObject;
|
||||
@@ -137,8 +139,21 @@
|
||||
/////
|
||||
// PUBLIC METHODS
|
||||
|
||||
returnTicker: function (callback) {
|
||||
return thisObject._public('returnTicker', callback);
|
||||
returnTicker: function (currencyA, currencyB, callback) {
|
||||
thisObject._public('returnTicker', processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let ticker;
|
||||
let market = joinCurrencies(currencyA, currencyB);
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
ticker = {
|
||||
bid: Number(response[market].highestBid),
|
||||
ask: Number(response[market].lowestAsk),
|
||||
last: Number(response[market].last)
|
||||
};
|
||||
}
|
||||
callback(err, ticker);
|
||||
}
|
||||
},
|
||||
|
||||
return24hVolume: function (callback) {
|
||||
@@ -220,7 +235,25 @@
|
||||
currencyPair: joinCurrencies(currencyA, currencyB)
|
||||
};
|
||||
|
||||
return thisObject._private('returnOpenOrders', parameters, callback);
|
||||
thisObject._private('returnOpenOrders', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let exchangePositions = [];
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
for (let i = 0; i < response.length; i++) {
|
||||
let openPosition = {
|
||||
id: response[i].orderNumber,
|
||||
type: response[i].type,
|
||||
rate: response[i].rate,
|
||||
amountA: response[i].total,
|
||||
amountB: response[i].amount,
|
||||
date: (new Date(response[i].time)).valueOf()
|
||||
};
|
||||
exchangePositions.push(openPosition);
|
||||
}
|
||||
}
|
||||
callback(err, exchangePositions);
|
||||
}
|
||||
},
|
||||
|
||||
returnTradeHistory: function (currencyA, currencyB, callback) {
|
||||
@@ -236,7 +269,26 @@
|
||||
orderNumber: orderNumber
|
||||
};
|
||||
|
||||
return thisObject._private('returnOrderTrades', parameters, callback);
|
||||
thisObject._private('returnOrderTrades', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let trades = [];
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
for (let i = 0; i < response.length; i++) {
|
||||
let trade = {
|
||||
id: response[i].tradeID,
|
||||
type: response[i].type,
|
||||
rate: response[i].rate,
|
||||
amountA: response[i].total,
|
||||
amountB: response[i].amount,
|
||||
fee: response[i].fee,
|
||||
date: (new Date(response[i].date)).valueOf()
|
||||
}
|
||||
trades.push(trade);
|
||||
}
|
||||
}
|
||||
callback(err, trades);
|
||||
}
|
||||
},
|
||||
|
||||
buy: function (currencyA, currencyB, rate, amount, callback) {
|
||||
@@ -246,7 +298,15 @@
|
||||
amount: amount
|
||||
};
|
||||
|
||||
return thisObject._private('buy', parameters, callback);
|
||||
thisObject._private('buy', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let orderNumber;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
orderNumber = response.orderNumber;
|
||||
}
|
||||
callback(err, orderNumber);
|
||||
}
|
||||
},
|
||||
|
||||
sell: function (currencyA, currencyB, rate, amount, callback) {
|
||||
@@ -256,7 +316,15 @@
|
||||
amount: amount
|
||||
};
|
||||
|
||||
return thisObject._private('sell', parameters, callback);
|
||||
thisObject._private('sell', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let orderNumber;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
orderNumber = response.orderNumber;
|
||||
}
|
||||
callback(err, orderNumber);
|
||||
}
|
||||
},
|
||||
|
||||
cancelOrder: function (currencyA, currencyB, orderNumber, callback) {
|
||||
@@ -275,7 +343,15 @@
|
||||
amount: amount ? amount : null
|
||||
};
|
||||
|
||||
return thisObject._private('moveOrder', parameters, callback);
|
||||
thisObject._private('moveOrder', parameters, processResponse);
|
||||
|
||||
function processResponse(err, response) {
|
||||
let orderNumber;
|
||||
if (err.result === global.DEFAULT_OK_RESPONSE.result) {
|
||||
orderNumber = response.orderNumber;
|
||||
}
|
||||
callback(err, orderNumber);
|
||||
}
|
||||
},
|
||||
|
||||
withdraw: function (currency, amount, address, callback) {
|
||||
@@ -399,7 +475,7 @@
|
||||
return thisObject._private('toggleAutoRenew', { orderNumber: orderNumber }, callback);
|
||||
},
|
||||
|
||||
analizeResponse: function (logger, exchangeErr, exchangeResponse, notOkCallBack, okCallBack) {
|
||||
analizeResponse: function (exchangeErr, exchangeResponse, callBack) {
|
||||
|
||||
const FULL_LOG = true;
|
||||
const LOG_FILE_CONTENT = true;
|
||||
@@ -407,10 +483,10 @@
|
||||
|
||||
/* This function analizes the different situations we might encounter trying to access Poloniex and returns appropiate standard errors. */
|
||||
|
||||
try {
|
||||
let stringExchangeResponse = JSON.stringify(exchangeResponse);
|
||||
let stringExchangeErr = JSON.stringify(exchangeErr);
|
||||
|
||||
let stringExchangeResponse = JSON.stringify(exchangeResponse);
|
||||
let stringExchangeErr = JSON.stringify(exchangeErr);
|
||||
try {
|
||||
|
||||
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeErr = " + stringExchangeErr); }
|
||||
if (LOG_FILE_CONTENT === true) { logger.write(MODULE_NAME, "[INFO] analizeResponse -> exchangeResponse = " + stringExchangeResponse); }
|
||||
@@ -429,33 +505,31 @@
|
||||
logger.write(MODULE_NAME, "[WARN] analizeResponse -> Timeout reached or connection problem while trying to access the Exchange API. Requesting new execution later.");
|
||||
logger.write(MODULE_NAME, "[WARN] analizeResponse -> stringExchangeErr = " + stringExchangeErr);
|
||||
|
||||
notOkCallBack(global.DEFAULT_RETRY_RESPONSE);
|
||||
callBack(global.DEFAULT_RETRY_RESPONSE);
|
||||
return;
|
||||
|
||||
} else {
|
||||
|
||||
if (JSON.stringify(exchangeResponse).indexOf("error") > 0) {
|
||||
if (stringExchangeResponse.indexOf("error") > 0) {
|
||||
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected response from the Exchange.");
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> JSON.stringify(exchangeErr) = " + JSON.stringify(exchangeErr));
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeErr = " + exchangeErr);
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeResponse = " + exchangeResponse);
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> JSON.stringify(exchangeResponse) = " + JSON.stringify(exchangeResponse));
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> JSON.stringify(exchangeErr) = " + stringExchangeErr);
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeResponse = " + stringExchangeResponse);
|
||||
|
||||
/* {"error":"Not enough USDT.","success":0}*/
|
||||
|
||||
if (JSON.stringify(exchangeResponse).indexOf("Not enough") > 0) {
|
||||
if (stringExchangeResponse.indexOf("Not enough") > 0) {
|
||||
|
||||
let err = {
|
||||
resutl: global.CUSTOM_FAIL_RESPONSE.result,
|
||||
message: exchangeResponse.error
|
||||
};
|
||||
|
||||
notOkCallBack(err);
|
||||
callBack(err);
|
||||
|
||||
} else {
|
||||
|
||||
notOkCallBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
|
||||
}
|
||||
return;
|
||||
@@ -464,22 +538,22 @@
|
||||
if (exchangeErr) {
|
||||
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> Unexpected error trying to contact the Exchange.");
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeErr = " + exchangeErr);
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> exchangeErr = " + stringExchangeErr);
|
||||
|
||||
notOkCallBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
|
||||
} else {
|
||||
|
||||
logger.write(MODULE_NAME, "[INFO] analizeResponse -> No problem found.");
|
||||
okCallBack();
|
||||
callBack(global.DEFAULT_OK_RESPONSE, exchangeResponse);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
logger.write(MODULE_NAME, "[ERROR] analizeResponse -> err.message = " + err.message);
|
||||
notOkCallBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
callBack(global.DEFAULT_FAIL_RESPONSE);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user