Operations Module moved to old repos

This commit is contained in:
Luis Fernando Molina committed 2020-11-20 19:46:12 +01:00
1 parent 765659d4a2
commit 9e00cd2468
88 files changed
-84

No files matched your search

@@ -0,0 +1,150 @@
import { CloneInputType } from '../types/input'
import { CloneType } from '../types'
import { Clone } from '../../models'
import { BotTypesEnum } from '../../enums/BotTypes'
import teamQuery from '../../graphQLCalls/teamQuery'
import authorizeKey from '../../graphQLCalls/authorizeKey'
import addBotMutation from '../../graphQLCalls/addBotMutation'
import cloneDetails from '../cloneDetails'
import {
AuthenticationError,
WrongArgumentsError,
OperationsError,
AuthorizationError
} from '../../errors'
import logger from '../../config/logger'
import createKubernetesClone from '../../kubernetes/createClone'
import { isDefined } from '../../config/utils'
import { CloneModeEnum, LIVE, COMPETITION, BACKTEST } from '../../enums/CloneMode'
import { Trading } from '../../enums/BotTypes'
const args = {
clone: { type: CloneInputType }
}
const resolve = async (parent, { clone }, context) => {
logger.debug('addClone -> Entering Fuction.')
if (!context.userId) {
throw new AuthenticationError()
} else {
clone.authorization = context.authorization
}
if (!Object.values(CloneModeEnum).includes(clone.mode)) {
throw new WrongArgumentsError('The mode selected is not valid.')
}
if (!Object.values(BotTypesEnum).includes(clone.botType)) {
throw new WrongArgumentsError('The bot type selected is not valid.')
}
if ((clone.mode === LIVE || clone.mode === COMPETITION) && !isDefined(clone.keyId)) {
throw new WrongArgumentsError('The key was not provided to run the clone.')
}
let allUserBotsResponse = await teamQuery(context.authorization, clone.botId)
let bot = allUserBotsResponse.data.data.teams_FbByOwner.edges[0].node
clone = cloneDetails(bot, clone)
clone.createDatetime = new Date().valueOf() / 1000 | 0
clone.active = true
// TODO Temporary Limitations on bot creation
if (clone.accessCode !== undefined && clone.accessCode.length > 0) {
if (clone.accessCode === process.env.ACCESS_CODE) {
if (clone.baseAsset === 'assetB') {
clone.balanceAssetA = 0
clone.balanceAssetB = clone.balanceBaseAsset
} else if (clone.baseAsset === 'assetA') {
clone.balanceAssetA = clone.balanceBaseAsset
clone.balanceAssetB = 0
} else {
throw new Error('Invalid base asset.')
}
} else {
throw new Error('Invalid access code.')
}
} else {
if (clone.baseAsset === 'assetB') {
clone.balanceAssetA = 0
clone.balanceAssetB = Number(process.env.DEFAULT_BALANCE_ASSET_B)
} else if (clone.baseAsset === 'assetA') {
clone.balanceAssetA = Number(process.env.DEFAULT_BALANCE_ASSET_A)
clone.balanceAssetB = 0
} else {
throw new Error('Invalid base asset.')
}
}
if (!(clone.teamSlug === "AAMasters" || clone.teamSlug === "AAVikings")) {
let clones = await Clone.find({
authId: context.userId,
active: true
})
if (clones !== undefined && clones.length >= 5) {
throw new Error('Currently maximum number of clones per user is 5. You can delete an existing clone and try again.')
}
}
// END temporary limitations
try {
let newClone = new Clone(clone)
newClone.authId = context.userId
clone.id = newClone._id
logger.debug('addClone -> Creating the clone on the Database.')
let savedClone = await newClone.save()
if (clone.mode === LIVE || clone.mode === COMPETITION) {
logger.debug('addClone -> Authorizing clone to use the key.')
let keyResponse = await authorizeKey(context.authorization, clone.keyId, clone.id, false)
if (isDefined(keyResponse.data.data.keyVault_AuthorizeClone)) {
clone.accessTokenKey = keyResponse.data.data.keyVault_AuthorizeClone
} else {
logger.error('addClone -> Authorizing clone to use the key fail.')
throw new AuthorizationError()
}
}
await createKubernetesClone(clone)
if (clone.botType === Trading) {
let productCodeName
if (clone.mode === LIVE) {
productCodeName = 'Live Trading History'
}
if (clone.mode === COMPETITION) {
productCodeName = 'Competition Trading History'
}
if (clone.mode === BACKTEST) {
productCodeName = 'Backtest Trading History'
}
let newEcosystemBot = {
devTeam: clone.teamSlug,
codeName: clone.botSlug,
cloneId: clone.id,
productCodeName
}
await addBotMutation(context.authorization, newEcosystemBot)
}
logger.debug('addClone -> Clone created sucessfully.')
return savedClone
} catch (err) {
logger.error('addClone -> Error: %s', err.stack)
throw new OperationsError('There has been an error creating the clone.')
}
}
const AddCloneMutation = {
addClone: {
type: CloneType,
args,
resolve
}
}
export default AddCloneMutation
@@ -0,0 +1,77 @@
import { GraphQLNonNull, GraphQLID, GraphQLString } from 'graphql'
import { AuthenticationError, OperationsError } from '../../errors'
import { Clone } from '../../models'
import logger from '../../config/logger'
import removeKuberneteClone from '../../kubernetes/removeClone'
import teamQuery from '../../graphQLCalls/teamQuery'
import { isDefined } from '../../config/utils'
import cloneDetails from '../cloneDetails'
import authorizeKey from '../../graphQLCalls/authorizeKey'
import { LIVE, COMPETITION, BACKTEST } from '../../enums/CloneMode'
import { Trading } from '../../enums/BotTypes'
import removeBotMutation from '../../graphQLCalls/removeBotMutation'
const args = { id: { type: new GraphQLNonNull(GraphQLID) } }
const resolve = async (parent, { id }, context) => {
logger.debug('removeClone -> Entering Fuction.')
if (!context.userId) {
throw new AuthenticationError()
}
try {
let clone = await Clone.findOne({
_id: id,
authId: context.userId,
active: true
})
if (!isDefined(clone)) {
throw new OperationsError('You are not authorized to remove this clone.')
}
let allUserBotsResponse = await teamQuery(context.authorization, clone.botId)
let bot = allUserBotsResponse.data.data.teams_FbByOwner.edges[0].node
clone = cloneDetails(bot, clone)
if ((clone.mode === LIVE || clone.mode === COMPETITION) && isDefined(clone.keyId)) {
logger.debug('removeClone -> Release the clone key.')
await authorizeKey(context.authorization, clone.keyId, clone.id, true)
}
logger.debug('removeClone -> Removing Clone from Kubernates.')
await removeKuberneteClone(clone.id)
const query = {
_id: id,
authId: context.userId
}
const options = { new: true }
const update = { active: false }
return new Promise((res, rej) => {
Clone.findOneAndUpdate(query, update, options, (err, doc) => {
if (err) {
logger.error('removeClone -> Error removing clone from the DB. %s', err.stack)
rej(err)
return
}
logger.debug('removeClone -> Clone Removed from the DB.')
res('Clone Removed.')
})
})
} catch (error) {
logger.error('Error removing the clone. %s', error.stack)
throw new OperationsError(error.message)
}
}
const RemoveCloneMutation = {
removeClone: {
type: GraphQLString,
args,
resolve
}
}
export default RemoveCloneMutation
@@ -0,0 +1,140 @@
import { GraphQLString } from 'graphql'
import { SimulationInputType } from '../types/input'
import removeKuberneteClone from '../../kubernetes/removeClone'
import { Clone } from '../../models'
import { Indicator } from '../../enums/BotTypes'
import { DateTime } from 'luxon'
import teamQuery from '../../graphQLCalls/teamQuery'
import cloneDetails from '../cloneDetails'
import {
AuthenticationError,
OperationsError
} from '../../errors'
import logger from '../../config/logger'
import createKubernetesClone from '../../kubernetes/createClone'
const args = {
simulation: { type: SimulationInputType }
}
const resolve = async (parent, { simulation }, context) => {
logger.debug('runSimulation -> Entering Fuction.')
if (!context.userId) {
throw new AuthenticationError()
}
try {
// Find all running clones
let clones = await Clone.find({
authId: context.userId,
active: true
}).sort({ createDatetime: -1 })
// Find all user bots
let allUserBotsResponse = await teamQuery(context.authorization, null)
let allUserBots = allUserBotsResponse.data.data.teams_FbByOwner.edges
let simulatorBot
// Identify clones to stop, if any
for (var j = 0; j < allUserBots.length; j++) {
let bot = allUserBots[j].node
if (bot.kind === Indicator && bot.slug.substring(0, 10) === "simulator-") {
simulatorBot = bot // TODO One simulator per user
for (var i = 0; i < clones.length; i++) {
if (clones[i].botId === bot.id) {
if ((simulation.timePeriodDailyArray !== undefined && clones[i].processName === "Multi-Period-Daily") ||
(simulation.timePeriodMarketArray !== undefined && clones[i].processName === "Multi-Period-Market") ||
(simulation.timePeriodDailyArray === undefined && simulation.timePeriodMarketArray === undefined)) {
logger.debug('runSimulation -> Stop running clones.')
await removeKuberneteClone(clones[i]._id)
logger.debug('runSimulation -> Clone Removed from Kubernetes: %s.', clones[i]._id)
let clone = await Clone.findOneAndUpdate({ _id: clones[i]._id, authId: context.userId }, { active: false }, { new: true })
if (!clone) throw new Error('Clone Not Found.')
logger.debug('runSimulation -> Clone Removed from the DB.')
}
}
}
}
}
if (simulation.beginDatetime === undefined) {
simulation.beginDatetime = DateTime.utc().minus({ days: 7 }).startOf('day')
}
if (simulation.resumeExecution === undefined) {
simulation.resumeExecution = false
}
if (simulatorBot !== undefined) {
if (simulation.timePeriodDailyArray !== undefined && simulation.timePeriodDailyArray.length > 0) {
simulation.timePeriod = simulation.timePeriodDailyArray
await createSimulatorClone(simulation, "Multi-Period-Daily", context.userId, simulatorBot, context.authorization)
}
if (simulation.timePeriodMarketArray !== undefined && simulation.timePeriodMarketArray.length > 0) {
simulation.timePeriod = simulation.timePeriodMarketArray
await createSimulatorClone(simulation, "Multi-Period-Market", context.userId, simulatorBot, context.authorization)
}
if (simulation.timePeriodDailyArray === undefined && simulation.timePeriodMarketArray === undefined) {
simulation.timePeriod = ["15-min", "10-min", "05-min"]
await createSimulatorClone(simulation, "Multi-Period-Daily", context.userId, simulatorBot, context.authorization)
simulation.timePeriod = ["24-hs", "12-hs", "08-hs", "06-hs", "04-hs", "03-hs", "02-hs", "01-hs"]
await createSimulatorClone(simulation, "Multi-Period-Market", context.userId, simulatorBot, context.authorization)
}
return "Simulation Clones Recreated."
} else {
return "The user doesn't have any simulator bot."
}
} catch (err) {
logger.error('runSimulation -> Error: %s', err.stack)
throw new OperationsError('There has been an error creating the clones.')
}
}
async function createSimulatorClone(simulation, processName, userId, simulatorBot, authorization) {
let clone = {
teamId: simulatorBot.team.id,
botId: simulatorBot.id,
mode: "noTime",
kind: "Indicator",
botSlug: simulatorBot.slug,
resumeExecution: simulation.resumeExecution,
exchangeName: "Poloniex", // TODO pending enable multiple exchange
beginDatetime: simulation.beginDatetime,
processName: processName,
createDatetime: new Date().valueOf() / 1000 | 0,
active: true,
authId: userId,
timePeriod: simulation.timePeriod.toString(),
authorization: authorization
}
let newClone = new Clone(clone)
clone.id = newClone._id
logger.debug('runSimulation -> Creating %s clone on the Database.', processName)
await newClone.save()
clone = cloneDetails(simulatorBot, clone)
await createKubernetesClone(clone)
logger.debug('runSimulation -> %s clone created.', processName)
}
const RunSimulationMutation = {
runSimulation: {
type: GraphQLString,
args,
resolve
}
}
export default RunSimulationMutation
@@ -0,0 +1,91 @@
import {
GraphQLNonNull,
GraphQLID,
GraphQLString,
GraphQLInt,
GraphQLFloat
} from 'graphql'
import { OperationsError, AuthorizationError, AuthenticationError } from '../../errors'
import { Clone } from '../../models'
import logger from '../../config/logger'
import { isDefined } from '../../config/utils'
const args = {
id: { type: new GraphQLNonNull(GraphQLID) },
summaryDate: { type: GraphQLInt },
buyAverage: { type: GraphQLFloat },
sellAverage: { type: GraphQLFloat },
marketRate: { type: GraphQLFloat },
combinedProfitsA: { type: GraphQLFloat },
combinedProfitsB: { type: GraphQLFloat },
assetA: { type: GraphQLString },
assetB: { type: GraphQLString }
}
const resolve = async (parent,
{ id, summaryDate, buyAverage, sellAverage, marketRate, combinedProfitsA,
combinedProfitsB, assetA, assetB
}, context) => {
logger.debug('UpdateExecutionSummary -> Entering Function.')
if (!context.userId) {
throw new AuthenticationError()
}
if (!(context.userId === process.env.AACLOUD_ID)) {
logger.debug('User %s is not authorized to manage team %s.', authId, team.slug)
throw new AuthorizationError()
}
try {
let clone = await Clone.findOne({
_id: id,
active: true
})
if (!isDefined(clone)) {
return 'Clone not found.'
}
const query = { _id: id }
const options = { new: true }
const update = {
summaryDate: summaryDate,
buyAverage: buyAverage,
sellAverage: sellAverage,
marketRate: marketRate,
combinedProfitsA: combinedProfitsA,
combinedProfitsB: combinedProfitsB,
assetA: assetA,
assetB: assetB
}
logger.debug('UpdateExecutionSummary -> Updating clone on database.')
return new Promise((res, rej) => {
Clone.update(query, update, options, (err, clone) => {
if (err) {
logger.error('Error updating execution summary on the database. %s', err.stack)
rej(err)
return
}
logger.debug('Execution summary updated.')
res('Execution summary updated.')
})
})
} catch (error) {
logger.error('Error updating the execution summary. %s', error.stack)
throw new OperationsError(error.message)
}
}
const UpdateExecutionSummary = {
updateExecutionSummary: {
type: GraphQLString,
args,
resolve
}
}
export default UpdateExecutionSummary
@@ -0,0 +1,17 @@
import { GraphQLObjectType } from 'graphql'
import AddCloneMutation from './AddCloneMutation'
import RemoveCloneMutation from './RemoveCloneMutation'
import UpdateExecutionSummary from './UpdateExecutionSummary'
import RunSimulation from './RunSimulation'
const Mutation = new GraphQLObjectType({
name: 'Mutation',
fields: Object.assign(
AddCloneMutation,
RemoveCloneMutation,
UpdateExecutionSummary,
RunSimulation
)
})
export default Mutation