Integration with saweb-api

This commit is contained in:
Matias committed 2019-05-29 11:31:44 -03:00
1 parent 2601595782
commit c8f845c6e3
6 files changed
+144 -637

No files matched your search

+1 -55
View File
@@ -91,61 +91,7 @@ function newDashboard () {
function loadImages (callBack) {
try {
const accessToken = ''
/*
Soon, we will need to get images from the Financial Beings Module. I live this core here as a sample for that:
const apolloClient = new Apollo.lib.ApolloClient({
networkInterface: Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl,
transportBatching: true,
}),
connectToDevTools: true,
})
const QUERY = Apollo.gql`
query($authId: String){
users_UserByAuthId (authId: $authId){
id
referrerId
alias
firstName
middleName
lastName
bio
email
emailVerified
isDeveloper
isDataAnalyst
isTrader
avatarHandle
avatarChangeDate
role {
id
}
}
}
`
const getUser = () => {
return new Promise((resolve, reject) => {
apolloClient.query({
query: QUERY,
variables: {
authId: authId
}
})
.then(response => {
window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId));
resolve({ user: response.data.users_UserByAuthId })
})
.catch(error => {
console.log("apolloClient error getting user query", error)
reject(error)
});
});
}
*/
// Soon, we will need to get images from the Financial Beings Module.
const networkInterfaceTeams = Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl
-131
View File
@@ -1,131 +0,0 @@
function newExchangeAPI () {
const INFO_LOG = true
const LOG_FILE_CONTENT = true
const MODULE_NAME = 'CloudVM -> Exchange API'
const SERVER_URL = window.canvasApp.urlPrefix + 'ExchangeAPI/'
let thisObject = {
initialize: initialize,
getTicker: getTicker,
getOpenPositions: getOpenPositions,
getExecutedTrades: getExecutedTrades,
putPosition: putPosition,
movePosition: movePosition,
getPublicTradeHistory: getPublicTradeHistory
}
return thisObject
function initialize (callBackFunction) {
/* When this initialized is called from the Browser, there is no need to send it to the server since the server will
anyways initialize this library at each method call. */
callBackFunction(window.DEFAULT_OK_RESPONSE)
}
function getTicker (pMarket, callBackFunction) {
let authToken = window.localStorage.getItem('access_token')
let path = SERVER_URL
+ "getTicker" + "/"
+ authToken
callServer(undefined, path + '/NO-LOG', onServerResponse)
function onServerResponse (pServerResponse) {
let response = JSON.parse(pServerResponse)
if (response.result === window.DEFAULT_FAIL_RESPONSE.result) {
callBackFunction(window.DEFAULT_FAIL_RESPONSE)
} else {
callBackFunction(window.DEFAULT_OK_RESPONSE, response)
}
}
}
function getOpenPositions (pMarket, callBackFunction) {
let authToken = window.localStorage.getItem('access_token');
let path = SERVER_URL
+ "getOpenPositions" + "/"
+ authToken
callServer(undefined, path + '/NO-LOG', onServerResponse)
function onServerResponse(pServerResponse) {
let response = JSON.parse(pServerResponse);
if (response.result === window.DEFAULT_FAIL_RESPONSE.result)
callBackFunction(window.DEFAULT_FAIL_RESPONSE);
else
callBackFunction(window.DEFAULT_OK_RESPONSE, response);
}
}
function getExecutedTrades(pPositionId, callBackFunction) {
let authToken = window.localStorage.getItem('access_token');
let path = SERVER_URL
+ "getExecutedTrades" + "/"
+ authToken + "/"
+ pPositionId
;
callServer(undefined, path + "/NO-LOG", onServerResponse);
function onServerResponse(pServerResponse) {
let response = JSON.parse(pServerResponse);
if (response.result === window.DEFAULT_FAIL_RESPONSE.result)
callBackFunction(window.DEFAULT_FAIL_RESPONSE);
else
callBackFunction(window.DEFAULT_OK_RESPONSE, response);
}
}
function putPosition(pMarket, pType, pRate, pAmountA, pAmountB, callBackFunction) {
let authToken = window.localStorage.getItem('access_token');
let path = SERVER_URL
+ "putPosition" + "/"
+ authToken + "/"
+ pType + "/"
+ pRate + "/"
+ pAmountA + "/"
+ pAmountB
;
callServer(undefined, path + '/NO-LOG', onServerResponse)
function onServerResponse (pServerResponse) {
let response = JSON.parse(pServerResponse)
if (response.result === window.DEFAULT_FAIL_RESPONSE.result) {
callBackFunction(window.DEFAULT_FAIL_RESPONSE)
} else {
callBackFunction(window.DEFAULT_OK_RESPONSE, response)
}
}
}
function getPublicTradeHistory (pMarket, startTime, endTime, callBackFunction) {
let authToken = window.localStorage.getItem('access_token')
let path = SERVER_URL
+ CURRENT_BOT_CODE_NAME + '/'
+ 'getPublicTradeHistory' + '/'
+ authToken + '/'
+ startTime + '/'
+ endTime
callServer(undefined, path + '/NO-LOG', onServerResponse)
function onServerResponse(pServerResponse) {
let response = JSON.parse(pServerResponse);
if (response.result === window.DEFAULT_FAIL_RESPONSE.result)
callBackFunction(window.DEFAULT_FAIL_RESPONSE);
else
callBackFunction(window.DEFAULT_OK_RESPONSE, response);
}
}
}
+2 -2
View File
@@ -61,8 +61,8 @@ function newCodeEditor () {
}
thisObject.iconNOT_OK.src = window.canvasApp.urlPrefix + thisObject.imagePathNOT_OK
}
thisObject.iconOK.src = window.canvasApp.urlPrefix + thisObject.imagePathOK
thisObject.icon = thisObject.iconOK // The default value is ON.
// thisObject.iconOK.src = window.canvasApp.urlPrefix + thisObject.imagePathOK
// thisObject.icon = thisObject.iconOK // The default value is ON.
}
function deactivate () {
+6 -10
View File
@@ -275,18 +275,14 @@ function newStrategizerGateway () {
/* Getting the FB that own the Strategies */
let teamtradingSystemSimulationFB = ''
let teams = window.localStorage.getItem('userTeams')
if (teams === null || teams === '' || teams === []) {
if (ERROR_LOG === true) { logger.write('[ERROR] loadFromStrategyzer -> no user teams found at local storage. Can not get Strategies without them. ') }
return
}
teams = JSON.parse(teams)
let ecosystem = JSON.parse(window.localStorage.getItem('ecosystem'))
let teams = ecosystem.devTeams
for (let i = 0; i < teams.length; i++) {
let team = teams[i]
for (let j = 0; j < team.fb.length; j++) {
let fb = team.fb[j]
if (fb.slug.indexOf('simulator') >= 0) {
teamtradingSystemSimulationFB = fb.slug
for (let j = 0; j < team.bots.length; j++) {
let bot = team.bots[j]
if (bot.codeName.indexOf('simulator') >= 0) {
teamtradingSystemSimulationFB = bot.codeName
}
}
}
-84
View File
@@ -1,84 +0,0 @@

function newEndUser () {
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
let container = newContainer()
container.initialize()
thisObject.container = container
thisObject.container.frame.width = 200
thisObject.container.frame.height = COCKPIT_SPACE_HEIGHT
container.frame.position.x = viewPort.visibleArea.topRight.x - thisObject.container.frame.width * 5
container.frame.position.y = viewPort.visibleArea.bottomLeft.y + BREAKPOINT_HEIGHT
container.isDraggeable = false
return thisObject
function initialize () {
let storedUser = window.localStorage.getItem('loggedInUser')
if (storedUser === null || storedUser === '') {
// User is currently not logged in.
window.USER_LOGGED_IN = ''
return
}
let loggedInUser = JSON.parse(storedUser)
window.USER_LOGGED_IN = loggedInUser.alias
/* Here we will rearrange the storage permissions array into a map, so that it can be easily consumed when needed. */
let permissionsMap = new Map()
for (i = 0; i < window.USER_PROFILE.storagePermissions.length; i++) {
let permission = window.USER_PROFILE.storagePermissions[i]
permissionsMap.set(permission[0], permission[1])
}
window.USER_PROFILE.storagePermissions = permissionsMap
}
function getContainer (point) {
let container
/* First we check if this point is inside this object UI. */
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return this.container
} else {
/* This point does not belong to this space. */
return undefined
}
}
function draw () {
return // nothing to show
thisObject.container.frame.draw(false, false)
let fontSize = 12
let label = window.USER_LOGGED_IN
if (label === undefined) { label = '' };
let point = {
x: thisObject.container.frame.width * 1 / 3,
y: (thisObject.container.frame.height / 2) + 4
}
point = thisObject.container.frame.frameThisPoint(point)
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'
browserCanvasContext.fillText(label, point.x, point.y)
}
}
+135 -355
View File
@@ -1,8 +1,6 @@
function newLogin () {
function newLogin() {
const MODULE_NAME = 'Login'
const INFO_LOG = false
const INTENSIVE_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
@@ -27,381 +25,163 @@ function newLogin () {
container.isDraggeable = false
container.isClickeable = true
let currentLabel
let userAuthorization
return thisObject
async function initialize (pSharedStatus) {
async function initialize(sharedStatus) {
try {
const accessToken = window.localStorage.getItem('access_token')
let user = window.localStorage.getItem('user')
sharedStatus = pSharedStatus
if (user === null) {
// if there is no user that means that we are logged off, which means it is time to clean the local storage of things from the last log in.
window.localStorage.removeItem('loggedInUser')
return
if (accessToken) {
await getEvents(accessToken, sharedStatus)
await getClones(accessToken)
}
user = JSON.parse(user)
const authId = user.authId
const apolloClient = new Apollo.lib.ApolloClient({
networkInterface: Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl,
transportBatching: true
}),
connectToDevTools: true
})
const USERS_QUERY = Apollo.gql`
query($authId: String){
users_UserByAuthId (authId: $authId){
id
referrerId
alias
firstName
middleName
lastName
bio
email
emailVerified
isDeveloper
isDataAnalyst
isTrader
avatarHandle
avatarChangeDate
role {
id
}
}
}
`
const getUser = () => {
return new Promise((resolve, reject) => {
apolloClient.query({
query: USERS_QUERY,
variables: {
authId: authId
}
})
.then(response => {
window.localStorage.setItem('loggedInUser', JSON.stringify(response.data.users_UserByAuthId))
resolve({ user: response.data.users_UserByAuthId})
})
.catch(error => {
console.log('apolloClient error getting user query', error.graphQLErrors, error.stack)
reject(error)
})
})
}
/* Getting all Teams */
const networkInterfaceTeams = Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl
})
networkInterfaceTeams.use([{
applyMiddleware (req, next) {
req.options.headers = {
authorization: `Bearer ${accessToken}`
}
next()
}
}])
const apolloClientTeams = new Apollo.lib.ApolloClient({
networkInterface: networkInterfaceTeams,
connectToDevTools: true
})
const TEAM_BY_OWNER_QUERY = Apollo.gql`
query teamsByOwnerQuery {
teams_TeamsByOwner {
id
name
slug
profile {
avatar
banner
description
motto
updatedAt
}
members {
member {
alias
}
}
fb {
id
name
slug
avatar
kind
status {
status
reason
createdAt
}
}
}
}
`
const getTeamByOwner = () => {
return new Promise((resolve, reject) => {
apolloClientTeams.query({
query: TEAM_BY_OWNER_QUERY
})
.then(response => {
window.localStorage.setItem('userTeams', JSON.stringify(response.data.teams_TeamsByOwner))
resolve({ teams: response.data.teams_TeamsByOwner})
})
.catch(error => {
console.log('apolloClient error getting user teams', error.graphQLErrors, error.stack)
reject(error)
})
})
}
/* Gettings All Events */
const networkInterfaceEvents = Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl
})
const apolloClientEvents = new Apollo.lib.ApolloClient({
networkInterface: networkInterfaceEvents,
connectToDevTools: true,
addTypename: false
})
const EVENTS_QUERY = Apollo.gql`
query events($maxStartDate: Int, $minEndDate: Int){
events_Events(maxStartDate: $maxStartDate, minEndDate: $minEndDate){
id
title
startDatetime
endDatetime
participants{
clone{
id
team{
slug
}
bot{
slug
}
}
}
}
}
`
const getCurrentEvents = () => {
var d = new Date()
var nowSeconds = Math.round(d.getTime() / 1000)
var twoWeeksAgoSeconds = nowSeconds - 1209600
return new Promise((resolve, reject) => {
apolloClientEvents.query({
query: EVENTS_QUERY,
variables: { maxStartDate: nowSeconds, minEndDate: twoWeeksAgoSeconds }
})
.then(response => {
window.localStorage.setItem('currentEvents', JSON.stringify(response.data.events_Events))
currentEvent = window.localStorage.getItem('currentEventObject')
if (currentEvent === null || currentEvent === '[]' || currentEvent === '') {
sharedStatus.currentEventIndex = -1
} else {
currentEvent = JSON.parse(currentEvent)
sharedStatus.currentEventIndex = response.data.events_Events.findIndex(function (element) {
return element.id == currentEvent.id
})
}
resolve({ currentEvents: response.data.events_Events})
})
.catch(error => {
console.log('apolloClient error getting current events', error.graphQLErrors, error.stack)
reject(error)
})
})
}
/* Getting all Clones */
const networkInterfaceClones = Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl
})
networkInterfaceClones.use([{
applyMiddleware (req, next) {
req.options.headers = {
authorization: `Bearer ${accessToken}`
}
next()
}
}])
const apolloClientClones = new Apollo.lib.ApolloClient({
networkInterface: networkInterfaceClones,
connectToDevTools: true
})
const CLONES_QUERY = Apollo.gql`
query Operations_Clones{
operations_Clones {
id
authId
teamId
botId
mode
resumeExecution
beginDatetime
endDatetime
waitTime
state
stateDatetime
createDatetime
lastLogs
runAsTeam
summaryDate
buyAverage
sellAverage
marketRate
combinedProfitsA
combinedProfitsB
assetA
assetB
botType
teamName
botName
botAvatar
teamAvatar
processName
keyId
botSlug
}
}
`
const getClones = () => {
return new Promise((resolve, reject) => {
apolloClientClones.query({
query: CLONES_QUERY
})
.then(response => {
window.localStorage.setItem('userClones', JSON.stringify(response.data.operations_Clones))
let clones = response.data.operations_Clones
for (let i = 0; i < clones.length; i++) {
let clone = clones[i]
if (clone.botType === 'Trading') {
let teamSlug = clone.teamName.toLowerCase()
teamSlug = teamSlug.replace(' ', '-')
let devTeam = ecosystem.getTeam(teamSlug)
let bot = ecosystem.getBot(devTeam, clone.botSlug)
if (bot !== undefined) {
bot.cloneId = clone.id
}
}
}
resolve({ clones: response.data.operations_Clones})
})
.catch(error => {
console.log('apolloClient error getting user clones', error.graphQLErrors, error.stack)
reject(error)
})
})
}
// To avoid race conditions, add asynchronous fetches to array
let fetchDataPromises = []
fetchDataPromises.push(getUser(), getTeamByOwner(), getCurrentEvents(), getClones(), authenticateUser())
// When all asynchronous fetches resolve, authenticate user or throw error.
await Promise.all(fetchDataPromises).then(result => {
}, err => {
console.error('[ERROR] Login -> GraphQL Fetch Error -> err = ', err)
})
thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick)
async function authenticateUser () {
// TODO USER_PROFILE should be retrieved from saweb-api ecosystem
return
let path = window.canvasApp.urlPrefix + 'AABrowserAPI/authenticateUser/'
return new Promise(
function (resolve, reject) {
callServer(undefined, path, (result) => {
let responseFromServer = JSON.parse(result)
err = responseFromServer.err
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
console.log('Please make sure you create a new team!')
reject(err)
}
window.USER_PROFILE = responseFromServer.userProfile
currentLabel = 'Logged In'
resolve()
})
}
)
}
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err.stack) }
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err) }
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.stack = ' + err.stack) }
}
}
function onClick () {
async function getEvents(accessToken, sharedStatus) {
var d = new Date()
var nowSeconds = Math.round(d.getTime() / 1000)
var twoWeeksAgoSeconds = nowSeconds - 1209600
let response = await axios({
url: window.canvasApp.graphQL.masterAppApiUrl,
method: 'post',
data: {
query:
`query events($maxStartDate: Int, $minEndDate: Int){
events_Events(maxStartDate: $maxStartDate, minEndDate: $minEndDate){
id
title
startDatetime
endDatetime
participants{
clone{
id
team{
slug
}
bot{
slug
}
}
}
}
}`,
},
variables: {
variables: { maxStartDate: nowSeconds, minEndDate: twoWeeksAgoSeconds }
},
headers: {
authorization: 'Bearer ' + accessToken
}
})
if (response.data.errors) {
console.log('Error getting events: ' + JSON.stringify(response.data.errors))
throw 'Error getting events: ' + JSON.stringify(response.data.errors)
} else {
window.localStorage.setItem('currentEvents', JSON.stringify(response.data.data.events_Events))
currentEvent = window.localStorage.getItem('currentEventObject')
if (currentEvent === null || currentEvent === '[]' || currentEvent === '') {
sharedStatus.currentEventIndex = -1
} else {
currentEvent = JSON.parse(currentEvent)
sharedStatus.currentEventIndex = response.data.data.events_Events.findIndex(function (element) {
return element.id == currentEvent.id
})
}
}
}
async function getClones(accessToken) {
let response = await axios({
url: window.canvasApp.graphQL.masterAppApiUrl,
method: 'post',
data: {
query:
`query Operations_Clones{
operations_Clones {
id
authId
teamId
botId
mode
resumeExecution
beginDatetime
endDatetime
waitTime
state
stateDatetime
createDatetime
lastLogs
runAsTeam
summaryDate
buyAverage
sellAverage
marketRate
combinedProfitsA
combinedProfitsB
assetA
assetB
botType
teamName
botName
botAvatar
teamAvatar
processName
keyId
botSlug
}
}
`
},
headers: {
authorization: 'Bearer ' + accessToken
}
})
if (response.data.errors) {
console.log('Error getting clones: ' + JSON.stringify(response.data.errors))
throw 'Error getting clones: ' + JSON.stringify(response.data.errors)
} else {
window.localStorage.setItem('userClones', JSON.stringify(response.data.data.operations_Clones))
let clones = response.data.data.operations_Clones
for (let i = 0; i < clones.length; i++) {
let clone = clones[i]
if (clone.botType === 'Trading') {
let teamSlug = clone.teamName.toLowerCase()
teamSlug = teamSlug.replace(' ', '-')
let devTeam = ecosystem.getTeam(teamSlug)
let bot = ecosystem.getBot(devTeam, clone.botSlug)
if (bot !== undefined) {
bot.cloneId = clone.id
}
}
}
}
}
function onClick() {
}
function getContainer (point) {
let container
/* First we check if this point is inside this object UI. */
function getContainer(point) {
/* First we check if this point is inside this object UI. */
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return this.container
} else {
/* This point does not belong to this space. */
/* This point does not belong to this space. */
return undefined
}
}
function draw () {
function draw() {
return // nothing to show.
thisObject.container.frame.draw(false, false)
let fontSize = 12
let label = currentLabel
if (label === undefined) { label = '' };
let point = {
x: thisObject.container.frame.width * 1 / 3,
y: (thisObject.container.frame.height / 2) + 4
}
point = thisObject.container.frame.frameThisPoint(point)
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'
browserCanvasContext.fillText(label, point.x, point.y)
}
}