Live Trading working tested at Binance

This commit is contained in:
Luis Fernando Molina committed 2020-02-07 16:50:11 +01:00
1 parent 1ba29a7bad
commit 15b8a9044d
63 files changed
+1675 -1970

No files matched your search

+98 -155
View File
@@ -39,7 +39,7 @@
timeFrameLabel,
currentDay,
interExecutionMemory,
assistant,
exchangeAPI,
callback,
callBackFunction) {
@@ -167,6 +167,8 @@
let periods = 0;
let positionPeriods = 0;
let closeRate
/* Usefull counters for conditions and formulas */
let distanceToLast = {
@@ -554,8 +556,6 @@
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> Candle Begin @ " + (new Date(candle.begin)).toLocaleString()) }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> Candle End @ " + (new Date(candle.end)).toLocaleString()) }
/* Assistant Info */
let ticker = {
bid: candle.close,
ask: candle.close,
@@ -706,7 +706,7 @@
if (openStage !== undefined) {
/* Default Values*/
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
positionSize = balanceBaseAsset;
positionRate = candle.close;
} else {
@@ -729,13 +729,13 @@
initialDefinition.positionSize.formula.error = err.message
}
if (isNaN(positionSize)) {
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
positionSize = balanceBaseAsset;
} else {
positionSize = balanceQuotedAsset;
}
} else {
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
if (positionSize > balanceBaseAsset) { positionSize = balanceBaseAsset }
} else {
if (positionSize > balanceQuotedAsset) { positionSize = balanceQuotedAsset }
@@ -756,7 +756,7 @@
initialDefinition.positionRate.formula.error = err.message
}
if (isNaN(positionRate)) {
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
positionRate = candle.close;
} else {
positionRate = candle.close;
@@ -1093,7 +1093,7 @@
let maximumBalance
let balance
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
balance = balanceBaseAsset
minimumBalance = bot.VALUES_TO_USE.minimumBalanceA
maximumBalance = bot.VALUES_TO_USE.maximumBalanceA
@@ -1675,7 +1675,7 @@
/* Stop Loss condition: Here we verify if the Stop Loss was hitted or not. */
if ((bot.VALUES_TO_USE.baseAsset === 'BTC' && candle.max >= stopLoss) || (bot.VALUES_TO_USE.baseAsset !== 'BTC' && candle.min <= stopLoss)) {
if ((bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset && candle.max >= stopLoss) || (bot.VALUES_TO_USE.baseAsset !== bot.market.baseAsset && candle.min <= stopLoss)) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> Stop Loss was hit."); }
/*
@@ -1685,7 +1685,7 @@
If we take the stop loss value at those situation would be a huge distortion of facts.
*/
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
if (stopLoss < candle.min) {
stopLoss = candle.min
if (processingDailyFiles) {
@@ -1710,42 +1710,15 @@
/* Apply the Slippage */
let slippageAmount = slippedStopLoss * bot.VALUES_TO_USE.slippage.stopLoss / 100
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
slippedStopLoss = slippedStopLoss + slippageAmount
} else {
slippedStopLoss = slippedStopLoss - slippageAmount
}
let finalStopLoss = slippedStopLoss;
closeRate = slippedStopLoss;
let feePaid = 0
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
strategy.positionSize = balanceQuotedAsset / finalStopLoss;
strategy.positionRate = finalStopLoss;
feePaid = balanceQuotedAsset / finalStopLoss * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceBaseAsset = balanceBaseAsset + balanceQuotedAsset / finalStopLoss - feePaid;
balanceQuotedAsset = 0;
} else {
strategy.positionSize = balanceBaseAsset * finalStopLoss;
strategy.positionRate = finalStopLoss;
feePaid = balanceBaseAsset * finalStopLoss * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceQuotedAsset = balanceQuotedAsset + balanceBaseAsset * finalStopLoss - feePaid;
balanceBaseAsset = 0;
}
if (processingDailyFiles) {
if (positionedAtYesterday) {
yesterday.balanceBaseAsset = balanceBaseAsset;
yesterday.balanceQuotedAsset = balanceQuotedAsset;
}
}
marketRate = finalStopLoss;
marketRate = closeRate;
type = '"Close@StopLoss"';
strategyStage = 'Close Stage';
stopLossStage = 'No Stage';
@@ -1753,7 +1726,7 @@
currentTrade.end = candle.end;
currentTrade.status = 1;
currentTrade.exitType = 1;
currentTrade.endRate = finalStopLoss;
currentTrade.endRate = closeRate;
closePositionNow = true;
@@ -1772,7 +1745,7 @@
/* Take Profit condition: Here we verify if the Take Profit was hit or not. */
if ((bot.VALUES_TO_USE.baseAsset === 'BTC' && candle.min <= takeProfit) || (bot.VALUES_TO_USE.baseAsset !== 'BTC' && candle.max >= takeProfit)) {
if ((bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset && candle.min <= takeProfit) || (bot.VALUES_TO_USE.baseAsset !== bot.market.baseAsset && candle.max >= takeProfit)) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> Take Profit was hit."); }
/*
@@ -1782,7 +1755,7 @@
If we take the stop loss value at those situation would be a huge distortion of facts.
*/
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
if (takeProfit > candle.max) {
takeProfit = candle.max
if (processingDailyFiles) {
@@ -1806,43 +1779,15 @@
/* Apply the Slippage */
let slippageAmount = slippedTakeProfit * bot.VALUES_TO_USE.slippage.takeProfit / 100
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
slippedTakeProfit = slippedTakeProfit + slippageAmount
} else {
slippedTakeProfit = slippedTakeProfit - slippageAmount
}
let finalTakeProfit = slippedTakeProfit;
closeRate = slippedTakeProfit;
let feePaid = 0
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
strategy.positionSize = balanceQuotedAsset / finalTakeProfit;
strategy.positionRate = finalTakeProfit;
feePaid = balanceQuotedAsset / finalTakeProfit * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceBaseAsset = balanceBaseAsset + balanceQuotedAsset / finalTakeProfit - feePaid;
balanceQuotedAsset = 0;
} else {
strategy.positionSize = balanceBaseAsset * finalTakeProfit;
strategy.positionRate = finalTakeProfit;
feePaid = balanceBaseAsset * finalTakeProfit * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceQuotedAsset = balanceQuotedAsset + balanceBaseAsset * finalTakeProfit - feePaid;
balanceBaseAsset = 0;
}
if (processingDailyFiles) {
if (positionedAtYesterday) {
yesterday.balanceBaseAsset = balanceBaseAsset;
yesterday.balanceQuotedAsset = balanceQuotedAsset;
}
}
marketRate = finalTakeProfit;
marketRate = closeRate;
type = '"Close@TakeProfit"';
strategyStage = 'Close Stage';
stopLossStage = 'No Stage';
@@ -1851,7 +1796,7 @@
currentTrade.end = candle.end;
currentTrade.status = 1;
currentTrade.exitType = 2;
currentTrade.endRate = finalTakeProfit;
currentTrade.endRate = closeRate;
closePositionNow = true;
@@ -1895,7 +1840,7 @@
/* We take what was calculated at the formula and apply the slippage. */
let slippageAmount = tradePositionRate * bot.VALUES_TO_USE.slippage.positionRate / 100
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
tradePositionRate = tradePositionRate - slippageAmount
} else {
tradePositionRate = tradePositionRate + slippageAmount
@@ -1993,20 +1938,7 @@
}
}
/* Checking the status of current positions */
let positions = assistant.getPositions();
if (positions.length > 0) {
let position = positions[positions.length - 1] // We are allways checking the the last position is not open.
if (position.status === 'open') {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> Not placing the trade at the exchange because the last position is still open. "); }
afterLoop();
return
}
}
/* Mechanism to avoid putting the same order over and over again at different executions of the simulation engine. */
if (interExecutionMemory.executionContext !== undefined) {
if (interExecutionMemory.executionContext.periods !== undefined) {
if (periods <= interExecutionMemory.executionContext.periods) {
@@ -2030,34 +1962,28 @@
}
}
let openPositionRate
let orderPrice
let amountA
let amountB
let positionDirection
let availableBalance = assistant.getAvailableBalance()
let orderSide
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
positionDirection = "sell"
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
orderSide = "sell"
openPositionRate = tradePositionRate - 100 // 100 is Provisional since we do have management of orders yet
orderPrice = tradePositionRate - 100 // This is going to be ingnored at the Exchange API for now since we only put market orders.
amountA = tradePositionSize * openPositionRate
amountA = tradePositionSize * orderPrice
amountB = tradePositionSize
if (amountB > availableBalance.quotedAsset) { // The assistant know what fees were paid.
amountB = availableBalance.quotedAsset
}
} else {
positionDirection = "buy"
orderSide = "buy"
openPositionRate = tradePositionRate + 100 // 100 is Provisional since we do have management of orders yet
orderPrice = tradePositionRate // This is going to be ingnored at the Exchange API for now since we only put market orders.
amountA = tradePositionSize
amountB = tradePositionSize / openPositionRate
amountB = tradePositionSize / orderPrice
if (amountA > availableBalance.baseAsset) { // The assistant know what fees were paid.
amountA = availableBalance.baseAsset
}
}
interExecutionMemory.executionContext = {
@@ -2065,46 +1991,47 @@
periods: periods,
}
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> Ready to put order."); }
assistant.putPosition(positionDirection, openPositionRate, amountA, amountB, onOrderPut)
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> Ready to create order."); }
exchangeAPI.createOrder(bot.market, orderSide, orderPrice, amountA, amountB, onOrderCreated)
function onOrderPut(err) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> Entering function."); }
function onOrderCreated(err, order) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> Entering function."); }
try {
switch (err.result) {
case global.DEFAULT_OK_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> DEFAULT_OK_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> DEFAULT_OK_RESPONSE "); }
interExecutionMemory.executionContext = {
status: "In a Position",
periods: periods,
amountA: amountA,
amountB: amountB
amountB: amountB,
orderId: order.id
}
takePositionAtSimulation()
return;
}
case global.DEFAULT_FAIL_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> DEFAULT_FAIL_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> Message = " + err.message); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> DEFAULT_FAIL_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> Message = " + err.message); }
strategy.openStage.openExecution.error = err.message
afterLoop()
return;
}
case global.DEFAULT_RETRY_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> DEFAULT_RETRY_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> Message = " + err.message); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> DEFAULT_RETRY_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> Message = " + err.message); }
strategy.openStage.openExecution.error = err.message
afterLoop()
return;
}
}
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> Unexpected Response -> Message = " + err.message); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> Unexpected Response -> Message = " + err.message); }
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
return
} catch (err) {
logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> err = " + err.stack);
logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> err = " + err.stack);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
return
}
@@ -2135,7 +2062,7 @@
let feePaid = 0
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
feePaid = tradePositionSize * tradePositionRate * bot.VALUES_TO_USE.feeStructure.taker / 100
@@ -2231,19 +2158,7 @@
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> putClosingOrder -> Entering function."); }
/* Checking the status of current positions */
let positions = assistant.getPositions();
if (positions.length > 0) {
let position = positions[positions.length - 1] // We are allways checking the the last position is not open.
if (position.status === 'open') {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> Exiting function because status of last position is Open."); }
afterLoop();
return
}
}
/* Mechanism to avoid putting the same order over and over again at different executions of the simulation engine. */
if (interExecutionMemory.executionContext !== undefined) {
if (interExecutionMemory.executionContext.periods !== undefined) {
if (periods <= interExecutionMemory.executionContext.periods) {
@@ -2254,27 +2169,26 @@
}
}
let closePositionRate
let orderPrice
let amountA
let amountB
let positionDirection
let availableBalance = assistant.getAvailableBalance()
let orderSide
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
positionDirection = "buy"
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
orderSide = "buy"
closePositionRate = ticker.last + 100; // This is provisional and totally arbitrary, until we have a formula on the designer that defines this stuff.
orderPrice = ticker.last + 100; // This is provisional and totally arbitrary, until we have a formula on the designer that defines this stuff.
amountA = availableBalance.baseAsset
amountB = availableBalance.baseAsset / closePositionRate
amountA = balanceQuotedAsset
amountB = balanceQuotedAsset / orderPrice
} else {
positionDirection = "sell"
orderSide = "sell"
closePositionRate = ticker.last - 100; // This is provisional and totally arbitrary, until we have a formula on the designer that defines this stuff.
orderPrice = ticker.last - 100; // This is provisional and totally arbitrary, until we have a formula on the designer that defines this stuff.
amountA = availableBalance.quotedAsset * closePositionRate
amountB = availableBalance.quotedAsset
amountA = balanceBaseAsset * orderPrice
amountB = balanceBaseAsset
}
@@ -2284,44 +2198,45 @@
}
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> About to close position at the exchange."); }
assistant.putPosition(positionDirection, closePositionRate, amountA, amountB, onOrderPut)
exchangeAPI.createOrder(bot.market, orderSide, orderPrice, amountA, amountB, onOrderCreated)
function onOrderPut(err) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderPut -> Entering function."); }
function onOrderCreated(err, order) {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderCreated -> Entering function."); }
try {
switch (err.result) {
case global.DEFAULT_OK_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderPut -> DEFAULT_OK_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderCreated -> DEFAULT_OK_RESPONSE "); }
interExecutionMemory.executionContext = {
status: "Position Closed",
periods: periods,
amountA: amountA,
amountB: amountB
amountB: amountB,
orderId: order.id
}
closePositionAtSimulation()
return;
}
case global.DEFAULT_FAIL_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderPut -> DEFAULT_FAIL_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putClosingOrder -> onOrderCreated -> DEFAULT_FAIL_RESPONSE "); }
/* We will assume that the problem is temporary, and expect that it will work at the next execution.*/
strategy.closeStage.closeExecution.error = err.message
afterLoop()
return;
}
case global.DEFAULT_RETRY_RESPONSE.result: {
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderPut -> DEFAULT_RETRY_RESPONSE "); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[INFO] runSimulation -> loop -> putOpeningOrder -> onOrderCreated -> DEFAULT_RETRY_RESPONSE "); }
strategy.closeStage.closeExecution.error = err.message
afterLoop()
return;
}
}
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putClosingOrder -> onOrderPut -> Unexpected Response -> Message = " + err.message); }
if (FULL_LOG === true) { logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putClosingOrder -> onOrderCreated -> Unexpected Response -> Message = " + err.message); }
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
return
} catch (err) {
logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putClosingOrder -> onOrderPut -> err = " + err.stack);
logger.write(MODULE_NAME, "[ERROR] runSimulation -> loop -> putClosingOrder -> onOrderCreated -> err = " + err.stack);
callBackFunction(global.DEFAULT_FAIL_RESPONSE);
return
}
@@ -2339,7 +2254,35 @@
}
}
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
let feePaid = 0
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
strategy.positionSize = balanceQuotedAsset / closeRate;
strategy.positionRate = closeRate;
feePaid = balanceQuotedAsset / closeRate * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceBaseAsset = balanceBaseAsset + balanceQuotedAsset / closeRate - feePaid;
balanceQuotedAsset = 0;
} else {
strategy.positionSize = balanceBaseAsset * closeRate;
strategy.positionRate = closeRate;
feePaid = balanceBaseAsset * closeRate * bot.VALUES_TO_USE.feeStructure.taker / 100
balanceQuotedAsset = balanceQuotedAsset + balanceBaseAsset * closeRate - feePaid;
balanceBaseAsset = 0;
}
if (processingDailyFiles) {
if (positionedAtYesterday) {
yesterday.balanceBaseAsset = balanceBaseAsset;
yesterday.balanceQuotedAsset = balanceQuotedAsset;
}
}
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
lastTradeProfitLoss = balanceBaseAsset - previousBalanceBaseAsset;
lastTradeROI = lastTradeProfitLoss * 100 / tradePositionSize;
if (isNaN(lastTradeROI)) { lastTradeROI = 0; }
@@ -2386,7 +2329,7 @@
}
}
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
ROI = (bot.VALUES_TO_USE.initialBalanceA + profit) / bot.VALUES_TO_USE.initialBalanceA - 1;
hitRatio = hits / roundtrips;
anualizedRateOfReturn = ROI / days * 365;
@@ -2652,7 +2595,7 @@
currentTrade.endRate = candle.close
/* Here we will calculate the ongoing ROI */
if (bot.VALUES_TO_USE.baseAsset === 'BTC') {
if (bot.VALUES_TO_USE.baseAsset === bot.market.baseAsset) {
currentTrade.lastTradeROI = (tradePositionRate - candle.close) / tradePositionRate * 100
} else {
currentTrade.lastTradeROI = (candle.close - tradePositionRate) / tradePositionRate * 100