Market Orders Simulated

This commit is contained in:
Luis Fernando Molina committed 2020-07-17 11:36:32 +02:00
1 parent faad10cb7a
commit 2c36279c94
14 files changed
+2031 -730

No files matched your search

@@ -5,6 +5,7 @@ exports.newTradingEngine = function newTradingEngine(bot, logger) {
*/
const MODULE_NAME = 'Trading Engine'
let thisObject = {
getNodeById: getNodeById,
cloneValues: cloneValues,
setCurrentCandle: setCurrentCandle,
updateEpisodeCountersAndStatistics: updateEpisodeCountersAndStatistics,
@@ -15,6 +16,7 @@ exports.newTradingEngine = function newTradingEngine(bot, logger) {
let tradingEngine
let sessionParameters
let nodesMap = new Map()
return thisObject
@@ -34,6 +36,11 @@ exports.newTradingEngine = function newTradingEngine(bot, logger) {
function finalize() {
tradingEngine = undefined
sessionParameters = undefined
nodesMap = undefined
}
function getNodeById(NodeId) {
return nodesMap.get(NodeId)
}
function setCurrentCandle(candle) {
@@ -90,6 +97,8 @@ exports.newTradingEngine = function newTradingEngine(bot, logger) {
function initializeNode(node) {
if (node === undefined) { return }
/* Add to Node Map */
nodesMap.set(node.id, node)
/* Here we initialize the node value */
if (node.config !== undefined) {
@@ -1,10 +1,11 @@
exports.newTradingPosition = function newTradingPosition(bot, logger) {
exports.newTradingPosition = function newTradingPosition(bot, logger, tradingEngineModule) {
/*
This module packages all functions related to Positions.
*/
const MODULE_NAME = 'Trading Position'
let thisObject = {
openPosition: openPosition,
closingPosition: closingPosition,
closePosition: closePosition,
applyStopLossFormula: applyStopLossFormula,
applyTakeProfitFormula: applyTakeProfitFormula,
@@ -53,16 +54,17 @@ exports.newTradingPosition = function newTradingPosition(bot, logger) {
tradingEngine.current.position.takeProfit.takeProfitPhase.value = 0
}
function closePosition(exitType) {
function closingPosition(exitType) {
tradingEngine.current.position.status.value = 'Closing'
tradingEngine.current.position.exitType.value = exitType
}
function closePosition() {
tradingEngine.current.position.status.value = 'Closed'
tradingEngine.current.position.end.value = tradingEngine.current.candle.end.value
tradingEngine.current.position.exitType.value = exitType
/*
Now that the position is closed, it is the right time to move this position from current to last at the Trading Engine data structure.
*/
const TRADING_ENGINE_MODULE = require('./TradingEngine.js')
let tradingEngineModule = TRADING_ENGINE_MODULE.newTradingEngine(bot, logger)
tradingEngineModule.cloneValues(tradingEngine.current.position, tradingEngine.last.position)
}
+150 -100
View File
@@ -45,85 +45,115 @@ exports.newTradingRecords = function newTradingRecords(bot, logger) {
let outputDatasetArray = outputDatasetsMap.get(product.config.codeName)
if (bot.processingDailyFiles === true && dataset.config.type === 'Daily Files') {
persistRecord()
persistRecords()
}
if (bot.processingDailyFiles === false && dataset.config.type === 'Market Files') {
persistRecord()
persistRecords()
}
function persistRecord() {
pruneOutputFile(product, outputDatasetArray)
let record = scanRecordDefinition(product)
function persistRecords() {
/* Clean the file from information of previous executions */
pruneOutputFile(product, outputDatasetArray)
/* Clean Open Records */
if (product.config.saveAsObjects === true) {
/* For saving objects we need to take care of a different set of rules. */
for (let j = 0; j < product.record.properties.length; j++) {
let recordProperty = product.record.properties[j]
if (recordProperty.config.codeName === product.config.propertyNameThatDefinesObject) {
let propertyValue = record[j]
/*
We check that the existing file does not contain at the end a record that
does not signal that the object is closed.
If it does, we replace it with the new one until at some point it will signal
does the object is closed.
/* Remove Open Records */
spliceOpenRecords(j, product, outputDatasetArray)
}
}
}
/*
The product root can be a node or a node property of type array.
*/
let productRoot = eval(product.config.nodePath)
if (product.config.nodePathType === 'array') {
/*
This means that the configured nodePath is not pointing to a node, but to a node property that is an array.
For that reason we will assume that each element of the array is a record to be outputed
*/
for (let index = 0; index < productRoot.length; index++) {
/*
The Product Root Node is the root of the node hiriarchy from where we are going to extract the record values.
*/
let productRootNode = productRoot[index]
let record = scanRecordDefinition(product, productRootNode, index)
persistIndividualRecord(record, product, outputDatasetArray)
}
} else {
/*
This means that the configured nodePath points to a single node, which is the one whose children constitutes
the record to be saved at the output file.
*/
/*
The Product Root Node is the root of the node hiriarchy from where we are going to extract the record values.
*/
let productRootNode = productRoot
let record = scanRecordDefinition(product, productRootNode)
persistIndividualRecord(record, product, outputDatasetArray)
}
}
}
function persistIndividualRecord(record, product, outputDatasetArray) {
if (product.config.saveAsObjects === true) {
/* For saving objects we need to take care of a different set of rules. */
for (let j = 0; j < product.record.properties.length; j++) {
let recordProperty = product.record.properties[j]
if (recordProperty.config.codeName === product.config.propertyNameThatDefinesObject) {
let propertyValue = record[j]
if (bot.processingDailyFiles) {
/*
When dealing with Daily Files, we need to avoid to write an open object at the last 'candle' of the day,
since the object will be duplicated on the next day. How do we know we are positioned at the last candle
of the day? Easy: the end of the candle must be 1 millisecod before the next day. That happens at any
time frame.
*/
let lastRecord = outputDatasetArray[outputDatasetArray.length - 1]
if (lastRecord !== undefined) {
let lastRecordValue = lastRecord[j]
if (lastRecordValue !== product.config.propertyValueThatClosesObject) {
outputDatasetArray.splice(outputDatasetArray.length - 1, 1)
}
}
if (bot.processingDailyFiles) {
let currentDay = new Date(tradingEngine.current.candle.end.value)
let nextDay = new Date(tradingEngine.current.candle.end.value + 1)
if (currentDay.getUTCDate() !== nextDay.getUTCDate()) {
/*
When dealing with Daily Files, we need to avoid to write an open object at the last 'candle' of the day,
since the object will be duplicated on the next day. How do we know we are positioned at the last candle
of the day? Easy: the end of the candle must be 1 millisecod before the next day. That happens at any
time frame.
We will save the object only if it is closed, becasuse we are at the last candle of the day.
*/
let currentDay = new Date(tradingEngine.current.candle.end.value)
let nextDay = new Date(tradingEngine.current.candle.end.value + 1)
if (currentDay.getUTCDate() !== nextDay.getUTCDate()) {
/*
We will save the object only if it is closed, becasuse we are at the last candle of the day.
*/
if (propertyValue === product.config.propertyValueThatClosesObject) {
outputDatasetArray.push(record)
}
} else {
/*
When we are not at the end of the day, we will save the object normally, like in market files.
*/
if (propertyValue !== product.config.propertyValueThatPreventsSavingObject) {
outputDatasetArray.push(record)
}
if (propertyValue === product.config.propertyValueThatClosesObject) {
outputDatasetArray.push(record)
}
}
else {
} else {
/*
For Market Files we will add a record everytime that proeprty value does not match this
When we are not at the end of the day, we will save the object normally, like in market files.
*/
if (propertyValue !== product.config.propertyValueThatPreventsSavingObject) {
outputDatasetArray.push(record)
}
}
break
}
else {
/*
For Market Files we will add a record everytime that proeprty value does not match this
*/
if (propertyValue !== product.config.propertyValueThatPreventsSavingObject) {
outputDatasetArray.push(record)
}
}
break
}
} else {
/* When we are not dealing with objects, we add every record to the existing file. */
outputDatasetArray.push(record)
}
} else {
/* When we are not dealing with objects, we add every record to the existing file. */
outputDatasetArray.push(record)
}
}
function scanRecordDefinition(product) {
/*
The Product Root Node is the root of the node hiriarchy branch that we need to look at
in order to fnd the node where we are going to extract the value.
*/
let productRootNode = eval(product.config.nodePath)
function scanRecordDefinition(product, productRootNode, index) {
let record = []
for (let j = 0; j < product.record.properties.length; j++) {
let recordProperty = product.record.properties[j]
@@ -201,64 +231,84 @@ exports.newTradingRecords = function newTradingRecords(bot, logger) {
}
return record
}
}
function safeNumericValue(value) {
/*
The purpose of this function is to check that value variable does not have a value that
will later break the JSON format of files where this is going to be stored at.
*/
if (value === Infinity) {
value = Number.MAX_SAFE_INTEGER
function safeNumericValue(value) {
/*
The purpose of this function is to check that value variable does not have a value that
will later break the JSON format of files where this is going to be stored at.
*/
if (value === Infinity) {
value = Number.MAX_SAFE_INTEGER
}
if (value === undefined) {
value = 0
}
if (value === null) {
value = 0
}
if (isNaN(value)) {
value = 0
}
return value
}
if (value === undefined) {
value = 0
}
if (value === null) {
value = 0
}
if (isNaN(value)) {
value = 0
}
return value
}
function safeStringValue(value) {
/*
The purpose of this function is to check that value variable does not have a value that
will later break the JSON format of files where this is going to be stored at.
*/
if (value === undefined) {
value = ''
function safeStringValue(value) {
/*
The purpose of this function is to check that value variable does not have a value that
will later break the JSON format of files where this is going to be stored at.
*/
if (value === undefined) {
value = ''
}
if (value === null) {
value = ''
}
return value
}
if (value === null) {
value = ''
function pruneOutputFile(product, outputFile) {
if (outputFile.isPrunned === true) { return }
/*
When a session is resumed, we will be potentially reading output files belonging to a previous session execution.
For that reason we need to prune all the records that are beyond the current candle. We do not delete everything
because we might be resuming a stopped session, which is fine.
*/
for (let i = 0; i < outputFile.length; i++) {
let record = outputFile[i]
for (let j = 0; j < product.record.properties.length; j++) {
let recordProperty = product.record.properties[j]
if (recordProperty.config.codeName === 'end') {
let end = record[j]
if (end >= tradingEngine.current.candle.end.value) {
outputFile.splice(i, 1)
pruneOutputFile(product, outputFile)
return
}
}
}
}
outputFile.isPrunned = true
}
return value
}
function pruneOutputFile(product, outputFile) {
if (outputFile.isPrunned === true) { return }
/*
When a session is resumed, we will be potentially reading output files belonging to a previous session execution.
For that reason we need to prune all the records that are beyond the current candle. We do not delete everything
because we might be resuming a stopped session, which is fine.
*/
for (let i = 0; i < outputFile.length; i++) {
let record = outputFile[i]
function spliceOpenRecords(j, product, outputDatasetArray) {
/*
Before adding records to the output file, we need to remove all open records,
because we will be adding the same records later with potentially
new or updated information.
*/
for (let j = 0; j < product.record.properties.length; j++) {
let recordProperty = product.record.properties[j]
if (recordProperty.config.codeName === 'end') {
let end = record[j]
if (end >= tradingEngine.current.candle.end.value) {
outputFile.splice(i, 1)
pruneOutputFile(product, outputFile)
for (let i = 0; i < outputDatasetArray.length; i++) {
let dataRecord = outputDatasetArray[i]
if (dataRecord !== undefined) {
let dataRecordValue = dataRecord[j]
if (dataRecordValue !== product.config.propertyValueThatClosesObject) {
outputDatasetArray.splice(i, 1)
spliceOpenRecords(j, product, outputDatasetArray)
return
}
}
}
}
outputFile.isPrunned = true
}
}
@@ -41,12 +41,6 @@ exports.newTradingSimulation = function newTradingSimulation(bot, logger, UTILIT
const MIN_TAKE_PROFIT_VALUE = 0.0000000001 // We can not let the buy order be zero to avoid division by 0 error or infinity numbers as a result.
const MAX_TAKE_PROFIT_VALUE = Number.MAX_SAFE_INTEGER
/* Variables to know when we need to open or close a position. */
let triggeringOn
let triggeringOff
let takingPosition
let closingPosition
/* These are the Modules we will need to run the Simulation */
const EXCHANGE_API = require('../ExchangeAPI');
exchangeAPI = EXCHANGE_API.newExchangeAPI(logger, bot);
@@ -56,16 +50,12 @@ exports.newTradingSimulation = function newTradingSimulation(bot, logger, UTILIT
let tradingEngineModule = TRADING_ENGINE_MODULE.newTradingEngine(bot, logger)
tradingEngineModule.initialize()
const TRADING_ENGINE_EXECUTION = require('./TradingExecution.js')
let tradingExecutionModule = TRADING_ENGINE_EXECUTION.newTradingExecution(bot, logger)
tradingExecutionModule.initialize()
const TRADING_RECORDS_MODULE = require('./TradingRecords.js')
let tradingRecordsModule = TRADING_RECORDS_MODULE.newTradingRecords(bot, logger)
tradingRecordsModule.initialize(outputDatasetsMap)
const TRADING_SYSTEM_MODULE = require('./TradingSystem.js')
let tradingSystemModule = TRADING_SYSTEM_MODULE.newTradingSystem(bot, logger)
let tradingSystemModule = TRADING_SYSTEM_MODULE.newTradingSystem(bot, logger, tradingEngineModule)
tradingSystemModule.initialize()
/* Setting up the candles array: The whole simulation is based on the array of candles at the time-frame defined at the session parameters. */
@@ -153,68 +143,21 @@ exports.newTradingSimulation = function newTradingSimulation(bot, logger, UTILIT
tradingSystemModule.mantainPositions()
tradingEngineModule.updateEpisodeCountersAndStatistics()
/*
The next step is about evaluationg Conditions and Formulas of the Trading System.
*/
tradingSystemModule.evalConditions()
tradingSystemModule.evalFormulas()
/*
Next we check if we will be triggering on, off or taking position.
*/
triggeringOn = tradingSystemModule.checkTriggerOn()
triggeringOff = tradingSystemModule.checkTriggerOff()
takingPosition = tradingSystemModule.checkTakePosition()
/* Time to check the execution of orders */
tradingSystemModule.checkExecution()
/* Stop Loss Management */
if (takingPosition !== true) {
tradingSystemModule.checkStopPhasesEvents()
tradingSystemModule.calculateStopLoss()
}
/* Take Profit Management */
if (takingPosition !== true) {
tradingSystemModule.checkTakeProfitPhaseEvents()
tradingSystemModule.calculateTakeProfit()
}
tradingEngineModule.updateDistanceToEventsCounters()
/* Checking if Stop or Take Profit were hit */
if (takingPosition !== true) {
closingPosition = tradingSystemModule.checkStopLossOrTakeProfitWasHit()
}
/* Run the Trigger Stage */
tradingSystemModule.triggerStage()
/* Taking a Position */
if (takingPosition === true) {
tradingSystemModule.getReadyToTakePosition()
/*
Whem we calculated all the formulas at the begining of the loop, we didn't know
we were going to take position in this same loop cycle. Some might formulas depends on
calculations that are triggered only when we are taking position. For that reason
we will calculate all formulas again, and after that the Stop Loss and Take Profit.
*/
tradingSystemModule.evalFormulas()
tradingSystemModule.calculateTakeProfit()
tradingSystemModule.calculateStopLoss()
/* Run the Open Stage */
tradingSystemModule.openStage()
tradingExecutionModule.takePosition()
tradingSystemModule.takePosition()
takingPosition = false
}
/* Run the Manage Stage */
tradingSystemModule.manageStage()
/* Closing a Position */
if (closingPosition === true) {
tradingSystemModule.getReadyToClosePosition()
tradingExecutionModule.closePosition()
tradingSystemModule.closePosition()
closingPosition = false
}
/* Run the Close Stage */
tradingSystemModule.closeStage()
/* After a position was closed, we need to close the strategy. */
tradingSystemModule.exitStrategyAfterPosition()
/* Add new records to the process output */
tradingRecordsModule.appendRecords()
controlLoop()
@@ -246,10 +189,13 @@ exports.newTradingSimulation = function newTradingSimulation(bot, logger, UTILIT
function afterLoop() {
tradingEngineModule.finalize()
tradingExecutionModule.finalize()
tradingSystemModule.finalize()
tradingRecordsModule.finalize()
tradingEngineModule = undefined
tradingSystemModule = undefined
tradingRecordsModule = undefined
callback()
}
@@ -410,8 +356,7 @@ exports.newTradingSimulation = function newTradingSimulation(bot, logger, UTILIT
function checkMinimunAndMaximunBalance() {
/* Checks for Minimun and Maximun Balance. We do the check while not inside any strategy only. */
if (
tradingEngine.current.strategy.stageType.value === 'No Stage' &&
tradingEngine.current.strategy.index.value === -1
tradingEngine.current.strategy.index.value === tradingEngine.current.strategy.index.config.initialValue
) {
/*
First thing to do is to check if we are below the minimum balance, or above the maximun balance.
@@ -1,4 +1,4 @@
exports.newTradingStrategy = function newTradingStrategy(bot, logger) {
exports.newTradingStrategy = function newTradingStrategy(bot, logger, tradingEngineModule) {
/*
This module packages all functions related to Strategies.
*/
@@ -7,7 +7,7 @@ exports.newTradingStrategy = function newTradingStrategy(bot, logger) {
openStrategy: openStrategy,
closeStrategy: closeStrategy,
updateEnds: updateEnds,
updateStageType: updateStageType,
updateStageStatus: updateStageStatus,
updateStatus: updateStatus,
updateCounters: updateCounters,
resetStrategy: resetStrategy,
@@ -27,14 +27,13 @@ exports.newTradingStrategy = function newTradingStrategy(bot, logger) {
tradingEngine = undefined
}
function openStrategy(stageType, index, situationName, strategyName) {
function openStrategy(index, situationName, strategyName) {
tradingEngine.current.strategy.status.value = 'Open'
tradingEngine.current.strategy.begin.value = tradingEngine.current.candle.begin.value
tradingEngine.current.strategy.end.value = tradingEngine.current.candle.end.value
tradingEngine.current.strategy.beginRate.value = tradingEngine.current.candle.min.value
tradingEngine.current.strategy.endRate.value = tradingEngine.current.candle.min.value
tradingEngine.current.strategy.stageType.value = stageType
tradingEngine.current.strategy.index.value = index
tradingEngine.current.strategy.situationName.value = situationName
tradingEngine.current.strategy.strategyName.value = strategyName
@@ -48,9 +47,6 @@ exports.newTradingStrategy = function newTradingStrategy(bot, logger) {
/*
Now that the strategy is closed, it is the right time to move this strategy from current to last at the Trading Engine data structure.
*/
const TRADING_ENGINE_MODULE = require('./TradingEngine.js')
let tradingEngineModule = TRADING_ENGINE_MODULE.newTradingEngine(bot, logger)
tradingEngineModule.cloneValues(tradingEngine.current.strategy, tradingEngine.last.strategy)
}
@@ -65,8 +61,25 @@ exports.newTradingStrategy = function newTradingStrategy(bot, logger) {
}
}
function updateStageType(stageType) {
tradingEngine.current.strategy.stageType.value = stageType
function updateStageStatus(stage, status) {
switch (stage) {
case 'Trigger Stage': {
tradingEngine.current.strategy.triggerStageStatus.value = status
break
}
case 'Open Stage': {
tradingEngine.current.strategy.openStageStatus.value = status
break
}
case 'Manage Stage': {
tradingEngine.current.strategy.manageStageStatus.value = status
break
}
case 'Close Stage': {
tradingEngine.current.strategy.closeStageStatus.value = status
break
}
}
}
function updateStatus() {
File diff suppressed because it is too large. Load diff
+7
View File
@@ -33,6 +33,13 @@ global.ONE_MIN_IN_MILISECONDS = 60 * 1000
global.LOGGER_MAP = new Map()
global.SESSION_MAP = new Map()
global.UNIQUE_ID = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)
return v.toString(16)
})
}
process.on('uncaughtException', function (err) {
console.log('[ERROR] Task Server -> server -> uncaughtException -> err.message = ' + err.message)
console.log('[ERROR] Task Server -> server -> uncaughtException -> err.stack = ' + err.stack)