diff --git a/ChartsSpace/PlottersManager.js b/ChartsSpace/PlottersManager.js
index 47e5c71f7..16ffb3acf 100644
--- a/ChartsSpace/PlottersManager.js
+++ b/ChartsSpace/PlottersManager.js
@@ -144,7 +144,7 @@ function newPlottersManager () {
try {
/* At this current version of the platform, we will support only one competition with only one plotter. */
- const COMPETITION_HOST = 'AAArena'
+ const COMPETITION_HOST = 'AAMasters'
const COMPETITION = 'Weekend-Deathmatch'
let objName = COMPETITION_HOST + '-' + COMPETITION
@@ -170,7 +170,7 @@ function newPlottersManager () {
}
}
/* Now we have all the initial data loaded and ready to be delivered to the new instance of the plotter. */
- let plotter = getNewPlotter(competition.plotter.host, competition.plotter.codeName, competition.plotter.moduleName)
+ let plotter = getNewPlotter(competition.plotter.devTeam, competition.plotter.codeName, competition.plotter.moduleName)
plotter.container.connectToParent(thisObject.container, true, true, false, true, true, true)
plotter.container.frame.position.x = thisObject.container.frame.width / 2 - plotter.container.frame.width / 2
plotter.container.frame.position.y = thisObject.container.frame.height / 2 - plotter.container.frame.height / 2
diff --git a/Dashboard.js b/Dashboard.js
index 663c7cfa6..46d5dd536 100644
--- a/Dashboard.js
+++ b/Dashboard.js
@@ -91,64 +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
- sessionToken
- role {
- id
- }
- }
- }
- `
- const getUser = () => {
- return new Promise((resolve, reject) => {
- apolloClient.query({
- query: QUERY,
- variables: {
- authId: authId
- }
- })
- .then(response => {
- sessionToken = response.data.users_UserByAuthId.sessionToken;
-
- 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
diff --git a/Exchange/ExchangeAPI.js b/Exchange/ExchangeAPI.js
deleted file mode 100644
index f72cfa729..000000000
--- a/Exchange/ExchangeAPI.js
+++ /dev/null
@@ -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);
- }
- }
-}
diff --git a/FloatingSpace/CodeEditor.js b/FloatingSpace/CodeEditor.js
index 8df2e4311..9b910f842 100644
--- a/FloatingSpace/CodeEditor.js
+++ b/FloatingSpace/CodeEditor.js
@@ -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 () {
diff --git a/Panels/ProductsPanel.js b/Panels/ProductsPanel.js
index 8c0cb96f3..8ba4c18da 100644
--- a/Panels/ProductsPanel.js
+++ b/Panels/ProductsPanel.js
@@ -58,33 +58,20 @@ function newProductsPanel () {
panelTabButton.fitFunction = thisObject.fitFunction
panelTabButton.initialize()
- /* Get the current teams of the logged in user. */
-
- let storedTeams = window.localStorage.getItem('userTeams')
- let userTeams
- if (storedTeams !== null && storedTeams !== undefined && storedTeams !== '') {
- userTeams = JSON.parse(storedTeams)
- }
-
/* First thing is to build the thisObject.productCards array */
- let devTeams = ecosystem.getTeams()
+ let ecosystem = JSON.parse(window.localStorage.getItem('ecosystem'))
- for (let i = 0; i < devTeams.length; i++) {
- let devTeam = devTeams[i]
+ for (let i = 0; i < ecosystem.devTeams.length; i++) {
+ let devTeam = ecosystem.devTeams[i]
for (let j = 0; j < devTeam.bots.length; j++) {
let bot = devTeam.bots[j]
- let userTeam = isUserTeam(devTeam.codeName, userTeams)
if (bot.type !== 'Indicator' && bot.cloneId === undefined) { continue }
if (bot.products !== undefined) {
for (let k = 0; k < bot.products.length; k++) {
let product = bot.products[k]
-
- if (window.localStorage.getItem('Show AAMaster Layers') === null) {
- if (product.shareWith !== 'Public' && !userTeam) { continue }
- }
/* Now we create Product objects */
let productCard = newProductCard()
@@ -253,17 +240,4 @@ function newProductsPanel () {
panelTabButton.draw()
}
-
- function isUserTeam (team, userTeams) {
- if (userTeams === undefined) {
- return false
- }
-
- for (let index = 0; index < userTeams.length; index++) {
- if (team === userTeams[index].slug) {
- return true
- }
- }
- return false
- }
}
diff --git a/README.md b/README.md
index 7fa3a65e8..789f59b54 100644
--- a/README.md
+++ b/README.md
@@ -1,20 +1,44 @@
# Welcome to the Canvas App
-The Canvas App is the built-in charting system of Superalgos. It is the software capable of running the Plotters that represent datasets graphically.
+The Canvas App provides a visual environment for the _Charting System_ and the _Strategy Designer_.
-
+**Installation (for developers):** To install the Canvas App, you need to install AAWeb, following [this guide](https://github.com/Superalgos/AAWeb/blob/develop/README.md).
-## Installation
+# Trading System Automation Demo
-To install the Canvas App, you need to install AAWeb, following this guide:
+Use the latest Chrome version to [access the Demo](https://demo.superalgos.org), sign up, log in and click on the CHARTS link in the Menu.
-https://github.com/Superalgos/AAWeb/blob/develop/README.md
+
+
+## Overview
-## Usage
+The first time you access the _Charts_, you will see the following screen, split in half. The top half features the space used by the _Charting System_ and the bottom half features the _Strategy Designer_.
-The first time you access the Canvas App, you will see the following screen with no chart displayed, since the app expects you to select one of the available layers at the Layers Panel on the left:
+Use the control in the center of the turquoise bar to pull the bar up and down in order to make more room to either application.
-
+
+
+Pulling the bar to the very top of the screen causes the _Charting System_ to stop consuming resources in your local machine, and gives you an ample view of the _Strategy Designer_.
+
+The **_Strategy Designer_** allows you to manage your _Trading System_. The structure represented by the various icons nested in a hierarchy of elements is the representation of the logic behind your _Strategies_.
+
+
+
+Pulling the bar to the very bottom of the screen causes the _Strategy Designer_ to stop consuming resources from your local machine, and offers a full-screen view of the _Charting System_.
+
+The **_Charting System_** plots indicators data along with the actions taken by the _Strategy Engine_ and the _Executor_, integrated with market data.
+
+
+
+The **_Superalgos Protocol_** (also refered to as the _protocol_) determines the structure in which all the information regarding a trading system is stored and—at the same time—provides a clear guidance on how traders using the various tools developed and distributed by the Superalgos Project shall create and automate their strategies.
+
+> You don't really _need_ to know this, but for the sake of context...
+>
+> The **_Strategy Engine_** backtests and forward tests the instructions defined on its _protocol_ file input. In coordination with the _Strategy Executor_, the engine can also live trade.
+>
+>The **_Strategy Executor_** interprets the execution instructions embedded at a _protocol_ file. The instructions determine the type of order to use, and what to do in every possible situation that could emerge during the placement and management of exchange orders.
+
+## Charts Interface
### Layers Panel
@@ -25,16 +49,12 @@ The layer title bar can have 3 possible background colors:
2. **Green**: layer is on.
3. **Yellow**: layer is loading. If it stays yellow, it means it can't load fully.
-Click on the "Candles" layer and wait a few seconds date is loaded and candles are plotted. You should see something like this:
-
-
-
-As you may see, the candles belong to the BTC/USDT market @ Poloniex. Even though the app supports other markets and exchanges, it is better for us to have only this one active, while the codebase matures.
-
-Notice the following 3 elements relative to the position of the mouse pointer:
-
+
+
### Main Elements
+Notice the following three elements relative to the position of the mouse pointer:
+
1. Above, the current datetime. This is the date and time at the mouse pointer position.
2. To the right, the current rate. This is the rate (in this case USDT per BTC) at the mouse pointer position.
3. Below, the current time period (or candle size if you wish). This is the currently displayed time period—not only for candles, but for any other object plotted across available layers.
@@ -43,73 +63,96 @@ Notice the following 3 elements relative to the position of the mouse pointer:
There are many things you can do with your mouse wheel.
+1. Scroll over the Layers Panel to access layers that may be out of reach downwards.
1. Scroll on top of or next to the datetime to produce a horizontal scaling.
1. Scroll on top of or next to the displayed rate to produce a vertical scaling.
1. Scroll on top of or next to the time period to change the time period to available values.
1. Scroll elsewhere over the chart to zoom in and out. The App will not only zoom in and out of the chart, but also automatically adjust the time period to the most convenient one (for the current zoom level).
-1. Scroll over the Layers Panel to access layers that may be out of reach downwards.
-After zooming in the main elements stay at the top, left and bottom of the viewport as you can see in the next screenshot:
+
+
+### Minimizing & Moving Floating Panels
-
+To minimize a panel, click on the small triangle on the right of their title bar. This will automatically position the panel at the bottom of the screen. Clicking again restores the panel to its previous position.
-### Moving Panels
-
-Drag and drop right-clicking on the title bar.
-
-### Minimizing Panels
-
-Click on the small triangle on the right of their title bar. This will automatically position the panel at the bottom of the screen. Clicking again restores the panel to its previous position.
-
-In the following image, the Layers Panel was dragged to the left and the Current Candle Panel was minimized:
-
-
+You may also drag and drop the panels by right-clicking on the title bar.
+
+
### Layers
-Superalgos is an open system, meaning anyone can build layers for this charting app. So far—with our current limited manpower—we have created 8 public layers (available without logging in) and 2 private layers (available to logged-in users):
+Superalgos is an open system, meaning anyone can build layers for the _Charting System_. So far—with our current limited manpower—we have created 8 public layers (available without logging in) and 2 private layers (available to logged-in users):
#### Public Layers
1. **Candles**: Typical candlesticks.
-
-
+
+
2. **Volumes**: I innovated a bit placing the buy volume at the bottom (in green), and the sell volume at the top (in red).
-
+
+
3. **Candle Stairs Patterns**: This is an unusual pattern proving any dataset may be plotted on the charts (and by extension, that anything can be added to the system). A Stair Pattern is defined as a set of candles going in the same direction, either up or down. You can think of these patterns as "Candle Channels", as they represent channels with an up or down direction based on underlying candles direction.
-
-
+
+
4. **Volume Stairs Patterns**: A similar concept, this time with volumes. Whenever a sequence of volume bars is found where each one is bigger than the previous one, they are bundled together in a "Stair". The same applies when they are going down (the next is smaller than the previous one). For a trading bot, this serves to identify if sell or buy volumes are raising or declining, if any.
-
+
+
+5. **Bollinger Bands**: This is the traditional [Bollinger Bands indicator](https://en.wikipedia.org/wiki/Bollinger_Bands). Bollinger Bands have a moving average, in our case calculated with the last 20 periods (the line in the middle of the bands). We are plotting the moving average with one color when it is going up, and with a different color when it's going down. The upper band is at 2 Standard Deviations from the center, pretty much like the lower band, also at 2 Standard Deviations. These are the most widely used Bollinger Bands settings.
-5. **Bollinger Bands**: This is the traditional (Bollinger Bands indicator)[https://en.wikipedia.org/wiki/Bollinger_Bands]. Bollinger Bands have a moving average, in our case calculated with the last 20 periods (the line in the middle of the bands). We are plotting the moving average with one color when it is going up, and with a different color when it's going down. The upper band is at 2 Standard Deviations from the center, pretty much like the lower band, also at 2 Standard Deviations. These are the most widely used Bollinger Bands settings.
+
+
+6. **Percentage Bandwidth or %B**: This is a well-known indicator that derives from the Bollinger Bands. In a nutshell it tells you how close the price is either to the upper band or the lower band at any point in time. When the price is in the middle of the bands (it is calculated with the close value of each candle), then %B is in the middle of its chart, at value 50. When the price touches the upper band, then %B is at 100, and finally when the price is at the lower band, then %B is at 0.
-
-
-6. **Percentage Bandwidth or %B**: This is a well-known indicator that derives from the Bollinger Bands. In a nutshell it tells you how close the price is either to the upper band or the lower band at any point in time. When the price is in the middle of the bands (it is calculated with the close value of each candle), then %B is in the middle of its chart, at value 50. When the price touches the upper band, then %B is at 100, and finally when the price is at the lower band, then %B is at 0. The chart contains lines at %B value 30 and 70 since those are the most common values for traders to forecast when a reversal may happen. In our chart, %B is the one represented at #1. I've found useful to add a moving average in order to smooth volatility a bit, and to be able to ask—at any time—if it is going up or down. The moving average calculated with the last 5 %B values is plotted as line #2. Finally I also added a property called Bandwidth, which represents the separation of the upper band from the lower band. It is a measure of the volatility and is plotted at #3.
+
+
+The chart features lines at %B value 30 and 70 since those are the most common values for traders to forecast when a reversal may happen. In our chart, %B is the one represented at #1. I've found useful to add a moving average in order to smooth volatility a bit, and to be able to ask—at any time—if it is going up or down. The moving average calculated with the last 5 %B values is plotted as line #2. Finally I also added a property called Bandwidth, which represents the separation of the upper band from the lower band. It is a measure of the volatility and is plotted at #3.

-
+
7. **Bollinger Channels**: This is a non-standard indicator derived from the Bollinger Bands. These types of channels are calculated using the Bollinger Bands moving average. Essentially an upward channel begins when the moving average turns from going down to going up, and the channel finishes when it turns from going up to down. A downward channel starts when the Bollinger Band moving average turns from going up to down, and it finishes when it starts going up again. Upward channels are plotted in green, while downward channels in red. Additional information can be found at the indicator's panel, like the number of periods contained at the channel.
-
-
+
+
8. **Bollinger Sub-Channels**: If we consider that one Bollinger Channel can have sub-channels with the same direction (up or down) but different slopes, then we get to the concept of Bollinger Sub-Channels. The most important property of a sub-channel is its slope. The possible values are: side, gentle, medium, high and extreme. With this information, a trading bot could easily ask if it is in a sub-channel with a certain slope and for how many periods.
-
-
+
+
#### Private Layers
1. **Trading Simulation**: The Trading Simulation layer displays a backtest + fordwardtest (paper trading) of whatever strategies you have created in the system. At sign up, you are provided with an initial set of strategies so that you can be up and running as quickly as possible. By activating the Trading Simulation layer you should be able to see something like this:
-
+
+
+Notice Asset Balances in the bottom left corner of the screen. Asset A is your _base asset_.
-Let's take a moment to analyze what you see on the chart:
+
+
+The dashed line represents the duration of the trade at the price of the _take position_ event. Notice how the _base asset_ is exchanged for Asset B and back to the _base asset_ as the trade closes.
-A. This shows you when you entered into one of your strategies (think of it as if the strategy was activated because when activation conditions were met). The first icon represents the moment when you entered into that particular strategy, and the second icon represents the moment you left the strategy.
+
+
+Notice the green horizontal bars indicating the _take profit_ value for each period (candle). _Take profit_ is managed in _phases_, marked with the corresponding icons.
+
+
+Notice the red horizontal bars indicating the _stop_ value for each period (candle). Stop is managed in _phases_, marked with the corresponding icons.
+
+
+
+2. **Trading Conditions**: The Trading Conditions layer helps identify which _conditions_ are met at each candle. Notice how _conditions_ are highlighted as the cursor moves through different candles.
+
+
+
+3. **Simulation Strategies**: The Simulation Strategies layer identifies trigger on and trigger off events, signaling the activation and deactivation of strategies.
+
+
+
+4. **Simulation Trades**: The Simulation Trades layer marks trades with a triangle whose hypotenuse connects the price at the _take position_ event with the _exit_ price. When the trade is profitable, the triangle is green; when the _exit_ happens at a loss, the triangle is red.
+
+
+
diff --git a/StrategySpace/StrategizerGateway.js b/StrategySpace/StrategizerGateway.js
index 682260f97..222449458 100644
--- a/StrategySpace/StrategizerGateway.js
+++ b/StrategySpace/StrategizerGateway.js
@@ -264,8 +264,6 @@ function newStrategizerGateway () {
const authId = user.authId
- let sessionToken
-
const apolloClient = new Apollo.lib.ApolloClient({
networkInterface: Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl,
@@ -277,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
}
}
}
diff --git a/TopSpace/CurrentEvent.js b/TopSpace/CurrentEvent.js
index b2831e277..3b66174c8 100644
--- a/TopSpace/CurrentEvent.js
+++ b/TopSpace/CurrentEvent.js
@@ -8,7 +8,7 @@ function newCurrentEvent () {
function buildEcosystemEventsHack (reload) {
let hackedEcosystem = [{
- 'codeName': 'AAArena',
+ 'codeName': 'AAMasters',
'displayName': 'AA Arena',
'competitions': [{
'codeName': 'Weekend-Deathmatch',
@@ -86,9 +86,9 @@ function newCurrentEvent () {
return thisObject
function initialize (pSharedStatus) {
- let sessionToken = window.localStorage.getItem('sessionToken')
+ let accessToken = window.localStorage.getItem('access_token')
- if (sessionToken === null || sessionToken === '') {
+ if (accessToken === null || accessToken === '') {
/* not logged in */
return
}
@@ -126,9 +126,9 @@ function newCurrentEvent () {
}
function onClick () {
- let sessionToken = window.localStorage.getItem('sessionToken')
+ let accessToken = window.localStorage.getItem('access_token')
- if (sessionToken === null || sessionToken === '') {
+ if (accessToken === null || accessToken === '') {
/* not logged in */
return
}
@@ -169,9 +169,9 @@ function newCurrentEvent () {
}
function draw () {
- let sessionToken = window.localStorage.getItem('sessionToken')
+ let accessToken = window.localStorage.getItem('access_token')
- if (sessionToken === null || sessionToken === '') {
+ if (accessToken === null || accessToken === '') {
/* not logged in */
return
}
diff --git a/TopSpace/EndUser.js b/TopSpace/EndUser.js
deleted file mode 100644
index b8699eb69..000000000
--- a/TopSpace/EndUser.js
+++ /dev/null
@@ -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)
- }
-}
diff --git a/TopSpace/Login.js b/TopSpace/Login.js
index 61aa996c1..099176916 100644
--- a/TopSpace/Login.js
+++ b/TopSpace/Login.js
@@ -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,387 +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')
- window.localStorage.removeItem('sessionToken')
- return
+ if (accessToken) {
+ await getEvents(accessToken, sharedStatus)
+ await getClones(accessToken)
}
- user = JSON.parse(user)
-
- const authId = user.authId
-
- let sessionToken
-
- 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
- sessionToken
- role {
- id
- }
- }
- }
- `
- const getUser = () => {
- return new Promise((resolve, reject) => {
- apolloClient.query({
- query: USERS_QUERY,
- variables: {
- authId: authId
- }
- })
- .then(response => {
- sessionToken = response.data.users_UserByAuthId.sessionToken
-
- 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 () {
- if (sessionToken === undefined) { sessionToken = '' }
-
- let path = window.canvasApp.urlPrefix + 'AABrowserAPI/authenticateUser/' + sessionToken
-
- 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
- window.localStorage.setItem('sessionToken', sessionToken)
-
- 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)
}
}
diff --git a/WebDebugLog.js b/WebDebugLog.js
index b6aa23539..3888b3b82 100644
--- a/WebDebugLog.js
+++ b/WebDebugLog.js
@@ -1,5 +1,4 @@
-
-function newWebDebugLog () {
+ function newWebDebugLog () {
let thisObject = {
write: write,
fileName: 'undefined'