Merge remote-tracking branch 'upstream/develop'

This commit is contained in:
Matias committed 2019-05-02 15:17:51 -03:00
commit 641dbc4b8f
47 files changed
+2371 -1730

No files matched your search

-283
View File
@@ -1,283 +0,0 @@

function newDeleteTradingHistory () {
const MODULE_NAME = 'Delete Trading History'
const INFO_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
var thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
}
var container = newContainer()
container.initialize()
thisObject.container = container
thisObject.container.frame.width = 50
thisObject.container.frame.height = BOTTOM_SPACE_HEIGHT
resize()
container.isDraggeable = false
container.isClickeable = true
let icon
let canDrawIcon = false
return thisObject
function initialize (callBackFunction) {
try {
if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') }
icon = new Image()
icon.onload = onImageLoad
function onImageLoad () {
canDrawIcon = true
}
icon.src = window.canvasApp.urlPrefix + 'Images/Icons/trash.png'
thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick)
window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize)
if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE) }
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err.message = ' + err.message) }
if (callBackFunction !== undefined) { callBackFunction(GLOBAL.DEFAULT_FAIL_RESPONSE) }
}
}
function resize () {
container.frame.position.x = viewPort.visibleArea.topRight.x
container.frame.position.y = viewPort.visibleArea.bottomLeft.y
}
function onClick () {
try {
if (INFO_LOG === true) { logger.write('[INFO] onClick -> Entering function.') }
let sessionToken = window.localStorage.getItem('sessionToken')
if (sessionToken === null || sessionToken === '') {
/* not logged in */
return
}
/*
To delete the trading history we will follow these steps:
1. Get the status report of that bot.
2. Iterate through all the entries for the startMode received by parameters.
3. For each entry, get the execution history file belonging to that entry.
4. Iterate on each entry of each execution history file to get the date of each execution that we will use to locate the
execution context file.
6. Delete every execution context file found.
7. Delete the execution history file after finishing the interation.
8. Delete the Sequence file belonging to the received Start Mode.
9. Save the Status Report without the records of this Start Mode.
*/
let storage = AzureStorage.Blob
let readOnlyBlobService
let writeOnlyBlobService
let deleteOnlyBlobService
let readConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'READ')
if (readConnectionString !== undefined) {
readOnlyBlobService = storage.createBlobService(readConnectionString)
}
let writeConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'WRITE')
if (writeConnectionString !== undefined) {
writeOnlyBlobService = storage.createBlobService(writeConnectionString)
}
let deleteConnectionString = window.USER_PROFILE.storagePermissions.get(window.DEV_TEAM + '.' + 'DELETE')
if (deleteConnectionString !== undefined) {
deleteOnlyBlobService = storage.createBlobService(deleteConnectionString)
}
let containerName = window.DEV_TEAM.toLowerCase()
let statusReportFilePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Reports' + '/' + 'Trading-Process'
let statusReportFileName = window.CURRENT_START_MODE + '.' + 'Status.Report.USDT_BTC.json'
readOnlyBlobService.getBlobToText(containerName, statusReportFilePath + '/' + statusReportFileName, onStatusReport)
function onStatusReport (err, text, response) {
try {
if (INFO_LOG === true) { logger.write('[INFO] onClick -> onStatusReport -> Entering function.') }
if (err && err.code === 'BlobNotFound') {
console.log(statusReportFilePath + '/' + statusReportFileName + ' not found. No history detected for this start mode.')
return
}
let statusReport = JSON.parse(text)
let toBeDeleted = 0
let deleted = 0
for (let i = 0; i < statusReport.runs.length; i++) {
/* For each record, we will get the execution history file. */
let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process'
let fileName = 'Execution.History.' + window.CURRENT_START_MODE + '.' + i + '.json'
readOnlyBlobService.getBlobToText(containerName, filePath + '/' + fileName, onExecutionHistory)
function onExecutionHistory (err, text, response) {
let executionHistory = JSON.parse(text)
for (let j = 0; j < executionHistory.length; j++) {
let dateTime = new Date(executionHistory[j][0])
let datePath = dateTime.getUTCFullYear() + '/' + pad(dateTime.getUTCMonth() + 1, 2) + '/' + pad(dateTime.getUTCDate(), 2) + '/' + pad(dateTime.getUTCHours(), 2) + '/' + pad(dateTime.getUTCMinutes(), 2)
let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process' + '/' + datePath
let fileName = 'Execution.Context.' + window.CURRENT_START_MODE + '.' + i + '.json'
deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onDeleted)
toBeDeleted++
function onDeleted (err, text, response) {
if (err) {
console.log(filePath + '/' + fileName + ' NOT deleted.')
console.log('err.message = ' + err.message)
} else {
console.log(filePath + '/' + fileName + ' deleted.')
}
deleted++
if (toBeDeleted === deleted) {
updateStatusReport()
}
}
}
/* Now we delete the execution history file. */
deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onExecutionHistoryDeleted)
function onExecutionHistoryDeleted (err, text, response) {
console.log(filePath + '/' + fileName + ' deleted.')
}
}
}
function updateStatusReport () {
try {
if (INFO_LOG === true) { logger.write('[INFO] onClick -> onStatusReport -> updateStatusReport -> Entering function.') }
statusReport.runs = []
/* Here is where we update the current Status Report file with the new version without records for the current Start Mode. */
let fileContent = JSON.stringify(statusReport)
writeOnlyBlobService.createBlockBlobFromText(containerName, statusReportFilePath + '/' + statusReportFileName, fileContent, onStatusReportUpdated)
function onStatusReportUpdated (err, text, response) {
console.log(statusReportFilePath + '/' + statusReportFileName + ' updated.')
}
/* Finally we delete the sequence file. */
let filePath = window.DEV_TEAM + '/' + window.CURRENT_BOT_CODE_NAME + '.1.0' + '/' + 'AACloud.1.1' + '/' + 'Poloniex' + '/' + 'dataSet.V1' + '/' + 'Output' + '/' + 'Trading-Process'
let fileName = 'Execution.History.' + window.CURRENT_START_MODE + '.' + 'Sequence' + '.json'
deleteOnlyBlobService.deleteBlob(containerName, filePath + '/' + fileName, onDeleted)
function onDeleted (err, text, response) {
console.log(filePath + '/' + fileName + ' deleted.')
}
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> onStatusReport -> updateStatusReport -> err.message = ' + err.message) }
}
}
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> onStatusReport -> err.message = ' + err.message) }
}
}
function pad (str, max) {
str = str.toString()
return str.length < max ? pad('0' + str, max) : str
}
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] onClick -> err.message = ' + err.message) }
}
}
function getContainer (point) {
try {
if (INFO_LOG === true) { logger.write('[INFO] getContainer -> Entering function.') }
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
}
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] getContainer -> err.message = ' + err.message) }
}
}
function draw () {
try {
if (INFO_LOG === true) { logger.write('[INFO] draw -> Entering function.') }
let sessionToken = window.localStorage.getItem('sessionToken')
if (sessionToken === null || sessionToken === '') {
/* not logged in */
return
}
thisObject.container.frame.draw(false, false)
if (canDrawIcon === false) { return }
let breakpointsHeight = 0
let imageHeight = 15
let imageWidth = 15
let imagePoint = {
x: 10,
y: thisObject.container.frame.height / 2 - imageHeight / 2 + breakpointsHeight
}
imagePoint = thisObject.container.frame.frameThisPoint(imagePoint)
browserCanvasContext.drawImage(icon, imagePoint.x, imagePoint.y, imageWidth, imageHeight)
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] draw -> err.message = ' + err.message) }
}
}
}
-195
View File
@@ -1,195 +0,0 @@
function newBreakpointsBar () {
var thisObject = {
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
}
var container = newContainer()
container.initialize()
thisObject.container = container
thisObject.container.frame.width = browserCanvasContext.width
thisObject.container.frame.height = 15
container.frame.position.x = 0
container.frame.position.y = viewPort.visibleArea.bottomRight.y
container.isDraggeable = false
container.isClickeable = true
let logo
let canDrawLogo = false
let datetime
let timePeriod
let timeLineCoordinateSystem
let chartContainer
let breakpointsByTimePeriod = new Map()
return thisObject
function initialize (pChartContainer, pTimeLineCoordinateSystem) {
timeLineCoordinateSystem = pTimeLineCoordinateSystem
chartContainer = pChartContainer
viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged)
timePeriod = INITIAL_TIME_PERIOD
thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick)
for (let i = 0; i < marketFilesPeriods.length; i++) {
let breakpointsMap = new Map()
breakpointsByTimePeriod.set(marketFilesPeriods[i][0], breakpointsMap)
}
for (let i = 0; i < dailyFilePeriods.length; i++) {
let breakpointsMap = new Map()
breakpointsByTimePeriod.set(dailyFilePeriods[i][0], breakpointsMap)
}
}
function onClick (pPoint) {
let point = {
x: pPoint.x,
y: pPoint.y
}
let miliSeconds = getMilisecondsFromPoint(point, chartContainer, timeLineCoordinateSystem)
miliSeconds = normalizeX(miliSeconds) // We are now exactly at the middle of the "candle" correspondind to the point clicked.
let breakpointsMap = breakpointsByTimePeriod.get(timePeriod)
let breakpoint = breakpointsMap.get(miliSeconds)
if (breakpoint === undefined) {
/* The breakpoint didnt exist, then we create one. */
breakpointsMap.set(miliSeconds, 1)
} else {
/* The breakpoint existed, so we remove it. */
breakpointsMap.set(miliSeconds, undefined)
}
}
function normalizeX (pX) {
return Math.trunc(pX / timePeriod) * timePeriod + timePeriod / 2
}
function onZoomChanged (event) {
timePeriod = recalculatePeriod(event.newLevel)
}
function setDatetime (pDatetime) {
datetime = new Date(pDatetime)
}
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 () {
/*
To draw the breakpoints, we will calculate the miliseconds for the first x pixel of the breakpoint bar, and for the last x pixel. Once we have that
we can create an array with all the possible points for breack points. Finally we can see if brealpoints exists at those points. We plot only the ones
that exists.
*/
let breakpointsMap = breakpointsByTimePeriod.get(timePeriod)
let beginX = {
x: viewPort.visibleArea.bottomLeft.x,
y: 0
}
let endX = {
x: viewPort.visibleArea.bottomRight.x,
y: 0
}
let beginMiliseconds = getMilisecondsFromPoint(beginX, chartContainer, timeLineCoordinateSystem)
let endMiliseconds = getMilisecondsFromPoint(endX, chartContainer, timeLineCoordinateSystem)
beginMiliseconds = normalizeX(beginMiliseconds)
endMiliseconds = normalizeX(endMiliseconds)
window.AT_BREAKPOINT = false
for (let miliSeconds = beginMiliseconds; miliSeconds < endMiliseconds; miliSeconds = miliSeconds + timePeriod) {
let breakpoint = breakpointsMap.get(miliSeconds)
if (breakpoint !== undefined) {
let point1 = {
x: miliSeconds,
y: 0
}
point1 = timeLineCoordinateSystem.transformThisPoint(point1)
point1 = transformThisPoint(point1, chartContainer)
let point2 = {
x: miliSeconds,
y: thisObject.container.frame.height / 2 + 1
}
point2 = thisObject.container.frame.frameThisPoint(point2)
let point = {
x: point1.x,
y: point2.y
}
let isCurrentRecord = false
if (datetime !== undefined) {
let dateValue = datetime.valueOf()
if (dateValue >= miliSeconds - timePeriod / 2 && dateValue <= miliSeconds + timePeriod / 2 - 1) {
isCurrentRecord = true
}
}
let radius = 5
let opacity = '0.5'
browserCanvasContext.lineWidth = 1
/* Outer Circle */
browserCanvasContext.beginPath()
browserCanvasContext.strokeStyle = 'rgba(123, 50, 40, ' + opacity + ')'
if (isCurrentRecord === false) {
browserCanvasContext.fillStyle = 'rgba(223, 70, 60, ' + opacity + ')'
} else {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + opacity + ')' /* highlight the current record */
window.AT_BREAKPOINT = true // We are hitting a breakpoint!
}
browserCanvasContext.arc(point.x, point.y, radius, 0, Math.PI * 2, true)
browserCanvasContext.closePath()
if (point.x < viewPort.visibleArea.topLeft.x + 50 || point.x > viewPort.visibleArea.bottomRight.x - 50) { /* we leave this history without fill. */ } else {
browserCanvasContext.fill()
}
browserCanvasContext.stroke()
}
}
}
}
+3 -39
View File
@@ -2,44 +2,8 @@
We are thrilled you are interested in contributing to this repository. Your help may be essential to the project's success and we want you in!
Superalgos is a collective project, currently at a very early stage. Although this repository is not open source software yet, we do welcome contributions from the community.
Superalgos is a collective project, currently at a very early stage. We not only welcome contributions but may even choose to incentivize relevant contributions via the project's native crypto token.
Contributions are deemed _voluntary work_. There might be incentives in place for certain kinds of contributions. Contact us for more information in this regard.
Please read the [Join the Dev Team]( https://superalgos.org/developers-join-dev-team.shtml) page in our website to learn more about how you may become a relevant member of the Community and even make a living out of contributing code to the project.
In any case, contributors agree to provide an express grant of patent rights for their contributions. Submitting Pull Requests to this repository represents an express agreement with the terms of our Balanced Contributor Intellectual Property Agreement. This agreement is a direct implementation of GitHub's [Balanced Employee Intellectual Property Agreement 1.0.1](https://github.com/github/balanced-employee-ip-agreement/blob/master/Balanced_Employee_IP_Agreement.md).
# Balanced Contributor Intellectual Property Agreement 1.0.1
This BALANCED CONTRIBUTOR INTELLECTUAL PROPERTY AGREEMENT is between person or team submitting Pull Requests to this repository and Superalgos.org ("Project").
**What is this?** This is the Project's Intellectual Property Agreement ("Agreement"). If you've worked in the technology space before, there's a good chance that you've run across one or more of these in the past. This document is the official, entire and exclusive agreement on what intellectual property ("IP") is yours, and what belongs to the Project.
**Why is this?** The Project needs to be clear on what IP it owns and has rights to. Its customers, contributors, and investors depend on the Project having the legal rights to the products and services it is providing so that the Project can continue operating and doing business.
The Project also believes that it's important to be clear on what it doesn't own. The Project doesn't want you looking over your shoulder every time you work on something personal or worrying that the Project will someday seize your open source non-lethal mousetrap simulation software. In other words, the Project isn't interested in appropriating your personal projects.
**Read this.** Please read this document and be sure you understand it before you submit any Pull Requests. Due to legal risk and corporate obligations, the Project cannot, by and large, negotiate its terms. If you feel you have a particular circumstance that keeps you from signing, please let the Project's legal department ("Legal") know. And, of course, you're always free and encouraged to get your own legal counsel to explain anything you're not clear on.
Cool? Then, by submitting your first Pull Request, and as a condition of your contribution, you agree to the following:
1. **What the Project owns.** The Project owns any IP ("Project IP") that you create, or help create _as its contributor_, but only if it meets one or more of these additional conditions: The IP was (i) related to an existing or prospective Project product or service at the time you developed, invented, or created it, (ii) developed for use by the Project, or (iii) developed or promoted with existing Project IP or with the Project's endorsement. You hereby grant and assign, and will grant and assign, to the Project all rights and interests in all Project IP.
"Project IP" includes concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, and works of authorship.
2. **What the Project doesn't own.** If you create IP that doesn't fit into one of the categories listed above, the Project doesn't own it. In other words, the Project doesn't own concepts, designs, developments, discoveries, ideas, improvements, inventions, trade secrets, trademarks, or works of authorship that you develop, invent, or create that do not meet any of the conditions in Section 1.
3. **Contribution of your IP to Project projects.** If you include your own IP – such as IP you created prior to working for the Project – into a Project product or service, it's still yours, of course, but you grant the Project a non-exclusive, irrevocable, fully paid-up, royalty-free, perpetual, sublicensable, transferable, worldwide license to use it without restriction in any way or implementation, in modified form, or as is, by itself, or incorporated into another product or service ("License"). If you include your name in any project over which the Project would have rights under this Agreement, such as in a copyright notice or a comment in code or documentation, then the License covers the rights associated with that use of your name as well.
4. **Your contributions to non-Project projects.** The Project recognizes that you may be engaged in work that requires you to submit IP to entities other than the Project, such as open source projects used by the Project. Please make sure that Legal is aware of what you're working on so that Legal can help with any licensing issues. If any project asks you to sign a contribution agreement, you should check with Legal before doing so. These agreements may be legally binding on the Project and so should be run through Legal first.
5. **Voluntary Works** All Project IP that you are involved with or create as part of your work for the Project is voluntary work which does not require compensation. There might be incentives in place for certain kinds of contributions. Feel free to contact the Project to learn more.
6. **No conflicts.** You agree that you don't have any outstanding agreements or obligations that conflict with those in this Agreement, and that you won't enter into conflicting agreements in the future.
7. **IP protection.** The Project might someday need to show the work that went into the development of IP that it uses or has used, or to make government filings to establish that it owns the IP or has rights over it. To help in those situations, you agree not to destroy any records you maintain relating to the development of any Project IP or IP under License (together, "All IP"), and, if the Project asks, to provide those records to the Project. You agree to help the Project secure and defend its rights in All IP. For your help the Project will compensate you at a reasonable rate. If the Project is unable to secure your help, you authorize the Project to act on your behalf (as your agent and attorney-in-fact) in securing all rights related to All IP.
8. **Confidentiality.** As an contributor or contractor of the Project, you will have access to sensitive confidential information that is important to the Project's business. You are responsible for keeping this information confidential, including after you end your work for the Project.
"Confidential Information" includes non-public technical details about our products or services, financial information, business strategies and forecasts, customer data, or any other information, data or know-how that is valuable to the Project because it is not publicly known.
The Project's Confidential Information is sensitive and we expect that you'll treat it as such. You agree to only use the Project's Confidential Information for the purpose of performing your contribution and for the benefit of the Project. You will do your best to keep Confidential Information secret. If you are not sure if something is Confidential Information, you should assume that it is, until you can confirm otherwise.
Contributions are deemed _voluntary work_, irrespective of the incentives that may be in place, and are subject to the conditions described in the LICENSE
-15
View File
@@ -1,15 +0,0 @@
function newCandle () {
var candle = {
open: undefined,
close: undefined,
min: 10000000000000,
max: 0,
begin: undefined,
end: undefined,
direction: undefined,
beginId: undefined,
endId: undefined
}
return candle
}
+45 -4
View File
@@ -38,6 +38,7 @@ function newCanvas () {
floatingSpace: undefined,
panelsSpace: undefined,
bottomSpace: undefined,
strategySpace: undefined,
animation: undefined,
initialize: initialize,
finalize: finalize
@@ -52,13 +53,14 @@ function newCanvas () {
/*
The canvas object represents a layer on top of the browser canvas object.
Graphically, thiscanvas object has 4 spaces:
Graphically, thiscanvas object has 5 spaces:
1. The "Top Space": It is where Team and User information is displayed.
2. The "Chart Space": It is where the charts are plotted.
3. The "Floating Space": It is where floating elements live. There is a physics engine for this layer that allows these elements to flow.
4. The "Panels Space": It is where panels live. --> This space has yet to be develop, currently pannels are somehow at the Chart Space.
5. The "Bottom Space": Includes the breakpoint bar and a toolbar.
5. The "Bottom Space": Includes UIControls that other panels can add there.
6. The "Strategy Spece": Functionality to manage Strategies
All these spaces are child objects of the Canvas object.
@@ -78,6 +80,9 @@ function newCanvas () {
|
|
---> bottomSpace
|
|
---> strategySpace
*/
function finalize () {
@@ -120,6 +125,9 @@ function newCanvas () {
thisObject.topSpace = newTopSpace()
await thisObject.topSpace.initialize()
thisObject.strategySpace = newStrategySpace()
await thisObject.strategySpace.initialize()
thisObject.bottomSpace = newBottomSpace()
thisObject.bottomSpace.initialize()
@@ -159,15 +167,16 @@ function newCanvas () {
/* Here we add all the functions that will be called during the animation cycle. */
animation.addCallBackFunction('ViewPort Draw', viewPort.draw, onFunctionAdded)
animation.addCallBackFunction('Chart Space Background', thisObject.chartSpace.drawBackground, onFunctionAdded)
animation.addCallBackFunction('Chart Space', thisObject.chartSpace.draw, onFunctionAdded)
animation.addCallBackFunction('Floating Space', thisObject.floatingSpace.floatingLayer.physicsLoop, onFunctionAdded)
animation.addCallBackFunction('Panels Space', thisObject.panelsSpace.draw, onFunctionAdded)
animation.addCallBackFunction('Splash Screen', splashScreen.draw, onFunctionAdded)
animation.addCallBackFunction('ViewPort Animate', viewPort.animate, onFunctionAdded)
animation.addCallBackFunction('ViewPort Draw', viewPort.draw, onFunctionAdded)
animation.addCallBackFunction('Bottom Space', thisObject.bottomSpace.draw, onFunctionAdded)
animation.addCallBackFunction('Top Space', thisObject.topSpace.draw, onFunctionAdded)
animation.addCallBackFunction('Strategy Space', thisObject.strategySpace.draw, onFunctionAdded)
animation.addCallBackFunction('Splash Screen', splashScreen.draw, onFunctionAdded)
animation.start(onStart)
function onFunctionAdded (err) {
@@ -298,6 +307,20 @@ function newCanvas () {
let container
/* We check if the mouse is over an element of the Strategy Space / */
container = thisObject.strategySpace.getContainer(point)
if (container !== undefined && container.isDraggeable === true) {
containerBeingDragged = container
containerDragStarted = true
return
}
if (container !== undefined && container.isDraggeable === false) {
return
}
/* We check if the mouse is over an element of the Top Space / */
container = thisObject.topSpace.getContainer(point)
@@ -373,6 +396,15 @@ function newCanvas () {
let container
/* We check if the mouse is over an element of the Strategy Space / */
container = thisObject.strategySpace.getContainer(point)
if (container !== undefined && container.isClickeable === true) {
container.eventHandler.raiseEvent('onMouseClick', point)
return
}
/* We check if the mouse is over an element of the Top Space / */
container = thisObject.topSpace.getContainer(point)
@@ -506,6 +538,15 @@ function newCanvas () {
let container
/* We check if the mouse is over an element of the Strategy Space / */
container = thisObject.strategySpace.getContainer(point)
if (container !== undefined && container.detectMouseOver === true) {
container.eventHandler.raiseEvent('onMouseOver', point)
return
}
/* We check if the mouse is over an element of the Top Space / */
container = thisObject.topSpace.getContainer(point)
+1
View File
@@ -139,4 +139,5 @@ function recalculatePeriod (zoomLevel) {
if (zoomLevel <= -28) {
return ONE_DAY_IN_MILISECONDS
}
return ONE_DAY_IN_MILISECONDS
}
+23 -3
View File
@@ -10,15 +10,29 @@ function newContainer () {
isWheelable: false,
name: undefined,
initialize: initialize,
finalize: finalize,
connectToParent: connectToParent,
isForThisPurpose: isForThisPurpose
}
let connectedToParentWidth = false
let connectedToParentHeight = false
let isConnectedToParent = false
let dimensionsChangedEventSubscriptionId
let onMouseOverEventSubscriptionId
let onMouseNotOverEventSubscriptionId
return thisObject
function finalize () {
if (isConnectedToParent === true) {
thisObject.parentContainer.eventHandler.stopListening(dimensionsChangedEventSubscriptionId)
thisObject.parentContainer.eventHandler.stopListening(onMouseOverEventSubscriptionId)
thisObject.parentContainer.eventHandler.stopListening(onMouseNotOverEventSubscriptionId)
}
}
function initialize (pName) {
thisObject.name = pName
@@ -28,7 +42,6 @@ function newContainer () {
thisObject.frame.container = thisObject
thisObject.eventHandler = newEventHandler()
thisObject.eventHandler.initialize()
thisObject.eventHandler.name = pName
thisObject.displacement = newDisplacement()
@@ -39,12 +52,15 @@ function newContainer () {
function connectToParent (parentContainer, onWidth, onHeight) {
connectedToParentWidth = onWidth
connectedToParentHeight = onHeight
isConnectedToParent = true
thisObject.displacement.parentDisplacement = parentContainer.displacement
thisObject.frame.parentFrame = parentContainer.frame
thisObject.parentContainer = parentContainer
thisObject.parentContainer.eventHandler.listenToEvent('Dimmensions Changed', onParentDimmensionsChanged)
thisObject.parentContainer.eventHandler.listenToEvent('onMouseOver', onMouseOver)
dimensionsChangedEventSubscriptionId = thisObject.parentContainer.eventHandler.listenToEvent('Dimmensions Changed', onParentDimmensionsChanged)
onMouseOverEventSubscriptionId = thisObject.parentContainer.eventHandler.listenToEvent('onMouseOver', onMouseOver)
onMouseNotOverEventSubscriptionId = thisObject.parentContainer.eventHandler.listenToEvent('onMouseNotOver', onMouseNotOver)
if (connectedToParentWidth) {
thisObject.frame.width = thisObject.parentContainer.frame.width
@@ -74,6 +90,10 @@ function newContainer () {
thisObject.eventHandler.raiseEvent('onMouseOver', event)
}
function onMouseNotOver (event) {
thisObject.eventHandler.raiseEvent('onMouseNotOver', event)
}
function isForThisPurpose (purpose) {
if (purpose !== undefined) {
switch (purpose) {
+134
View File
@@ -0,0 +1,134 @@
function newSidePanel () {
const MODULE_NAME = 'Side Panel'
let thisObject = {
areas: [],
sidePanelTab: undefined,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
const SIDE_PANEL_WIDTH = 450
const SIDE_PANEL_TAB_WIDTH = 400
let isInitialized = false
thisObject.container = newContainer()
thisObject.container.name = MODULE_NAME
thisObject.container.initialize()
thisObject.container.isClickeable = true
thisObject.container.isDraggeable = false
thisObject.container.status = 'hidden'
resize()
return thisObject
function initialize () {
thisObject.sidePanelTab = newSidePanelTab()
thisObject.sidePanelTab.container.connectToParent(thisObject.container, false, false)
thisObject.sidePanelTab.initialize()
window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize)
isInitialized = true
}
function resize () {
thisObject.container.frame.width = SIDE_PANEL_WIDTH
thisObject.container.frame.height = browserCanvas.height // - TOP_SPACE_HEIGHT
thisObject.container.frame.position.x = -SIDE_PANEL_WIDTH
thisObject.container.frame.position.y = 0 // TOP_SPACE_HEIGHT
}
function getContainer (point) {
let container
container = thisObject.sidePanelTab.getContainer(point)
if (container !== undefined) { return container }
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return thisObject.container
} else {
return undefined
}
}
function draw () {
if (isInitialized === false) { return }
borders()
thisObject.sidePanelTab.draw()
for (let i = 0; i < thisObject.areas.length; i++) {
let area = thisObject.areas[i]
area.draw()
}
}
function borders () {
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: 0
}
point2 = {
x: thisObject.container.frame.width,
y: 0
}
point3 = {
x: thisObject.container.frame.width,
y: thisObject.container.frame.height
}
point4 = {
x: 0,
y: thisObject.container.frame.height
}
point1 = thisObject.container.frame.frameThisPoint(point1)
point2 = thisObject.container.frame.frameThisPoint(point2)
point3 = thisObject.container.frame.frameThisPoint(point3)
point4 = thisObject.container.frame.frameThisPoint(point4)
browserCanvasContext.setLineDash([0, 0])
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
browserCanvasContext.lineTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
browserCanvasContext.lineTo(point1.x, point1.y)
browserCanvasContext.closePath()
let opacity = 1
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.LIGHT_GREY + ', ' + opacity + ''
browserCanvasContext.fill()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.GREY + ', ' + opacity + ''
browserCanvasContext.lineWidth = 0.3
browserCanvasContext.stroke()
/* Shadow */
if (thisObject.container.status !== 'hidden') {
for (let i = 0; i <= 30; i++) {
opacity = 1 - (i / 300) - 0.95
browserCanvasContext.setLineDash([0, 0])
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point2.x + i, point2.y)
browserCanvasContext.lineTo(point3.x + i, point3.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + opacity + ''
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
}
}
}
}
+216
View File
@@ -0,0 +1,216 @@
function newSidePanelTab () {
const MODULE_NAME = 'Side Panel Tab'
let thisObject = {
pointerDirection: 'left',
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
const TAB_WIDTH = 25
const TAB_HEIGHT = 60
let isInitialized = false
let animation = 'none'
let ORIGINAL_PARENT_POSITON
let xOffset = 0
thisObject.container = newContainer()
thisObject.container.name = MODULE_NAME
thisObject.container.initialize()
thisObject.container.isClickeable = true
thisObject.container.isDraggeable = false
return thisObject
function initialize () {
thisObject.container.frame.width = TAB_WIDTH
thisObject.container.frame.height = TAB_HEIGHT
thisObject.container.frame.position.x = 0 + thisObject.container.parentContainer.frame.width
thisObject.container.frame.position.y = 20
ORIGINAL_PARENT_POSITON = thisObject.container.parentContainer.frame.position.x
thisObject.container.eventHandler.listenToEvent('onMouseClick', onMouseClick)
isInitialized = true
}
function onMouseClick (event) {
if (thisObject.pointerDirection === 'left') {
animation = 'opening'
} else {
animation = 'closing'
}
}
function getContainer (point) {
let container
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return thisObject.container
} else {
return undefined
}
}
function draw () {
if (isInitialized === false) { return }
animate()
borders()
arrow()
}
function animate () {
const STEP = 50
if (animation === 'opening') {
xOffset = xOffset + STEP
thisObject.container.parentContainer.frame.position.x = ORIGINAL_PARENT_POSITON + xOffset
if (xOffset > thisObject.container.parentContainer.frame.width) {
animation = 'none'
xOffset = thisObject.container.parentContainer.frame.width
thisObject.container.parentContainer.frame.position.x = ORIGINAL_PARENT_POSITON + xOffset
thisObject.container.parentContainer.status = 'visible'
thisObject.pointerDirection = 'right'
}
}
if (animation === 'closing') {
xOffset = xOffset - STEP
thisObject.container.parentContainer.frame.position.x = ORIGINAL_PARENT_POSITON + xOffset
if (xOffset < 0) {
animation = 'none'
xOffset = 0
thisObject.container.parentContainer.frame.position.x = ORIGINAL_PARENT_POSITON
thisObject.container.parentContainer.status = 'hidden'
thisObject.pointerDirection = 'left'
}
}
}
function arrow () {
let point1
let point2
let point3
if (thisObject.pointerDirection === 'left') {
point1 = {
x: TAB_WIDTH * 3.5 / 10,
y: TAB_HEIGHT * 12.5 / 30
}
point2 = {
x: TAB_WIDTH * 6.5 / 10,
y: TAB_HEIGHT * 15 / 30
}
point3 = {
x: TAB_WIDTH * 3.5 / 10,
y: TAB_HEIGHT * 17.5 / 30
}
} else {
point1 = {
x: TAB_WIDTH * 6.5 / 10,
y: TAB_HEIGHT * 12.5 / 30
}
point2 = {
x: TAB_WIDTH * 3.5 / 10,
y: TAB_HEIGHT * 15 / 30
}
point3 = {
x: TAB_WIDTH * 6.5 / 10,
y: TAB_HEIGHT * 17.5 / 30
}
}
point1 = thisObject.container.frame.frameThisPoint(point1)
point2 = thisObject.container.frame.frameThisPoint(point2)
point3 = thisObject.container.frame.frameThisPoint(point3)
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
browserCanvasContext.lineTo(point3.x, point3.y)
browserCanvasContext.closePath()
let opacity = 1
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.GREY + ', ' + opacity + ''
browserCanvasContext.fill()
}
function borders () {
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: 0
}
point2 = {
x: TAB_WIDTH,
y: 0
}
point3 = {
x: TAB_WIDTH,
y: TAB_HEIGHT
}
point4 = {
x: 0,
y: TAB_HEIGHT
}
point1 = thisObject.container.frame.frameThisPoint(point1)
point2 = thisObject.container.frame.frameThisPoint(point2)
point3 = thisObject.container.frame.frameThisPoint(point3)
point4 = thisObject.container.frame.frameThisPoint(point4)
let opacity
/* Shadow */
for (let i = 0; i <= 5; i++) {
opacity = 1 - (i / 100) - 0.93
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x + i, point1.y + i)
browserCanvasContext.lineTo(point2.x + i, point2.y + i)
browserCanvasContext.lineTo(point3.x + i, point3.y + i)
browserCanvasContext.lineTo(point4.x + i, point4.y + i)
browserCanvasContext.lineTo(point1.x + i, point1.y + i)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + opacity + ''
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
}
/* Background and Border */
browserCanvasContext.setLineDash([0, 0])
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
browserCanvasContext.lineTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
browserCanvasContext.lineTo(point1.x, point1.y)
browserCanvasContext.closePath()
opacity = 1
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ''
browserCanvasContext.fill()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.GREY + ', ' + opacity + ''
browserCanvasContext.lineWidth = 0.3
browserCanvasContext.stroke()
}
}
+5 -4
View File
@@ -2,8 +2,6 @@
let canvas
let markets
let ecosystem = newEcosystem()
let INITIAL_ZOOM_LEVEL = -26 // This is the zoom level at the view port in which the APP starts.
let INITIAL_TIME_PERIOD = recalculatePeriod(MIN_ZOOM_LEVEL) // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser.
let viewPort = newViewPort()
function newDashboard () {
@@ -20,6 +18,9 @@ function newDashboard () {
const DEBUG_START_UP_DELAY = 0 // 3000; // This is a waiting time in case there is a need to debug the very first steps of initialization, to be able to hit F12 on time.
let userProfileChangedEventSubscriptionId
let browserResizedEventSubscriptionId
return thisObject
function start () {
@@ -33,8 +34,8 @@ function newDashboard () {
/* Here we will setup the global eventHandler that will enable the Canvas App to react to events happening outside its execution scope. */
window.canvasApp.eventHandler = newEventHandler()
window.canvasApp.eventHandler.listenToEvent('User Profile Changed', userProfileChanged)
window.canvasApp.eventHandler.listenToEvent('Browser Resized', browserResized)
userProfileChangedEventSubscriptionId = window.canvasApp.eventHandler.listenToEvent('User Profile Changed', userProfileChanged)
browserResizedEventSubscriptionId = window.canvasApp.eventHandler.listenToEvent('Browser Resized', browserResized)
loadImages(onImagesLoaded)
+1 -1
View File
@@ -7,7 +7,7 @@ The displacement is a vector that displaces everything static drawn on on the co
*/
function newDisplacement () {
var displacement = {
let displacement = {
containerName: '', // This is for debugging purposes only.
parentDisplacement: undefined, // Here we store the displacement object of the parent cointainer, if exists.
container: undefined,
+11 -56
View File
@@ -1,83 +1,38 @@

function newEventHandler () {
const CONSOLE_LOG = false
let thisObject = {
name: undefined, // This is for debugging purposes only.
parentEventHandler: undefined, // Here we store the parent cointainer zoom object.
listenToEvent: listenToEvent,
stopListening: stopListening,
raiseEvent: raiseEvent,
initialize: initialize
raiseEvent: raiseEvent
}
var eventHandlers = [] // Here we store all the functions we will call when an event is comming.
var eventHandlers = [] // Here we store all the functions we will call when an event is raiseed.
return thisObject
function initialize () {
}
function listenToEvent (eventType, handler, extraData) {
eventHandlers.push([eventType, handler, extraData])
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Event Handler named ' + thisObject.name + ' received a request to listenToEvent ' + eventType + ' and call ' + (handler.toString()).substring(0, 50))
}
let eventSubscriptionId = Math.trunc(Math.random() * 1000000)
eventHandlers.push([eventType, handler, extraData, eventSubscriptionId])
return eventSubscriptionId
}
function stopListening (pEventType, pHandler) {
if (pHandler === undefined) {
pHandler = 'Anonymous Function'
}
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Event Handler named ' + thisObject.name + ' received a request to stop listening to an the event ' + pEventType + ' with this handler: ' + pHandler)
}
function stopListening (pEventSubscriptionId) {
for (let i = 0; i < eventHandlers.length; i++) {
let record = eventHandlers[i]
let eventType = record[0]
let handler = record[1]
if (pHandler === 'Anonymous Function') {
if (pEventType === eventType) {
eventHandlers.splice(i, 1)
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Evethandler found and deleted.')
}
return
}
} else {
if (pEventType === eventType && pHandler.toString() === handler.toString()) {
eventHandlers.splice(i, 1)
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Evethandler found and deleted.')
}
return
}
if (pEventSubscriptionId === eventHandlers[i][3]) {
eventHandlers.splice(i, 1)
return
}
}
}
function raiseEvent (eventType, event) {
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Event Handler named ' + thisObject.name + ' received a request to raiseEvent ' + eventType + ' with this data ' + (event.toString()).substring(0, 50))
}
for (var i = 0; i < eventHandlers.length; i++) {
/* We will execute all the functions listening to this event type. */
if (eventHandlers[i][0] === eventType) {
var handler = eventHandlers[i][1]
var extraData = eventHandlers[i][2]
if (thisObject.name !== undefined && CONSOLE_LOG === true) {
console.log('Event Handler named ' + thisObject.name + ' received a request to raiseEvent ' + eventType + ' and will call this handler: ' + (handler.toString()).substring(0, 50))
}
let handler = eventHandlers[i][1]
let extraData = eventHandlers[i][2]
handler(event, extraData)
}
+1 -1
View File
@@ -8,7 +8,7 @@ function newFloatingObject () {
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
var thisObject = {
let thisObject = {
physicsLoop: physicsLoop,
eventHandler: undefined,
+1 -1
View File
@@ -1,6 +1,6 @@

function newNote () {
var thisObject = {
let thisObject = {
physicsLoop: physicsLoop,
onMouseOver: onMouseOver,
+14 -45
View File
@@ -3,7 +3,7 @@ function newFrame () {
const PANEL_CORNERS_RADIOUS = 5
const TITLE_BAR_HEIGHT = 14 // this must be grater than radius
var frame = {
let frame = {
containerName: '', // This is for debugging purposes only.
parentFrame: undefined, // Here we store the parent cointainer zoom object.
width: browserCanvas.width,
@@ -290,25 +290,16 @@ function newFrame () {
}
function background () {
borderPoint1 = {
x: PANEL_CORNERS_RADIOUS,
y: PANEL_CORNERS_RADIOUS
let params = {
cornerRadious: 5,
lineWidth: 0.1,
opacity: 0.75,
container: frame.container,
borderColor: UI_COLOR.DARK,
backgroundColor: UI_COLOR.WHITE
}
borderPoint2 = {
x: frame.width - PANEL_CORNERS_RADIOUS,
y: PANEL_CORNERS_RADIOUS
}
borderPoint3 = {
x: frame.width - PANEL_CORNERS_RADIOUS,
y: frame.height - PANEL_CORNERS_RADIOUS
}
borderPoint4 = {
x: PANEL_CORNERS_RADIOUS,
y: frame.height - PANEL_CORNERS_RADIOUS
}
roundedCornersBackground(params)
titleBarPoint1 = {
x: 0,
@@ -322,36 +313,9 @@ function newFrame () {
/* Now the transformations. */
borderPoint1 = frameThisPoint(borderPoint1)
borderPoint2 = frameThisPoint(borderPoint2)
borderPoint3 = frameThisPoint(borderPoint3)
borderPoint4 = frameThisPoint(borderPoint4)
titleBarPoint1 = frameThisPoint(titleBarPoint1)
titleBarPoint2 = frameThisPoint(titleBarPoint2)
/* We paint the panel background first */
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 0.75)'
browserCanvasContext.beginPath()
browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, PANEL_CORNERS_RADIOUS, 1.0 * Math.PI, 1.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - PANEL_CORNERS_RADIOUS)
browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, PANEL_CORNERS_RADIOUS, 1.5 * Math.PI, 2.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint3.x + PANEL_CORNERS_RADIOUS, borderPoint3.y)
browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, PANEL_CORNERS_RADIOUS, 0 * Math.PI, 0.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + PANEL_CORNERS_RADIOUS)
browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, PANEL_CORNERS_RADIOUS, 0.5 * Math.PI, 1.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y)
browserCanvasContext.closePath()
browserCanvasContext.fill()
browserCanvasContext.lineWidth = 0.1
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.MANGANESE_PURPLE + ', 0.75)'
browserCanvasContext.stroke()
/* We paint the title bar now */
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.75)'
@@ -397,6 +361,11 @@ function newFrame () {
function borders () {
/* Lest get the important points of the drawing so as to apply the needed transformations. */
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: 0
+16 -6
View File
@@ -18,7 +18,10 @@ const DEFAULT_MARKET = {
UI_COLOR = {
DARK: "48, 48, 54",
LIGHT: "234, 226, 222",
GREY: "150, 150, 150",
LIGHT_GREY: "247, 247, 247",
WHITE: "255, 255, 255",
BLACK: "0, 0, 0",
GOLDEN_ORANGE: "240, 162, 2",
RUSTED_RED: "204, 88, 53",
GREEN: "188, 214, 67",
@@ -117,6 +120,8 @@ function convertTimePeriodToName(pTimePeriod) {
window.AT_BREAKPOINT = false;
const USDT_BTC_HTH = 19900; // This is needed to know the scale of the market time line.
const WIDHTER_VOLUME_BAR_BASE_FACTOR = 2.5;
@@ -143,7 +148,16 @@ const _3_MINUTES_IN_MILISECONDS = 3 * 60 * 1000;
const _2_MINUTES_IN_MILISECONDS = 2 * 60 * 1000;
const _1_MINUTE_IN_MILISECONDS = 1 * 60 * 1000;
const EARLIEST_DATE = new Date(2014, 0, 18, 4, 26, 8);
let NEW_SESSION_INITIAL_DATE = new Date(); // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser.
let INITIAL_ZOOM_LEVEL = -28.25 // This is the zoom level at the view port in which the APP starts.
let INITIAL_TIME_PERIOD = ONE_DAY_IN_MILISECONDS // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser.
let maxDate = new Date();
maxDate.setMilliseconds(0);
maxDate.setDate(maxDate.getDate() + 365 * 1); // We might have charts that projects data into the future.
const MIN_PLOTABLE_DATE = new Date(2015, 0, 1, 0, 0, 0);
const MAX_PLOTABLE_DATE = maxDate;
const TOP_SPACE_HEIGHT = 5;
const BOTTOM_SPACE_HEIGHT = 35;
@@ -167,13 +181,9 @@ const PERIOD_10_MIN = "10-min";
const PERIOD_05_MIN = "05-min";
const PERIOD_01_MIN = "01-min";
let INITIAL_DATE = new Date(); // This value will be overwritten at the viewPort.initialize if the user had a prevous session with this same browser.
var maxDate = new Date();
maxDate.setMilliseconds(0);
maxDate.setDate(maxDate.getDate() + 10);
const MAX_PLOTABLE_DATE = maxDate;
/*
We define here the size of the chartSpace. It has to bee enough big in order to accomodate all the charts we expect to display in this space.
+187 -25
View File
@@ -1,39 +1,201 @@
COPYRIGHT NOTICE
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
© Copyright 2018 Superalgos.org
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
LICENSE NOTICE
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
Superalgos is a collaborative project currently at a very early stage. Because certain aspects of
the project are still not clearly defined, we have chosen to --temporarily-- grant a restrictive
license for the use of this repository, until those aspects are clarified and a proper open source
license can be granted.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
Superalgos.org is publishing the code of this software for several reasons. However, it shall not be considered free software yet. Superalgos is a collaborative project in the crypto space and this
software is still proprietary software.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
The reasons for opening up the code of this software at this stage are the following:
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
* We believe that transparency is paramount to achieving our goals, so we want everyone to
be able to understand what this software does and how. Opening up the code of this software
allows anyone to take a close look.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
* We welcome contributions from the community. Contributions are regarded as voluntary work.
There may be incentives in place for certain kinds of contributions. Contact us to learn more.
Contributors agree to provide an express grant of patent rights for their contributions.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
LICENSE WORDING
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
Superalgos.org grants a limited license for the following uses:
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
1. CODE REVIEW AND AUDITS. You are granted permission to clone this repository to analyze,
review or audit the code.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. COLLABORATING WITH Superalgos.org. You are granted permission to fork this repository
with the sole purpose of correcting bugs and developing functionality in agreement with
Superalgos.org. By contributing to this repository you explicitely agree to the terms
detailed in CONTRIBUTING.MD.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
PLEASE SEE CONTRIBUTING.MD FOR MORE DETAILS ON THE IMPLICATIONS SURROUNDING YOUR CONTRIBUTIONS TO THIS REPOSITORY.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1 -1
View File
@@ -1,5 +1,5 @@
function newPanelTabButton () {
var thisObject = {
let thisObject = {
container: undefined,
draw: draw,
parentContainer: undefined,
+7 -3
View File
@@ -1,5 +1,5 @@
function newProductsPanel () {
var thisObject = {
let thisObject = {
container: undefined,
getLoadingProductCards: getLoadingProductCards,
draw: draw,
@@ -41,11 +41,11 @@
thisObject.container.name = 'Layers @ ' + exchange + ' ' + market.assetB + '/' + market.assetA
thisObject.container.frame.containerName = thisObject.container.name
thisObject.container.frame.width = UI_PANEL.WIDTH.LARGE
thisObject.container.frame.height = viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y // UI_PANEL.HEIGHT.LARGE;
thisObject.container.frame.height = UI_PANEL.HEIGHT.LARGE // viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y // UI_PANEL.HEIGHT.LARGE;
var position = {
x: viewPort.visibleArea.topLeft.x,
y: viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height
y: viewPort.visibleArea.topLeft.y// viewPort.visibleArea.bottomLeft.y - thisObject.container.frame.height
}
thisObject.container.frame.position = position
@@ -64,6 +64,7 @@
userTeams = JSON.parse(storedTeams)
userTeam = userTeams[0] // Currently we assume a user can be at only one team.
}
if (userTeam === undefined) { userTeam = {slug: ''} }
/* First thing is to build the productCards array */
@@ -82,6 +83,9 @@
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' && devTeam.codeName !== userTeam.slug) { continue }
}
/* Now we create Product objects */
let productCard = newProductCard()
+2 -1
View File
@@ -37,7 +37,7 @@ function newTimeControlPanel () {
panelTabButton.container.frame.parentFrame = thisObject.container.frame
panelTabButton.initialize()
let datetime = INITIAL_DATE
let datetime = NEW_SESSION_INITIAL_DATE
let datetimeDisplay = {
currentDatetime: datetime,
@@ -92,6 +92,7 @@ function newTimeControlPanel () {
}
function draw () {
return
thisObject.container.frame.draw(false, false, true)
thisObject.datetimeDisplay.draw()
panelTabButton.draw()
+3 -2
View File
@@ -10,7 +10,7 @@ function newPlottersManager () {
let competitionPlotters = []
let timePeriod = INITIAL_TIME_PERIOD
let datetime = INITIAL_DATE
let datetime = NEW_SESSION_INITIAL_DATE
let thisObject = {
setDatetime: setDatetime,
@@ -476,7 +476,7 @@ function newPlottersManager () {
if (INFO_LOG === true) { logger.write('[INFO] initializeProductPlotter -> onProductStorageInitialized -> onPlotterInizialized -> key = ' + pProductCard.product.plotter.devTeam + '-' + pProductCard.product.plotter.codeName + '-' + pProductCard.product.plotter.moduleName) }
try {
// plotter.positionAtDatetime(INITIAL_DATE);
// plotter.positionAtDatetime(NEW_SESSION_INITIAL_DATE);
} catch (err) {
// If the plotter does not implement this function its ok.
}
@@ -619,6 +619,7 @@ function newPlottersManager () {
productPlotters[i].storage.finalize()
if (productPlotters[i].plotter.finalize !== undefined) {
productPlotters[i].plotter.container.finalize()
productPlotters[i].plotter.finalize()
}
+2 -2
View File
@@ -8,7 +8,7 @@ function newProductCard () {
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
var thisObject = {
let thisObject = {
container: undefined,
draw: draw,
status: 'off',
@@ -70,7 +70,7 @@ function newProductCard () {
}
let timePeriod = INITIAL_TIME_PERIOD
let datetime = INITIAL_DATE
let datetime = NEW_SESSION_INITIAL_DATE
/* TODO We are in a transition period in which bots and teams images might be located at different places.
What we are going to do then is to try to load them from both places and use the variable that finally gets an
+3 -3
View File
@@ -186,7 +186,8 @@ function newProductStorage (pName) {
let event = {
totalValue: pCaller.getExpectedFiles(),
currentValue: pCaller.getFilesLoaded()
currentValue: pCaller.getFilesLoaded(),
filesNotLoaded: pCaller.getFilesNotLoaded()
}
thisObject.eventHandler.raiseEvent('Market File Loaded', event)
@@ -194,7 +195,7 @@ function newProductStorage (pName) {
if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> event.currentValue = ' + event.currentValue) }
if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> event.totalValue = ' + event.totalValue) }
if (event.currentValue === event.totalValue) {
if (event.currentValue + event.filesNotLoaded === event.totalValue) {
dataSetsLoaded++
if (INFO_LOG === true) { logger.write('[INFO] initialize -> onMarketFileReady -> dataSetsLoaded = ' + dataSetsLoaded) }
@@ -424,4 +425,3 @@ function newProductStorage (pName) {
}
}
}
+104 -4
View File
@@ -1,15 +1,115 @@
# Welcome to the Canvas App
The Canvas App is the in-house charting system of Superalgos. It is the software capable of running the Plotters that can represent datasets graphically.
The Canvas App is the built-in charting system of Superalgos. It is the software capable of running the Plotters that represent datasets graphically.
![image](https://user-images.githubusercontent.com/9479367/55588708-ca8f1e80-572e-11e9-9073-a591b1143171.png)
![image](https://user-images.githubusercontent.com/9479367/56820881-520f0f80-684d-11e9-9f47-4b3ca38370e9.png)
## Installation
To install the Canvas App, you need to install AAWeb. Please follow this guide:
To install the Canvas App, you need to install AAWeb, following this guide:
https://github.com/Superalgos/AAWeb/blob/develop/README.md
## Usage
Use your mouse wheel to zoom out and zoom in, and left click to drag and drop the charts. The Canvas App is designed to have a similar experience than Google Maps in the sense that allows you to easily navigate through different markets, potentially at different exchanges just by zooming out, dragging / dropping and zooming in at your destination.
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:
![image](https://user-images.githubusercontent.com/9479367/56821029-a3b79a00-684d-11e9-8226-2471e32b70e7.png)
### Layers Panel
This panel includes different layers you may visualize by toggling them on and off with a single mouse clicks.
The layer title bar can have 3 possible background colors:
1. **Red**: layer is off.
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:
![image](https://user-images.githubusercontent.com/9479367/56821266-1fb1e200-684e-11e9-9492-8bcbc3ed84d8.png)
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
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.
### Mouse Wheel Operations
There are many things you can do with your mouse wheel.
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:
![image](https://user-images.githubusercontent.com/9479367/56822037-30635780-6850-11e9-8d1c-1c58959f46e9.png)
### 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:
![image](https://user-images.githubusercontent.com/9479367/56822276-db741100-6850-11e9-9e23-d3fabb82754c.png)
### 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):
#### Public Layers
1. **Candles**: Typical candlesticks.
![image](https://user-images.githubusercontent.com/9479367/56822785-6acdf400-6852-11e9-98d9-0bd19ca98d61.png)
2. **Volumes**: I innovated a bit placing the buy volume at the bottom (in green), and the sell volume at the top (in red).
![image](https://user-images.githubusercontent.com/9479367/56822811-8638ff00-6852-11e9-9f25-6b97720a9d1b.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56822884-b6809d80-6852-11e9-999a-bccddfb68229.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56822975-f34c9480-6852-11e9-9175-19d397b89441.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56833341-82b37100-686e-11e9-8b17-55b3bf7a8fdb.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56834223-1c7c1d80-6871-11e9-9687-ae5dc12d0336.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56834955-30c11a00-6873-11e9-8601-9d8abc8fab84.png)
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.
![image](https://user-images.githubusercontent.com/9479367/56835528-c610de00-6874-11e9-8431-3cfe0c515f3e.png)
#### 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:
![image](https://user-images.githubusercontent.com/9479367/56860461-0799aa00-6997-11e9-9c2d-5ace122a5c25.png)
Let's take a moment to analyze what you see on the chart:
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.
-713
View File
@@ -1,713 +0,0 @@
function newChartGrid () {
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
let container = newContainer()
container.initialize()
thisObject.container = container
thisObject.container.frame.width = 0
thisObject.container.frame.height = 0
container.frame.position.x = 0
container.frame.position.y = 0
container.isDraggeable = false
container.isClickeable = true
return thisObject
function initialize () {
}
function getContainer (point) {
let container
container = rigthScale.getContainer(point)
if (container !== undefined) {
return container
}
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
return this.container
} else {
/* This point does not belong to this space. */
return undefined
}
}
function draw (container, timeLineCoordinateSystem) {
return // not for now
rightScaleBackground()
leftScaleBackground()
let periods = []
let boxes = []
let labels = []
const basePeriod = {
x: 8 * 60 * 60 * 1000,
y: timeLineCoordinateSystem.max.y / 1000
}
let period = {
x: basePeriod.x,
y: basePeriod.y
}
calculateTimeLabels()
printLabels(1000, 10000)
function calculateTimeLabels () {
periods.push(period) // 0
period = {
x: basePeriod.x / 8,
y: basePeriod.y / 10
}
periods.push(period) // 1
period = {
x: basePeriod.x / 8 / 6,
y: basePeriod.y / 100
}
periods.push(period) // 2
period = {
x: basePeriod.x * 3,
y: basePeriod.y * 10
}
periods.push(period) // 3
period = {
x: basePeriod.x * 3 * 7,
y: basePeriod.y * 100
}
periods.push(period) // 4
/* Period #2 Plotting */
boxes = []
plotGrid(periods[2])
labels = []
/* Label Calculation */
for (let i = 0; i < boxes.length; i++) {
const UPPER_PERIOD = 1
let box = boxes[i]
let currentValue = box.topLeft
currentValue = unTransformThisPoint(currentValue, container)
currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height)
/* We must compare the current value on the current period, against the next period, to know which cell we are in. */
let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000)
switch (distanceToNextPeriod) {
case 0: {
labels.push('0')
break
}
case Math.trunc(1 / 6 * 1000): {
}
labels.push('10')
break
case Math.trunc(2 / 6 * 1000): {
}
labels.push('20')
break
case Math.trunc(3 / 6 * 1000): {
}
labels.push('30')
break
case Math.trunc(4 / 6 * 1000): {
}
labels.push('40')
break
case Math.trunc(5 / 6 * 1000): {
}
labels.push('50')
break
}
}
printLabels(1, 150)
/* Period #1 Plotting */
boxes = []
plotGrid(periods[1])
labels = []
/* Label Calculation */
for (let i = 0; i < boxes.length; i++) {
const UPPER_PERIOD = 3
let box = boxes[i]
let currentValue = box.topLeft
currentValue = unTransformThisPoint(currentValue, container)
currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height)
/* We must compare the current value on the current period, against the next period, to know which cell we are in. */
let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000)
switch (distanceToNextPeriod) {
case 0: {
labels.push('0 Hs')
break
}
case Math.trunc(1 / 24 * 1000): {
}
labels.push('1 Hs')
break
case Math.trunc(2 / 24 * 1000): {
}
labels.push('2 Hs')
break
case Math.trunc(3 / 24 * 1000): {
}
labels.push('3 Hs')
break
case Math.trunc(4 / 24 * 1000): {
}
labels.push('4 Hs')
break
case Math.trunc(5 / 24 * 1000): {
}
labels.push('5 Hs')
break
case Math.trunc(6 / 24 * 1000): {
}
labels.push('6 Hs')
break
case Math.trunc(7 / 24 * 1000): {
}
labels.push('7 Hs')
break
case Math.trunc(8 / 24 * 1000): {
}
labels.push('8 Hs')
break
case Math.trunc(9 / 24 * 1000): {
}
labels.push('9 Hs')
break
case Math.trunc(10 / 24 * 1000): {
}
labels.push('10 Hs')
break
case Math.trunc(11 / 24 * 1000): {
}
labels.push('11 Hs')
break
case Math.trunc(12 / 24 * 1000): {
}
labels.push('12 Hs')
break
case Math.trunc(13 / 24 * 1000): {
}
labels.push('13 Hs')
break
case Math.trunc(14 / 24 * 1000): {
}
labels.push('14 Hs')
break
case Math.trunc(15 / 24 * 1000): {
}
labels.push('15 Hs')
break
case Math.trunc(16 / 24 * 1000): {
}
labels.push('16 Hs')
break
case Math.trunc(17 / 24 * 1000): {
}
labels.push('17 Hs')
break
case Math.trunc(18 / 24 * 1000): {
}
labels.push('18 Hs')
break
case Math.trunc(19 / 24 * 1000): {
}
labels.push('19 Hs')
break
case Math.trunc(20 / 24 * 1000): {
}
labels.push('20 Hs')
break
case Math.trunc(21 / 24 * 1000): {
}
labels.push('21 Hs')
break
case Math.trunc(22 / 24 * 1000): {
}
labels.push('22 Hs')
break
case Math.trunc(23 / 24 * 1000): {
}
labels.push('23 Hs')
break
}
}
printLabels(5, 250)
/* Period #0 Plotting */
boxes = []
plotGrid(periods[0])
labels = []
/* Label Calculation */
for (let i = 0; i < boxes.length; i++) {
const UPPER_PERIOD = 3
let box = boxes[i]
let currentValue = box.topLeft
currentValue = unTransformThisPoint(currentValue, container)
currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height)
/* We must compare the current value on the current period, against the next period, to know which cell we are in. */
let distanceToNextPeriod = Math.trunc((currentValue.x / periods[UPPER_PERIOD].x - Math.trunc(currentValue.x / periods[UPPER_PERIOD].x)) * 1000)
switch (distanceToNextPeriod) {
case 0: {
labels.push('Morning')
break
}
case Math.trunc(1 / 3 * 1000): {
}
labels.push('Afternoon')
break
case Math.trunc(2 / 3 * 1000): {
}
labels.push('Evening')
break
}
}
printLabels(15, 50)
/* Period #3 Plotting */
boxes = []
plotGrid(periods[3])
labels = []
/* Label Calculation */
for (let i = 0; i < boxes.length; i++) {
const UPPER_PERIOD = 1
let box = boxes[i]
let currentValue = box.topLeft
currentValue = unTransformThisPoint(currentValue, container)
currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height)
let date = new Date(currentValue.x)
labels.push(date.toDateString())
}
printLabels(100, 2250)
/* Period #4 Plotting */
boxes = []
plotGrid(periods[4])
labels = []
/* Label Calculation */
for (let i = 0; i < boxes.length; i++) {
const UPPER_PERIOD = 1
let box = boxes[i]
let currentValue = box.topLeft
currentValue = unTransformThisPoint(currentValue, container)
currentValue = timeLineCoordinateSystem.unInverseTransform(currentValue, container.frame.height)
let date = new Date(currentValue.x)
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
labels.push(monthNames[date.getMonth()] + ' ' + date.getFullYear())
}
}
function plotGrid (period) {
return
let periodWidth = period.x
let periodHeight = period.y
let visiblePoint1 = {
x: viewPort.visibleArea.topLeft.x,
y: viewPort.visibleArea.bottomLeft.y
}
visiblePoint1 = unTransformThisPoint(visiblePoint1, container)
visiblePoint1 = timeLineCoordinateSystem.unInverseTransform(visiblePoint1, container.frame.height)
let visiblePoint2 = {
x: viewPort.visibleArea.bottomRight.x,
y: viewPort.visibleArea.topRight.y
}
visiblePoint2 = unTransformThisPoint(visiblePoint2, container)
visiblePoint2 = timeLineCoordinateSystem.unInverseTransform(visiblePoint2, container.frame.height)
startingPoint = {
x: Math.trunc(visiblePoint1.x / periodWidth) * periodWidth,
y: Math.round(Math.trunc(visiblePoint1.y / periodHeight) * periodHeight * 100000) / 100000
}
endingPoint = {
x: Math.trunc(visiblePoint2.x / periodWidth) * periodWidth,
y: Math.trunc(visiblePoint2.y / periodHeight) * periodHeight
}
let lineWidth
if (viewPort.zoomLevel > 0) {
lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 20
} else {
lineWidth = period.x / basePeriod.x + period.x / basePeriod.x * viewPort.zoomLevel / 80
}
if (lineWidth < 0.7) {
return
}
if (lineWidth > 1.4) {
lineWidth = 1.4
}
browserCanvasContext.beginPath()
let y1
let y2
let lastRightLabelPosition = {
x: 0,
y: 0
}
let lastLeftLabelPosition = {
x: 0,
y: 0
}
for (var j = startingPoint.y; j <= endingPoint.y + periodHeight; j = j + periodHeight) {
if (j >= 0 && j <= timeLineCoordinateSystem.max.y) {
let point1 = {
x: visiblePoint1.x,
y: j
}
let point2 = {
x: visiblePoint2.x,
y: j
}
point1 = timeLineCoordinateSystem.transformThisPoint(point1)
point2 = timeLineCoordinateSystem.transformThisPoint(point2)
point1 = transformThisPoint(point1, container)
point2 = transformThisPoint(point2, container)
if (point1.y >= viewPort.visibleArea.topLeft.y) {
/* Here we keep the last two positive valued of y */
y2 = y1
y1 = point1.y
}
point1 = viewPort.fitIntoVisibleArea(point1)
point2 = viewPort.fitIntoVisibleArea(point2)
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
/* Now we put the scale on the right side of the chart */
drawRigthScale()
drawLeftScale()
function drawRigthScale () {
/* And now the scale. */
let fontSize = 10
let label = ' ' + Math.round(j * 1) / 1
label = Number(label).toLocaleString()
let labelPoint = {
x: viewPort.visibleArea.bottomRight.x + 5,
y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO
}
if (Math.abs(lastRightLabelPosition.y - labelPoint.y > fontSize || lastRightLabelPosition.y === 0)) {
if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) {
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y)
}
}
lastRightLabelPosition.x = labelPoint.x
lastRightLabelPosition.y = labelPoint.y
}
function drawLeftScale () {
let fontSize = 10
/*
j is a value between 0 and the max y on the scale of the products.
If we want to convert j to the scale of profits we need to apply the following formula:
*/
let labelValue = (j - timeLineCoordinateSystem.max.y / 2) * 200 / timeLineCoordinateSystem.max.y
labelValue = Math.round(labelValue * 100) / 100
if (labelValue > 0) { labelValue = '+' + labelValue }
if (parseInt(labelValue) > -10 && parseInt(labelValue) < 10) { labelValue = ' ' + labelValue }
if (parseInt(labelValue) === 0) { labelValue = ' ' + labelValue }
let label = ' ' + pad(labelValue, 3) + '%'
let labelPoint = {
x: 0,
y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO
}
if (Math.abs(lastLeftLabelPosition.y - labelPoint.y > fontSize || lastLeftLabelPosition.y === 0)) {
if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) {
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y)
}
}
lastLeftLabelPosition.x = labelPoint.x
lastLeftLabelPosition.y = labelPoint.y
}
}
}
let x1
let x2
for (var i = startingPoint.x; i <= endingPoint.x + periodWidth; i = i + periodWidth) {
let point3 = {
x: i,
y: 0
}
let point4 = {
x: i,
y: timeLineCoordinateSystem.max.y
}
point3 = timeLineCoordinateSystem.transformThisPoint(point3)
point4 = timeLineCoordinateSystem.transformThisPoint(point4)
point3 = transformThisPoint(point3, container)
point4 = transformThisPoint(point4, container)
/* Here we keep the last two positive valued of y */
x2 = x1
x1 = point3.x
if (x2 !== undefined) {
let topLeft = {
x: x2,
y: y1
}
let bottomRight = {
x: x1,
y: y2
}
let box = {
topLeft: topLeft,
bottomRight: bottomRight
}
boxes.push(box)
}
/* Painting the lines */
point3 = viewPort.fitIntoVisibleArea(point3)
point4 = viewPort.fitIntoVisibleArea(point4)
browserCanvasContext.moveTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
}
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.05' + Math.trunc(lineWidth + 1) + ')'
browserCanvasContext.lineWidth = lineWidth
browserCanvasContext.stroke()
}
function printLabels (baseZoomFilter, maxZoom) {
let zoomFilter = viewPort.zoomFontSize(baseZoomFilter)
if (zoomFilter < 7 || zoomFilter > maxZoom) {
return
}
for (let i = 0; i < boxes.length; i++) {
let label = labels[i]
if (label === undefined) {
label = 'undefined'
}
let fontSize = 10
let labelPoint = {
x: boxes[i].topLeft.x - label.length / 2 * fontSize * FONT_ASPECT_RATIO,
y: viewPort.visibleArea.topLeft.y - fontSize / 2 + 1
}
let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO
browserCanvasContext.beginPath()
browserCanvasContext.rect(labelPoint.x, labelPoint.y - fontSize, xOffset * 2, fontSize)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'
browserCanvasContext.fill()
browserCanvasContext.closePath()
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y)
}
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', 1)'
browserCanvasContext.beginPath()
browserCanvasContext.rect(0, TOP_SPACE_HEIGHT, viewPort.visibleArea.topLeft.x, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT)
browserCanvasContext.rect(viewPort.visibleArea.topRight.x, TOP_SPACE_HEIGHT, 500, viewPort.visibleArea.topLeft.y - TOP_SPACE_HEIGHT)
browserCanvasContext.closePath()
browserCanvasContext.fill()
}
function rightScaleBackground () {
const RIGHT_MARGIN = 50
/* We will paint some transparent background here. */
let opacity = '0.95'
browserCanvasContext.beginPath()
browserCanvasContext.rect(viewPort.visibleArea.topRight.x, viewPort.visibleArea.topRight.y, RIGHT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'
browserCanvasContext.closePath()
browserCanvasContext.fill()
}
function leftScaleBackground () {
const LEFT_MARGIN = 50
/* We will paint some transparent background here. */
let opacity = '0.95'
browserCanvasContext.beginPath()
browserCanvasContext.rect(0, viewPort.visibleArea.topRight.y, LEFT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'
browserCanvasContext.closePath()
browserCanvasContext.fill()
}
}
}
+211
View File
@@ -0,0 +1,211 @@
function newRateScale () {
const MODULE_NAME = 'Right Scale'
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize,
heightPercentage: 100
}
const HEIGHT_PERCENTAGE_DEFAULT_VALUE = 50
const STEP_SIZE = 5
const MIN_WIDTH = 50
thisObject.container = newContainer()
thisObject.container.initialize(MODULE_NAME)
thisObject.container.frame.width = viewPort.margins.RIGHT
thisObject.container.frame.height = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y
thisObject.container.frame.position.x = viewPort.visibleArea.bottomRight.x
thisObject.container.frame.position.y = TOP_SPACE_HEIGHT
thisObject.container.isDraggeable = false
thisObject.container.isClickeable = false
thisObject.container.isWheelable = true
let mouse = {
position: {
x: 0,
y: 0
}
}
let visible = false
let timeLineCoordinateSystem
return thisObject
function initialize (pTimeLineCoordinateSystem) {
timeLineCoordinateSystem = pTimeLineCoordinateSystem
thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel)
thisObject.heightPercentage = window.localStorage.getItem(MODULE_NAME)
if (!thisObject.heightPercentage) {
thisObject.heightPercentage = HEIGHT_PERCENTAGE_DEFAULT_VALUE
} else {
thisObject.heightPercentage = JSON.parse(thisObject.heightPercentage)
}
let event = {}
event.heightPercentage = thisObject.heightPercentage
thisObject.container.eventHandler.raiseEvent('Height Percentage Changed', event)
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
mouse.position.x = event.x
mouse.position.y = event.y
visible = true
})
thisObject.container.eventHandler.listenToEvent('onMouseNotOver', function (event) {
visible = false
})
}
function onMouseWheel (event) {
delta = event.wheelDelta
if (delta < 0) {
thisObject.heightPercentage = thisObject.heightPercentage - STEP_SIZE
if (thisObject.heightPercentage < STEP_SIZE) { thisObject.heightPercentage = STEP_SIZE }
} else {
thisObject.heightPercentage = thisObject.heightPercentage + STEP_SIZE
if (thisObject.heightPercentage > 100) { thisObject.heightPercentage = 100 }
}
event.heightPercentage = thisObject.heightPercentage
thisObject.container.eventHandler.raiseEvent('Height Percentage Changed', event)
window.localStorage.setItem(MODULE_NAME, thisObject.heightPercentage)
}
function getContainer (pPoint) {
let container
/* In this case we manually frame this point since we do a very special treatment of the position of this scale. */
let point = {
x: 0,
y: 0
}
point.x = pPoint.x - thisObject.container.frame.position.x - viewPort.margins.RIGHT
point.y = pPoint.y - thisObject.container.frame.position.y
if (thisObject.container.frame.isThisPointHere(point, undefined, true) === true) {
return thisObject.container
} else {
/* This point does not belong to this space. */
return undefined
}
}
function draw () {
if (visible === false) { return }
/* We need this scale to match the shape of its parent when the parent is inside the viewPort, when it is not, we need the scale still
to be visible at the top of the viewPort. */
let frame = thisObject.container.parentContainer.frame
let point1
let point2
let point3
let point4
point1 = {
x: frame.width - frame.width / 10,
y: 0
}
point2 = {
x: frame.width,
y: 0
}
point3 = {
x: frame.width,
y: frame.height
}
point4 = {
x: frame.width - frame.width / 10,
y: frame.height
}
point5 = {
x: 0,
y: 0
}
/* Now the transformations. */
point1 = transformThisPoint(point1, frame.container)
point2 = transformThisPoint(point2, frame.container)
point3 = transformThisPoint(point3, frame.container)
point4 = transformThisPoint(point4, frame.container)
point5 = transformThisPoint(point5, frame.container)
point1 = viewPort.fitIntoVisibleArea(point1)
point2 = viewPort.fitIntoVisibleArea(point2)
point3 = viewPort.fitIntoVisibleArea(point3)
point4 = viewPort.fitIntoVisibleArea(point4)
point5 = viewPort.fitIntoVisibleArea(point5)
if (point2.x - point1.x < MIN_WIDTH) {
point1.x = point2.x - MIN_WIDTH
point4.x = point2.x - MIN_WIDTH
}
/* Lets start the drawing. */
/*
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x + viewPort.margins.RIGHT, point2.y)
browserCanvasContext.lineTo(point3.x + viewPort.margins.RIGHT, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
browserCanvasContext.lineTo(point1.x, point1.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)'
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
*/
thisObject.container.frame.position.x = point1.x
thisObject.container.frame.position.y = point1.y
thisObject.container.frame.width = point2.x - point1.x
thisObject.container.frame.height = point3.y - point2.y
let point = {
x: point5.x + viewPort.margins.RIGHT,
y: mouse.position.y
}
let rate = getRateFromPoint(point, thisObject.container.parentContainer, timeLineCoordinateSystem)
let label = rate.toFixed(2)
let fontSize = 10
let xOffset = label.length * fontSize * FONT_ASPECT_RATIO
if (point.y + fontSize / 2 > point3.y || point.y - fontSize / 2 < point1.y) { return }
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.50)'
browserCanvasContext.fillText(label, point1.x + viewPort.margins.RIGHT, point.y + fontSize / 2)
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point.x, point.y)
browserCanvasContext.lineTo(point1.x + viewPort.margins.RIGHT, point.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.5)'
browserCanvasContext.lineWidth = 0.2
browserCanvasContext.setLineDash([1, 5])
browserCanvasContext.stroke()
}
}
-144
View File
@@ -1,144 +0,0 @@
function newRigthScale () {
const MODULE_NAME = 'Right Scale'
const INFO_LOG = false
const INTENSIVE_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize,
heightPercentage: 100
}
const HEIGHT_PERCENTAGE_DEFAULT_VALUE = 50
const RIGHT_MARGIN = 50
const STEP_SIZE = 5
thisObject.container = newContainer()
thisObject.container.initialize(MODULE_NAME)
thisObject.container.frame.width = RIGHT_MARGIN
thisObject.container.frame.height = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y
thisObject.container.frame.position.x = viewPort.visibleArea.bottomRight.x
thisObject.container.frame.position.y = TOP_SPACE_HEIGHT
thisObject.container.isDraggeable = false
thisObject.container.isClickeable = false
thisObject.container.isWheelable = true
let mouse = {
position: {
x: 0,
y: 0
}
}
return thisObject
function initialize () {
thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel)
thisObject.heightPercentage = window.localStorage.getItem(MODULE_NAME)
if (!thisObject.heightPercentage) {
thisObject.heightPercentage = HEIGHT_PERCENTAGE_DEFAULT_VALUE
} else {
thisObject.heightPercentage = JSON.parse(thisObject.heightPercentage)
}
let event = {}
event.heightPercentage = thisObject.heightPercentage
thisObject.container.eventHandler.raiseEvent('Height Percentage Changed', event)
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
mouse.position.x = event.x
mouse.position.y = event.y
})
}
function onMouseWheel (event) {
delta = event.wheelDelta
if (delta < 0) {
thisObject.heightPercentage = thisObject.heightPercentage - STEP_SIZE
if (thisObject.heightPercentage < STEP_SIZE) { thisObject.heightPercentage = STEP_SIZE }
} else {
thisObject.heightPercentage = thisObject.heightPercentage + STEP_SIZE
if (thisObject.heightPercentage > 100) { thisObject.heightPercentage = 100 }
}
event.heightPercentage = thisObject.heightPercentage
thisObject.container.eventHandler.raiseEvent('Height Percentage Changed', event)
window.localStorage.setItem(MODULE_NAME, thisObject.heightPercentage)
}
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 thisObject.container
} else {
/* This point does not belong to this space. */
return undefined
}
}
function draw () {
drawBackground()
drawLabel()
}
function drawBackground () {
const RIGHT_MARGIN = 50
/* We will paint some transparent background here. */
let opacity = '0.95'
browserCanvasContext.beginPath()
browserCanvasContext.rect(viewPort.visibleArea.topRight.x, viewPort.visibleArea.topRight.y, RIGHT_MARGIN, viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'
browserCanvasContext.closePath()
browserCanvasContext.fill()
}
function drawLabel () {
let label = '6000'
let fontSize = 10
let ratePoint = {
x: 0,
y: mouse.position.y
}
// getRateFromPoint(ratePoint)
let labelPoint = {
x: viewPort.visibleArea.topRight.x + 5,
y: mouse.position.y - fontSize / 2 + 1
}
let xOffset = 0// label.length / 2 * fontSize * FONT_ASPECT_RATIO
browserCanvasContext.beginPath()
browserCanvasContext.rect(labelPoint.x, labelPoint.y, xOffset * 2, fontSize)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.RUSTED_RED + ', 1)'
browserCanvasContext.fill()
browserCanvasContext.closePath()
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)'
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y)
}
}
+267
View File
@@ -0,0 +1,267 @@
function newTimePeriodScale () {
const MODULE_NAME = 'Time Period Scale'
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize,
timePeriod: undefined
}
const FILES_PERIOD_DEFAULT_VALUE = 0
const TIME_PERIOD_DEFAULT_VALUE = 0
const MIN_HEIGHT = 50
thisObject.container = newContainer()
thisObject.container.initialize(MODULE_NAME)
thisObject.container.isDraggeable = false
thisObject.container.isClickeable = false
thisObject.container.isWheelable = true
let mouse = {
position: {
x: 0,
y: 0
}
}
let visible = false
let timeLineCoordinateSystem
let objectStorage = {}
let filePeriodIndex = FILES_PERIOD_DEFAULT_VALUE
let timePeriodIndex = TIME_PERIOD_DEFAULT_VALUE
let timePeriodsMasterArray = [marketFilesPeriods, dailyFilePeriods]
let timePeriodLabel = ''
return thisObject
function initialize (pTimeLineCoordinateSystem) {
timeLineCoordinateSystem = pTimeLineCoordinateSystem
thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel)
readObjectState()
newTimePeriod()
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
mouse.position.x = event.x
mouse.position.y = event.y
visible = true
})
thisObject.container.eventHandler.listenToEvent('onMouseNotOver', function (event) {
visible = false
})
viewPort.eventHandler.listenToEvent('Zoom Changed', onZoomChanged)
}
function onZoomChanged (event) {
let currentTimePeriod = thisObject.timePeriod
let timePeriod = recalculatePeriod(event.newLevel)
if (timePeriod !== currentTimePeriod) {
for (let i = 0; i < timePeriodsMasterArray.length; i++) {
let timePeriodArray = timePeriodsMasterArray[i]
for (let j = 0; j < timePeriodArray.length; j++) {
let record = timePeriodArray[j]
if (timePeriod === record[0]) {
filePeriodIndex = i
timePeriodIndex = j
}
}
}
saveObjectState()
newTimePeriod()
}
}
function onMouseWheel (event) {
delta = event.wheelDelta
if (delta < 0) {
timePeriodIndex--
if (timePeriodIndex < 0) {
filePeriodIndex--
if (filePeriodIndex < 0) {
filePeriodIndex = 0
timePeriodIndex = 0
} else {
timePeriodIndex = timePeriodsMasterArray[filePeriodIndex].length - 1
}
}
} else {
timePeriodIndex++
if (timePeriodIndex > timePeriodsMasterArray[filePeriodIndex].length - 1) {
filePeriodIndex++
if (filePeriodIndex > timePeriodsMasterArray.length - 1) {
filePeriodIndex = timePeriodsMasterArray.length - 1
timePeriodIndex = timePeriodsMasterArray[filePeriodIndex].length - 1
} else {
timePeriodIndex = 0
}
}
}
saveObjectState()
newTimePeriod()
}
function getContainer (pPoint) {
let container
/* In this case we manually frame this point since we do a very special treatment of the position of this scale. */
let point = {
x: 0,
y: 0
}
point.x = pPoint.x - thisObject.container.frame.position.x
point.y = pPoint.y - thisObject.container.frame.position.y
if (thisObject.container.frame.isThisPointHere(point, undefined, true) === true) {
return thisObject.container
} else {
/* This point does not belong to this space. */
return undefined
}
}
function draw () {
if (visible === false) { return }
/* We need this scale to match the shape of its parent when the parent is inside the viewPort, when it is not, we need the scale still
to be visible at the top of the viewPort. */
let frame = thisObject.container.parentContainer.frame
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: frame.height - frame.height / 10
}
point2 = {
x: frame.width,
y: frame.height - frame.height / 10
}
point3 = {
x: frame.width,
y: frame.height
}
point4 = {
x: 0,
y: frame.height
}
point5 = {
x: 0,
y: 0
}
/* Now the transformations. */
point1 = transformThisPoint(point1, frame.container)
point2 = transformThisPoint(point2, frame.container)
point3 = transformThisPoint(point3, frame.container)
point4 = transformThisPoint(point4, frame.container)
point5 = transformThisPoint(point5, frame.container)
point1 = viewPort.fitIntoVisibleArea(point1)
point2 = viewPort.fitIntoVisibleArea(point2)
point3 = viewPort.fitIntoVisibleArea(point3)
point4 = viewPort.fitIntoVisibleArea(point4)
point5 = viewPort.fitIntoVisibleArea(point5)
if (point3.y - point2.y < MIN_HEIGHT) {
point1.y = point3.y - MIN_HEIGHT
point2.y = point3.y - MIN_HEIGHT
}
/* Lets start the drawing. */
let displacement = viewPort.margins.BOTTOM - BOTTOM_SPACE_HEIGHT
/*
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y + displacement)
browserCanvasContext.lineTo(point2.x, point2.y + displacement)
browserCanvasContext.lineTo(point3.x, point3.y + displacement)
browserCanvasContext.lineTo(point4.x, point4.y + displacement)
browserCanvasContext.lineTo(point1.x, point1.y + displacement)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)'
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
*/
thisObject.container.frame.position.x = point1.x
thisObject.container.frame.position.y = point1.y + displacement
thisObject.container.frame.width = point2.x - point1.x
thisObject.container.frame.height = point3.y - point2.y
let point = {
x: mouse.position.x,
y: point1.y + viewPort.margins.BOTTOM
}
let label = timePeriodLabel
let fontSize = 10
let xOffset = label.length * fontSize * FONT_ASPECT_RATIO
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.50)'
if (point.x - xOffset / 2 < point1.x || point.x + xOffset / 2 > point2.x) { return }
browserCanvasContext.fillText(label, point.x - xOffset / 2, point.y + fontSize + 1)
/*
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point.x, point1.y)
browserCanvasContext.lineTo(point.x, point5.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.5)'
browserCanvasContext.lineWidth = 0.2
browserCanvasContext.setLineDash([1, 5])
browserCanvasContext.stroke()
*/
}
function saveObjectState () {
objectStorage.filePeriodIndex = filePeriodIndex
objectStorage.timePeriodIndex = timePeriodIndex
window.localStorage.setItem(MODULE_NAME, JSON.stringify(objectStorage))
}
function readObjectState () {
let objectStorageString = window.localStorage.getItem(MODULE_NAME)
if (objectStorageString !== null && objectStorageString !== '') {
objectStorage = JSON.parse(objectStorageString)
filePeriodIndex = objectStorage.filePeriodIndex
timePeriodIndex = objectStorage.timePeriodIndex
}
}
function newTimePeriod () {
let timePeriodArray = timePeriodsMasterArray[filePeriodIndex]
thisObject.timePeriod = timePeriodArray[timePeriodIndex][0]
timePeriodLabel = timePeriodArray[timePeriodIndex][1]
let event = {}
event.timePeriod = thisObject.timePeriod
thisObject.container.eventHandler.raiseEvent('Time Period Changed', event)
}
}
+140 -16
View File
@@ -1,10 +1,5 @@
function newTimeScale () {
const MODULE_NAME = 'Time Scale'
const INFO_LOG = false
const INTENSIVE_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
let thisObject = {
container: undefined,
@@ -14,26 +9,32 @@ function newTimeScale () {
lenghtPercentage: undefined
}
const LENGHT_PERCENTAGE_DEFAULT_VALUE = 50
const RIGHT_MARGIN = 50
const LENGHT_PERCENTAGE_DEFAULT_VALUE = 5
const STEP_SIZE = 5
const MIN_HEIGHT = 50
thisObject.container = newContainer()
thisObject.container.initialize(MODULE_NAME)
thisObject.container.frame.width = viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x
thisObject.container.frame.height = 100
thisObject.container.frame.position.x = viewPort.visibleArea.bottomRight.x
thisObject.container.frame.position.y = TOP_SPACE_HEIGHT
thisObject.container.isDraggeable = false
thisObject.container.isClickeable = false
thisObject.container.isWheelable = true
let mouse = {
position: {
x: 0,
y: 0
}
}
let visible = false
let timeLineCoordinateSystem
return thisObject
function initialize () {
function initialize (pTimeLineCoordinateSystem) {
timeLineCoordinateSystem = pTimeLineCoordinateSystem
thisObject.container.eventHandler.listenToEvent('Mouse Wheel', onMouseWheel)
thisObject.lenghtPercentage = window.localStorage.getItem(MODULE_NAME)
@@ -46,6 +47,17 @@ function newTimeScale () {
let event = {}
event.lenghtPercentage = thisObject.lenghtPercentage
thisObject.container.eventHandler.raiseEvent('Lenght Percentage Changed', event)
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
mouse.position.x = event.x
mouse.position.y = event.y
visible = true
})
thisObject.container.eventHandler.listenToEvent('onMouseNotOver', function (event) {
visible = false
})
}
function onMouseWheel (event) {
@@ -64,10 +76,16 @@ function newTimeScale () {
window.localStorage.setItem(MODULE_NAME, thisObject.lenghtPercentage)
}
function getContainer (point) {
function getContainer (pPoint) {
let container
/* First we check if this point is inside this object UI. */
/* In this case we manually frame this point since we do a very special treatment of the position of this scale. */
let point = {
x: 0,
y: 0
}
point.x = pPoint.x - thisObject.container.frame.position.x
point.y = pPoint.y - thisObject.container.frame.position.y + viewPort.margins.TOP
if (thisObject.container.frame.isThisPointHere(point, undefined, true) === true) {
return thisObject.container
@@ -79,6 +97,112 @@ function newTimeScale () {
}
function draw () {
if (visible === false) { return }
/* We need this scale to match the shape of its parent when the parent is inside the viewPort, when it is not, we need the scale still
to be visible at the top of the viewPort. */
let frame = thisObject.container.parentContainer.frame
let point1
let point2
let point3
let point4
point1 = {
x: 0,
y: 0
}
point2 = {
x: frame.width,
y: 0
}
point3 = {
x: frame.width,
y: frame.height / 10
}
point4 = {
x: 0,
y: frame.height / 10
}
point5 = {
x: 0,
y: frame.height
}
/* Now the transformations. */
point1 = transformThisPoint(point1, frame.container)
point2 = transformThisPoint(point2, frame.container)
point3 = transformThisPoint(point3, frame.container)
point4 = transformThisPoint(point4, frame.container)
point5 = transformThisPoint(point5, frame.container)
point1 = viewPort.fitIntoVisibleArea(point1)
point2 = viewPort.fitIntoVisibleArea(point2)
point3 = viewPort.fitIntoVisibleArea(point3)
point4 = viewPort.fitIntoVisibleArea(point4)
point5 = viewPort.fitIntoVisibleArea(point5)
if (point3.y - point2.y < MIN_HEIGHT) {
point3.y = point2.y + MIN_HEIGHT
point4.y = point2.y + MIN_HEIGHT
}
/* Lets start the drawing. */
/*
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y - viewPort.margins.TOP)
browserCanvasContext.lineTo(point2.x, point2.y - viewPort.margins.TOP)
browserCanvasContext.lineTo(point3.x, point3.y - viewPort.margins.TOP)
browserCanvasContext.lineTo(point4.x, point4.y - viewPort.margins.TOP)
browserCanvasContext.lineTo(point1.x, point1.y - viewPort.margins.TOP)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)'
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
*/
thisObject.container.frame.position.x = point1.x
thisObject.container.frame.position.y = point1.y
thisObject.container.frame.width = point2.x - point1.x
thisObject.container.frame.height = point3.y - point2.y
let point = {
x: mouse.position.x,
y: point1.y - viewPort.margins.TOP
}
let date = getDateFromPoint(point, thisObject.container.parentContainer, timeLineCoordinateSystem)
date = new Date(date)
let label = date.toUTCString()
let fontSize = 10
let xOffset = label.length * fontSize * FONT_ASPECT_RATIO
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.PRIMARY
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', 0.50)'
if (point.x - xOffset / 2 < point1.x || point.x + xOffset / 2 > point2.x) { return }
browserCanvasContext.fillText(label, point.x - xOffset / 2, point.y + fontSize + 7)
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point.x, point1.y)
browserCanvasContext.lineTo(point.x, point5.y)
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', 0.5)'
browserCanvasContext.lineWidth = 0.2
browserCanvasContext.setLineDash([1, 5])
browserCanvasContext.stroke()
}
}
+86 -9
View File
@@ -1,10 +1,13 @@

function newBottomSpace () {
var thisObject = {
deleteTradingHistory: undefined,
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
createNewControl: createNewControl,
destroyControl: destroyControl,
getControl: getControl,
initialize: initialize
}
@@ -14,17 +17,79 @@ function newBottomSpace () {
container.isDraggeable = false
controlsMap = new Map()
resize()
return thisObject
function initialize () {
thisObject.deleteTradingHistory = newDeleteTradingHistory()
thisObject.deleteTradingHistory.initialize()
window.canvasApp.eventHandler.listenToEvent('Browser Resized', resize)
}
function createNewControl (pType, pDrawFunction, pOwner) {
let control
switch (pType) {
case 'Over The Line':
{
control = newUIControl()
control.initialize()
control.drawFunction = pDrawFunction
break
}
}
let controlArray = controlsMap.get(pOwner)
if (controlArray === undefined) {
controlArray = []
controlsMap.set(pOwner, controlArray)
}
controlArray.push(control)
control.handle = Math.floor((Math.random() * 10000000) + 1)
return control.handle
}
function destroyControl (pControlHandle) {
thisObject.controls = controlsMap.get('Global')
if (thisObject.controls !== undefined) {
for (let i = 0; i < thisObject.controls.length; i++) {
let control = thisObject.controls[i]
if (control.handle === pControlHandle) {
thisObject.controls.splice(i, 1) // Delete item from array.
return
}
}
}
thisObject.controls = controlsMap.get(window.CHART_ON_FOCUS)
if (thisObject.controls !== undefined) {
for (let i = 0; i < thisObject.controls.length; i++) {
let control = thisObject.controls[i]
if (control.handle === pControlHandle) {
thisObject.controls.splice(i, 1) // Delete item from array.
return
}
}
}
}
function getControl (pControlHandle, pOwner) {
thisObject.controls = controlsMap.get(pOwner)
if (thisObject.controls != undefined) {
for (let i = 0; i < thisObject.controls.length; i++) {
let control = thisObject.controls[i]
if (control.handle === pControlHandle) {
return control
}
}
}
}
function resize () {
container.frame.position.x = 0
container.frame.position.y = viewPort.visibleArea.bottomLeft.y
@@ -36,9 +101,6 @@ function newBottomSpace () {
function getContainer (point) {
let container
container = thisObject.deleteTradingHistory.getContainer(point)
if (container !== undefined) { return container }
return thisObject.container
}
@@ -46,7 +108,22 @@ function newBottomSpace () {
thisObject.container.frame.draw(false, false)
drawBackground()
thisObject.deleteTradingHistory.draw()
thisObject.controls = controlsMap.get('Global')
if (thisObject.controls !== undefined) {
for (let i = 0; i < thisObject.controls.length; i++) {
let control = thisObject.controls[i]
control.draw()
}
}
thisObject.controls = controlsMap.get(window.CHART_ON_FOCUS)
if (thisObject.controls !== undefined) {
for (let i = 0; i < thisObject.controls.length; i++) {
let control = thisObject.controls[i]
control.draw()
}
}
}
function drawBackground () {
+1 -1
View File
@@ -13,7 +13,7 @@ function newChartSpace () {
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
var thisObject = {
let thisObject = {
container: undefined,
drawBackground: drawBackground,
draw: draw,
+9 -7
View File
@@ -5,7 +5,7 @@ The Panel Space y the place wehre all panels live, no matter who create them.
*/
function newPanelsSpace () {
var thisObject = {
let thisObject = {
container: undefined,
createNewPanel: createNewPanel,
destroyPanel: destroyPanel,
@@ -16,7 +16,7 @@ function newPanelsSpace () {
initialize: initialize
}
var container = newContainer()
let container = newContainer()
container.initialize()
thisObject.container = container
thisObject.container.isDraggeable = false
@@ -76,6 +76,10 @@ function newPanelsSpace () {
let panel = thisObject.panels[i]
if (panel.handle === pPanelHandle) {
if (panel.finalize !== undefined) {
panel.finalize()
}
thisObject.panels.splice(i, 1) // Delete item from array.
return
}
@@ -98,11 +102,9 @@ function newPanelsSpace () {
function draw () {
thisObject.container.frame.draw(false, false)
/* When we draw a time machine, that means also to draw all the charts in it. */
thisObject.panels = panelsMap.get('Global')
if (thisObject.panels != undefined) {
for (var i = 0; i < thisObject.panels.length; i++) {
if (thisObject.panels !== undefined) {
for (let i = 0; i < thisObject.panels.length; i++) {
let panel = thisObject.panels[i]
panel.draw()
}
@@ -110,7 +112,7 @@ function newPanelsSpace () {
thisObject.panels = panelsMap.get(window.CHART_ON_FOCUS)
if (thisObject.panels !== undefined) {
for (var i = 0; i < thisObject.panels.length; i++) {
for (let i = 0; i < thisObject.panels.length; i++) {
let panel = thisObject.panels[i]
panel.draw()
}
+45
View File
@@ -0,0 +1,45 @@
function newStrategySpace () {
const MODULE_NAME = 'Strategy Space'
let thisObject = {
sidePanel: undefined,
strategyCollection: undefined,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
let container = newContainer()
container.initialize()
thisObject.container = container
container.isDraggeable = false
return thisObject
async function initialize () {
thisObject.sidePanel = newSidePanel()
thisObject.sidePanel.initialize()
thisObject.strategyCollection = newStrategyCollection()
thisObject.strategyCollection.container.connectToParent(thisObject.sidePanel.container, true, true)
await thisObject.strategyCollection.initialize()
thisObject.sidePanel.areas.push(thisObject.strategyCollection)
}
function getContainer (point) {
let container
if (thisObject.sidePanel !== undefined) {
container = thisObject.sidePanel.getContainer(point)
if (container !== undefined) { return container }
}
return
}
function draw () {
thisObject.sidePanel.draw()
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
function newTopSpace () {
var thisObject = {
let thisObject = {
container: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
+1 -1
View File
@@ -5,7 +5,7 @@ The Splash Screen is to show some 'loading...' controls while the app is being l
*/
function newSplashScreen () {
var thisObject = {
let thisObject = {
container: undefined,
draw: draw,
timeMachines: [],
+264
View File
@@ -0,0 +1,264 @@
function newStrategyCollection () {
const MODULE_NAME = 'Strategy Collection'
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
let thisObject = {
strategies: undefined,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
let colletionItems = []
thisObject.container = newContainer()
thisObject.container.name = MODULE_NAME
thisObject.container.initialize()
thisObject.container.frame.width = 0
thisObject.container.frame.height = 0
thisObject.container.frame.position.x = 0
thisObject.container.frame.position.y = 0
thisObject.container.isDraggeable = false
thisObject.container.isClickeable = true
return thisObject
async function initialize () {
try {
const accessToken = window.localStorage.getItem('xaccess_token')
let user = window.localStorage.getItem('xuser')
if (user === null) {
// if there is no user that means that we are logged off, which means this object can not be used.
return
}
thisObject.container.eventHandler.listenToEvent('onMouseClick', onClick)
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
})
/* Getting the FB that own the Strategies */
let strategySimulationClone = ''
let clones = window.localStorage.getItem('userClones')
if (clones === null || clones === '') {
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> no user clones found at local storage. Can not get Strategies without them. ') }
return
}
clones = JSON.parse(clones)
for (let i = 0; i < clones.length; i++) {
let clone = clones[i]
if (clone.botType === 'Indicator') {
strategySimulationClone = clone.botSlug
}
}
/* Getting all Strategies */
const networkInterface = Apollo.lib.createNetworkInterface({
uri: window.canvasApp.graphQL.masterAppApiUrl
})
networkInterface.use([{
applyMiddleware (req, next) {
req.options.headers = {
authorization: `Bearer ${accessToken}`
}
next()
}
}])
const QUERY = Apollo.gql`
query($fbSlug: String!){
strategizer_StrategyByFb(fbSlug: $fbSlug){
subStrategies(activeOnly: true){
name
entryPoint{
situations{
name
conditions{
name
code
}
}
}
exitPoint{
situations{
name
conditions{
name
code
}
}
}
sellPoint{
situations{
name
conditions{
name
code
}
}
}
buyPoint{
situations{
name
conditions{
name
code
}
}
}
stopLoss{
phases{
name
code
situations{
name
conditions{
name
code
}
}
}
}
buyOrder{
phases{
name
code
situations{
name
conditions{
name
code
}
}
}
}
sellOrder{
phases{
name
code
situations{
name
conditions{
name
code
}
}
}
}
}
}
}
`
const getStrategies = () => {
return new Promise((resolve, reject) => {
apolloClient.query({
query: QUERY,
variables: { fbSlug: strategySimulationClone}
})
.then(response => {
window.localStorage.setItem('userStrategies', JSON.stringify(response.data.strategizer_StrategyByFb.subStrategies))
thisObject.strategies = response.data.strategizer_StrategyByFb.subStrategies
createCollectionItems()
resolve({ strategies: response.data.strategizer_StrategyByFb.subStrategies})
})
.catch(error => {
console.log('apolloClient error getting user strategies', error.graphQLErrors, error.stack)
reject(error)
})
})
}
// To avoid race conditions, add asynchronous fetches to array
let fetchDataPromises = []
fetchDataPromises.push(getStrategies())
// 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.stack)
})
} catch (err) {
if (ERROR_LOG === true) { logger.write('[ERROR] initialize -> err = ' + err.stack) }
}
}
function createCollectionItems () {
const TOP_MARGIN = 100
const ITEMS_SEPARATION = 90
for (let i = 0; i < thisObject.strategies.length; i++) {
let strategy = thisObject.strategies[i]
let collectionItem = newStrategyCollectionItem()
collectionItem.container.connectToParent(thisObject.container, false, false)
collectionItem.initialize()
collectionItem.strategy = strategy
collectionItem.container.frame.position.y = i * ITEMS_SEPARATION + TOP_MARGIN
colletionItems.push(collectionItem)
/* Load Strategies Icons */
let imageIndex = i + 1
if (imageIndex > 14) { imageIndex = 14 }
let strategyImage = loadEmoji('Symbols/Emoji Symbols-' + (112 + imageIndex) + '.png')
collectionItem.icon = strategyImage
}
}
function onClick () {
}
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 () {
if (colletionItems === undefined) {
return
}
for (let i = 0; i < colletionItems.length; i++) {
let item = colletionItems[i]
item.draw()
}
}
}
+164
View File
@@ -0,0 +1,164 @@
function newStrategyCollectionItem () {
const MODULE_NAME = 'Strategy Collection Item'
let thisObject = {
icon: undefined,
strategy: undefined,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
}
let isInitialized = false
thisObject.container = newContainer()
thisObject.container.name = MODULE_NAME
thisObject.container.initialize()
thisObject.container.isClickeable = true
thisObject.container.isDraggeable = false
return thisObject
function initialize () {
const ITEM_WIDTH = 430
const ITEM_HEIGHT = 80
thisObject.container.frame.width = ITEM_WIDTH
thisObject.container.frame.height = ITEM_HEIGHT
const LEFT_MARGIN = (thisObject.container.parentContainer.frame.width - thisObject.container.frame.width) / 2
const TOP_MARGIN = 100
thisObject.container.frame.position.x = LEFT_MARGIN
thisObject.container.frame.position.y = TOP_MARGIN
thisObject.container.eventHandler.listenToEvent('onMouseClick', onMouseClick)
isInitialized = true
}
function onMouseClick (event) {
}
function getContainer (point) {
let container
if (thisObject.container.frame.isThispointHere(point, true) === true) {
return thisObject.container
} else {
return undefined
}
}
function draw () {
if (isInitialized === false) { return }
borders()
text()
arrow()
icon()
}
function text () {
if (thisObject.strategy === undefined) {
return
}
const LEFT_MARGIN = 80
const TOP_MARGIN = 45
let strategy = thisObject.strategy
let labelpoint = {
x: LEFT_MARGIN,
y: TOP_MARGIN
}
labelpoint = thisObject.container.frame.frameThisPoint(labelpoint)
let labelToPrint = strategy.name
labelToPrint = labelToPrint.toUpperCase()
labelToPrint = labelToPrint.substring(0, 30)
let opacity = 1
let fontSize = 15
printLabel(labelToPrint, labelpoint.x, labelpoint.y, opacity, fontSize)
}
function borders () {
let params = {
cornerRadious: 8,
lineWidth: 0.1,
opacity: 1,
container: thisObject.container,
borderColor: UI_COLOR.DARK,
backgroundColor: UI_COLOR.WHITE,
castShadow: true
}
roundedCornersBackground(params)
}
function arrow () {
const X_OFFSET = 400
const Y_OFFSET = 40
const HEIGHT = 12
const WIDTH = 6
const LINE_WIDTH = 2
const OPACITY = 0.6
point1 = {
x: X_OFFSET,
y: Y_OFFSET - HEIGHT / 2
}
point2 = {
x: X_OFFSET + WIDTH,
y: Y_OFFSET
}
point3 = {
x: X_OFFSET,
y: Y_OFFSET + HEIGHT / 2
}
/* Now the transformations. */
point1 = thisObject.container.frame.frameThisPoint(point1)
point2 = thisObject.container.frame.frameThisPoint(point2)
point3 = thisObject.container.frame.frameThisPoint(point3)
browserCanvasContext.setLineDash([0, 0])
/* The Arrow */
browserCanvasContext.beginPath()
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
browserCanvasContext.lineTo(point3.x, point3.y)
browserCanvasContext.lineWidth = LINE_WIDTH
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.DARK + ', ' + OPACITY + ')'
browserCanvasContext.stroke()
}
function icon () {
if (thisObject.icon === undefined) { return }
const X_OFFSET = 45
const Y_OFFSET = 40
const IMAGE_SIZE = 40
point1 = {
x: X_OFFSET,
y: Y_OFFSET
}
/* Now the transformations. */
point1 = thisObject.container.frame.frameThisPoint(point1)
browserCanvasContext.drawImage(thisObject.icon, point1.x - IMAGE_SIZE / 2, point1.y - IMAGE_SIZE / 2, IMAGE_SIZE, IMAGE_SIZE)
}
}
+1 -1
View File
@@ -8,7 +8,7 @@ The scale on the Y axis depends on the data that wants to be plotted. Usually we
*/
function newTimeLineCoordinateSystem () {
var thisObject = {
let thisObject = {
min: undefined,
max: undefined,
scale: undefined,
+55 -16
View File
@@ -43,6 +43,8 @@ function newTimeMachine () {
let timeScale
let rigthScale
let timeLineCoordinateSystem = newTimeLineCoordinateSystem()
return thisObject
function finalize () {
@@ -67,6 +69,13 @@ function newTimeMachine () {
controlPanelHandle = canvas.panelsSpace.createNewPanel('Time Control Panel', undefined, panelOwner)
let controlPanel = canvas.panelsSpace.getPanel(controlPanelHandle, panelOwner)
recalculateScale()
thisObject.container.eventHandler.listenToEvent('Dimmensions Changed', function (event) {
recalculateScale()
moveToUserPosition(thisObject.container, timeLineCoordinateSystem, false, false, event.mousePosition)
})
/* First, we initialize the market that we are going to show first on screen. Later all the other markets will be initialized on the background. */
let position = 0 // This defines the position of each chart respect to each other.
@@ -74,7 +83,6 @@ function newTimeMachine () {
let timelineChart = newTimelineChart()
timelineChart.container.connectToParent(thisObject.container, true, true)
timelineChart.container.frame.height = thisObject.container.frame.height
timelineChart.container.frame.position.x = thisObject.container.frame.width / 2 - timelineChart.container.frame.width / 2
@@ -82,7 +90,7 @@ function newTimeMachine () {
position++
timelineChart.initialize(DEFAULT_EXCHANGE, DEFAULT_MARKET, onDefaultInitialized)
timelineChart.initialize(DEFAULT_EXCHANGE, DEFAULT_MARKET, timeLineCoordinateSystem, onDefaultInitialized)
function onDefaultInitialized (err) {
if (err.result !== GLOBAL.DEFAULT_OK_RESPONSE.result) {
@@ -98,22 +106,22 @@ function newTimeMachine () {
/* Each Time Machine has a Time Scale and a Right Scale. */
timeScale = newTimeScale()
timeScale.container.connectToParent(thisObject.container, false, false)
timeScale.container.eventHandler.listenToEvent('Lenght Percentage Changed', function (event) {
thisObject.container.frame.width = TIME_MACHINE_WIDTH * event.lenghtPercentage / 100
thisObject.container.eventHandler.raiseEvent('Dimmensions Changed', event)
})
timeScale.initialize()
rigthScale = newRigthScale()
timeScale.initialize(timeLineCoordinateSystem)
rigthScale = newRateScale()
rigthScale.container.connectToParent(thisObject.container, false, false)
rigthScale.container.eventHandler.listenToEvent('Height Percentage Changed', function (event) {
thisObject.container.frame.height = TIME_MACHINE_HEIGHT * event.heightPercentage / 100
thisObject.container.eventHandler.raiseEvent('Dimmensions Changed', event)
})
rigthScale.initialize()
rigthScale.initialize(timeLineCoordinateSystem)
initializeTheRest()
}
@@ -158,7 +166,7 @@ function newTimeMachine () {
position++
timelineChart.initialize(exchange, market, finalSteps)
timelineChart.initialize(exchange, market, timeLineCoordinateSystem, finalSteps)
function finalSteps () {
if (INFO_LOG === true) { logger.write('[INFO] initialize -> initializeTheRest -> initializeTimelineChart -> finalSteps -> Entering function.') }
@@ -186,15 +194,17 @@ function newTimeMachine () {
}
function draw () {
// this.container.frame.draw(false, false)
if (thisObject.container.frame.isInViewPort()) {
for (let i = 0; i < this.charts.length; i++) {
let chart = this.charts[i]
chart.draw()
}
for (let i = 0; i < this.charts.length; i++) {
let chart = this.charts[i]
chart.draw()
if (timeScale !== undefined) { timeScale.draw() }
if (rigthScale !== undefined) { rigthScale.draw() }
// thisObject.container.frame.draw(false, true, false)
}
if (timeScale !== undefined) { timeScale.draw() }
if (rigthScale !== undefined) { rigthScale.draw() }
}
function getContainer (point, purpose) {
@@ -226,6 +236,35 @@ function newTimeMachine () {
}
}
}
return this.container
if (thisObject.container.frame.isThisPointHere(point) === true) {
return thisObject.container
} else {
if (purpose === GET_CONTAINER_PURPOSE.MOUSE_OVER) {
thisObject.container.eventHandler.raiseEvent('onMouseNotOver')
}
return
}
}
function recalculateScale () {
if (INFO_LOG === true) { logger.write('[INFO] recalculateScale -> Entering function.') }
let minValue = {
x: MIN_PLOTABLE_DATE.valueOf(),
y: 0
}
let maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(USDT_BTC_HTH) / 4
}
timeLineCoordinateSystem.initialize(
minValue,
maxValue,
thisObject.container.frame.width,
thisObject.container.frame.height
)
}
}
+92 -72
View File
@@ -6,10 +6,10 @@
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
let timeLineCoordinateSystem = newTimeLineCoordinateSystem()
let timeLineCoordinateSystem
let timePeriod = INITIAL_TIME_PERIOD
let datetime = INITIAL_DATE
let datetime = NEW_SESSION_INITIAL_DATE
let thisObject = {
setDatetime: setDatetime,
@@ -25,9 +25,6 @@
thisObject.container.initialize(MODULE_NAME)
thisObject.container.detectMouseOver = true
// let chartGrid
let breakpointsBar
let initializationReady = false
let productsPanel
@@ -47,6 +44,7 @@
let market
let productsPanelHandle
let timePeriodScale
return thisObject
@@ -60,22 +58,18 @@
}
}
function initialize (pExchange, pMarket, callBackFunction) {
function initialize (pExchange, pMarket, pTimeLineCoordinateSystem, callBackFunction) {
try {
if (INFO_LOG === true) { logger.write('[INFO] initialize -> Entering function.') }
thisObject.container.eventHandler.listenToEvent('Dimmensions Changed', function (event) {
recalculateScale()
moveToUserPosition(thisObject.container, timeLineCoordinateSystem, false, false, event.mousePosition)
})
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
saveUserPosition(thisObject.container, timeLineCoordinateSystem, event)
})
/* We load the logow we will need for the background. */
exchange = pExchange
market = pMarket
timeLineCoordinateSystem = pTimeLineCoordinateSystem
thisObject.container.eventHandler.listenToEvent('onMouseOver', function (event) {
saveUserPosition(thisObject.container, timeLineCoordinateSystem, event)
})
let panelOwner = exchange + ' ' + market.assetB + '/' + market.assetA
productsPanelHandle = canvas.panelsSpace.createNewPanel('Products Panel', undefined, panelOwner)
@@ -116,17 +110,9 @@
logoExchange.src = window.canvasApp.urlPrefix + 'Images/' + exchange + '-logo-background.png'
logoAA.src = window.canvasApp.urlPrefix + 'Images/sa-logo-background.png'
// chartGrid = newChartGrid()
// chartGrid.initialize()
breakpointsBar = newBreakpointsBar()
breakpointsBar.initialize(thisObject.container, timeLineCoordinateSystem)
recalculateScale()
moveToUserPosition(thisObject.container, timeLineCoordinateSystem)
// moveToUserPosition(thisObject.container, timeLineCoordinateSystem, undefined, undefined, undefined, true)
timePeriod = INITIAL_TIME_PERIOD
datetime = INITIAL_DATE
datetime = NEW_SESSION_INITIAL_DATE
/* Event Subscriptions - we need this events to be fired first here and then in active Plotters. */
@@ -155,6 +141,18 @@
return
}
timePeriodScale = newTimePeriodScale()
timePeriodScale.container.connectToParent(thisObject.container, false, false)
timePeriodScale.container.eventHandler.listenToEvent('Time Period Changed', function (event) {
let currentTimePeriod = timePeriod
timePeriod = event.timePeriod
if (timePeriod !== currentTimePeriod) {
plotterManager.setTimePeriod(timePeriod)
}
})
timePeriodScale.initialize(timeLineCoordinateSystem)
initializationReady = true
callBackFunction(GLOBAL.DEFAULT_OK_RESPONSE)
return
@@ -169,16 +167,6 @@
if (INFO_LOG === true) { logger.write('[INFO] onZoomChanged -> Entering function.') }
if (initializationReady === true) {
let currentTimePeriod = timePeriod
timePeriod = recalculatePeriod(event.newLevel)
/* If the period changes, we need to spread the word in cascade towards all the depending objects. */
if (timePeriod !== currentTimePeriod) {
plotterManager.setTimePeriod(timePeriod)
}
recalculateCurrentDatetime()
// saveUserPosition(thisObject.container, timeLineCoordinateSystem)
@@ -194,7 +182,6 @@
if (thisObject.container.frame.isInViewPort()) {
plotterManager.setDatetime(pDatetime)
plotterManager.positionAtDatetime(pDatetime)
breakpointsBar.setDatetime(pDatetime)
}
}
@@ -234,8 +221,6 @@
plotterManager.setDatetime(datetime)
breakpointsBar.setDatetime(datetime)
thisObject.container.eventHandler.raiseEvent('Datetime Changed', datetime)
}
@@ -244,36 +229,13 @@
let container
// container = chartGrid.getContainer(point)
container = timePeriodScale.getContainer(point)
if (container !== undefined) { return container }
container = breakpointsBar.getContainer(point)
return container
}
function recalculateScale () {
if (INFO_LOG === true) { logger.write('[INFO] recalculateScale -> Entering function.') }
let minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
}
let maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(USDT_BTC_HTH) / 4
}
timeLineCoordinateSystem.initialize(
minValue,
maxValue,
thisObject.container.frame.width,
thisObject.container.frame.height
)
}
function tooTiny () {
if (INTENSIVE_LOG === true) { logger.write('[INFO] tooTiny -> Entering function.') }
@@ -301,8 +263,6 @@
if (window.CHART_ON_FOCUS === '') {
window.CHART_ON_FOCUS = exchange + ' ' + market.assetB + '/' + market.assetA
this.container.frame.draw()
drawChartsBackgroundImages()
}
}
@@ -316,9 +276,8 @@
// chartGrid.draw(thisObject.container, timeLineCoordinateSystem)
timePeriodScale.draw()
plotterManager.draw()
breakpointsBar.draw()
}
}
@@ -333,7 +292,7 @@
}
let toPoint = {
x: 0,
x: thisObject.container.frame.width,
y: thisObject.container.frame.height
}
@@ -342,7 +301,7 @@
browserCanvasContext.beginPath()
browserCanvasContext.rect(viewPort.visibleArea.topLeft.x, fromPoint.y, viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x, toPoint.y - fromPoint.y)
browserCanvasContext.rect(fromPoint.x, fromPoint.y, toPoint.x - fromPoint.x, toPoint.y - fromPoint.y)
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.WHITE + ', ' + opacity + ')'
browserCanvasContext.closePath()
@@ -355,6 +314,23 @@
if (canDrawLogoA === false || canDrawLogoB === false || canDrawLogoExchange === false || canDrawLogoAA === false) { return }
/* Fist we calculate the corners of the current frame so as not to draw imaages ourside of it */
let fromPoint = {
x: 0,
y: 0
}
let toPoint = {
x: thisObject.container.frame.width,
y: thisObject.container.frame.height
}
fromPoint = transformThisPoint(fromPoint, thisObject.container)
toPoint = transformThisPoint(toPoint, thisObject.container)
/* Second we calculate the points for the images themselves */
let backgroundLogoPoint1
let backgroundLogoPoint2
@@ -398,6 +374,10 @@
imagePoint = transformThisPoint(imagePoint, thisObject.container)
let offSet = 0
let imagePosition = {
x: 0,
y: 0
}
for (let j = 0; j < MAX_ROWS; j++) {
if (offSet === -imageWidth * 8) {
@@ -409,7 +389,17 @@
for (let i = 0; i < MAX_COLUMNS; i = i + 4) {
let logo = logoA
browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight)
imagePosition.x = imagePoint.x + i * imageWidth * 2 + offSet
imagePosition.y = imagePoint.y + j * rowHight + Y_TOP_MARGIN
if (
imagePosition.x > fromPoint.x &&
imagePosition.x + imageWidth < toPoint.x &&
imagePosition.y > fromPoint.y &&
imagePosition.y + imageHeight < toPoint.y
) {
browserCanvasContext.drawImage(logo, imagePosition.x, imagePosition.y, imageWidth, imageHeight)
}
}
}
@@ -425,7 +415,17 @@
for (let i = 1; i < MAX_COLUMNS; i = i + 4) {
let logo = logoB
browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight)
imagePosition.x = imagePoint.x + i * imageWidth * 2 + offSet
imagePosition.y = imagePoint.y + j * rowHight + Y_TOP_MARGIN
if (
imagePosition.x > fromPoint.x &&
imagePosition.x + imageWidth < toPoint.x &&
imagePosition.y > fromPoint.y &&
imagePosition.y + imageHeight < toPoint.y
) {
browserCanvasContext.drawImage(logo, imagePosition.x, imagePosition.y, imageWidth, imageHeight)
}
}
}
@@ -441,7 +441,17 @@
for (let i = 2; i < MAX_COLUMNS; i = i + 4) {
let logo = logoExchange
browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight)
imagePosition.x = imagePoint.x + i * imageWidth * 2 + offSet
imagePosition.y = imagePoint.y + j * rowHight + Y_TOP_MARGIN
if (
imagePosition.x > fromPoint.x &&
imagePosition.x + imageWidth < toPoint.x &&
imagePosition.y > fromPoint.y &&
imagePosition.y + imageHeight < toPoint.y
) {
browserCanvasContext.drawImage(logo, imagePosition.x, imagePosition.y, imageWidth, imageHeight)
}
}
}
@@ -457,7 +467,17 @@
for (let i = 3; i < MAX_COLUMNS; i = i + 4) {
let logo = logoAA
browserCanvasContext.drawImage(logo, imagePoint.x + i * imageWidth * 2 + offSet, imagePoint.y + j * rowHight + Y_TOP_MARGIN, imageWidth, imageHeight)
imagePosition.x = imagePoint.x + i * imageWidth * 2 + offSet
imagePosition.y = imagePoint.y + j * rowHight + Y_TOP_MARGIN
if (
imagePosition.x > fromPoint.x &&
imagePosition.x + imageWidth < toPoint.x &&
imagePosition.y > fromPoint.y &&
imagePosition.y + imageHeight < toPoint.y
) {
browserCanvasContext.drawImage(logo, imagePosition.x, imagePosition.y, imageWidth, imageHeight)
}
}
}
}
+5 -4
View File
@@ -5,6 +5,7 @@ function newLogin () {
const INTENSIVE_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
let thisObject = {
container: undefined,
@@ -100,7 +101,7 @@ function newLogin () {
resolve({ user: response.data.users_UserByAuthId})
})
.catch(error => {
console.log('apolloClient error getting user query', error)
console.log('apolloClient error getting user query', error.graphQLErrors, error.stack)
reject(error)
})
})
@@ -170,7 +171,7 @@ function newLogin () {
resolve({ teams: response.data.teams_TeamsByOwner})
})
.catch(error => {
console.log('apolloClient error getting user teams', error)
console.log('apolloClient error getting user teams', error.graphQLErrors, error.stack)
reject(error)
})
})
@@ -233,7 +234,7 @@ function newLogin () {
resolve({ currentEvents: response.data.events_Events})
})
.catch(error => {
console.log('apolloClient error getting current events', error)
console.log('apolloClient error getting current events', error.graphQLErrors, error.stack)
reject(error)
})
})
@@ -320,7 +321,7 @@ function newLogin () {
resolve({ clones: response.data.operations_Clones})
})
.catch(error => {
console.log('apolloClient error getting user clones', error)
console.log('apolloClient error getting user clones', error.graphQLErrors, error.stack)
reject(error)
})
})
+55
View File
@@ -0,0 +1,55 @@
function newUIControl () {
let thisObject = {
drawFunction: undefined,
paramsArray: undefined,
container: undefined,
draw: draw,
parentContainer: undefined,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
}
let isInitialized = false
/* Cointainer stuff */
let container = newContainer()
container.name = 'UI Control'
container.initialize()
container.isClickeable = true
thisObject.container = container
thisObject.container.frame.containerName = 'Panel Tab Button'
return thisObject
function initialize () {
isInitialized = true
}
function draw () {
if (isInitialized === false) { return }
if (thisObject.drawFunction !== undefined && thisObject.paramsArray !== undefined) {
thisObject.drawFunction(thisObject.paramsArray)
}
}
function getContainer (point) {
var container
/* First we check if thisObject point is inside thisObject space. */
if (thisObject.container.frame.isThisPointHere(point, true) === true) {
/* Now we see which is the inner most container that has it */
return thisObject.container
} else {
/* This point does not belong to thisObject space. */
return undefined
}
}
}
+33 -3
View File
@@ -100,12 +100,15 @@ function getUserPosition (timeLineCoordinateSystem) {
return userPosition
}
function moveToUserPosition (container, timeLineCoordinateSystem, ignoreX, ignoreY, center) {
function moveToUserPosition (container, timeLineCoordinateSystem, ignoreX, ignoreY, center, considerZoom) {
let userPosition = getUserPosition(timeLineCoordinateSystem)
viewPort.newZoomLevel(userPosition.zoom)
if (considerZoom === true) {
viewPort.newZoomLevel(userPosition.zoom)
}
INITIAL_TIME_PERIOD = recalculatePeriod(userPosition.zoom)
INITIAL_DATE = new Date(userPosition.date)
NEW_SESSION_INITIAL_DATE = new Date(userPosition.date)
let targetPoint = {
x: (new Date(userPosition.date)).valueOf(),
@@ -151,3 +154,30 @@ function removeTime (datetime) {
return dateOnly
}
function loadEmoji (pPath) {
let newImage
newImage = new Image()
newImage.onload = onImageLoaded
function onImageLoaded () {
newImage.isLoaded = true
}
newImage.src = window.canvasApp.urlPrefix + 'Images/Emoji/' + pPath
return newImage
}
function printLabel (labelToPrint, x, y, opacity, fontSize) {
let labelPoint
browserCanvasContext.font = fontSize + 'px ' + UI_FONT.SECONDARY + ' Saira'
let label = '' + labelToPrint
let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO
browserCanvasContext.fillStyle = 'rgba(' + UI_COLOR.DARK + ', ' + opacity + ')'
browserCanvasContext.fillText(label, x, y)
}
+85
View File
@@ -0,0 +1,85 @@
function roundedCornersBackground (params) {
borderPoint1 = {
x: params.cornerRadious,
y: params.cornerRadious
}
borderPoint2 = {
x: params.container.frame.width - params.cornerRadious,
y: params.cornerRadious
}
borderPoint3 = {
x: params.container.frame.width - params.cornerRadious,
y: params.container.frame.height - params.cornerRadious
}
borderPoint4 = {
x: params.cornerRadious,
y: params.container.frame.height - params.cornerRadious
}
/* Now the transformations. */
borderPoint1 = params.container.frame.frameThisPoint(borderPoint1)
borderPoint2 = params.container.frame.frameThisPoint(borderPoint2)
borderPoint3 = params.container.frame.frameThisPoint(borderPoint3)
borderPoint4 = params.container.frame.frameThisPoint(borderPoint4)
browserCanvasContext.setLineDash([0, 0])
/* Shadow */
if (params.castShadow === true) {
let SHADOW_OFFSET = 2
browserCanvasContext.beginPath()
browserCanvasContext.arc(borderPoint1.x + SHADOW_OFFSET, borderPoint1.y + SHADOW_OFFSET, params.cornerRadious, 1.0 * Math.PI, 1.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint2.x + SHADOW_OFFSET, borderPoint2.y - params.cornerRadious + SHADOW_OFFSET)
browserCanvasContext.arc(borderPoint2.x + SHADOW_OFFSET, borderPoint2.y + SHADOW_OFFSET, params.cornerRadious, 1.5 * Math.PI, 2.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint3.x + params.cornerRadious + SHADOW_OFFSET, borderPoint3.y + SHADOW_OFFSET)
browserCanvasContext.arc(borderPoint3.x + SHADOW_OFFSET, borderPoint3.y + SHADOW_OFFSET, params.cornerRadious, 0 * Math.PI, 0.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint4.x + SHADOW_OFFSET, borderPoint4.y + params.cornerRadious + SHADOW_OFFSET)
browserCanvasContext.arc(borderPoint4.x + SHADOW_OFFSET, borderPoint4.y + SHADOW_OFFSET, params.cornerRadious, 0.5 * Math.PI, 1.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint1.x - params.cornerRadious + SHADOW_OFFSET, borderPoint1.y + SHADOW_OFFSET)
browserCanvasContext.closePath()
browserCanvasContext.lineWidth = 10
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + 0.01 + ')'
browserCanvasContext.stroke()
browserCanvasContext.lineWidth = 5
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + 0.01 + ')'
browserCanvasContext.stroke()
browserCanvasContext.lineWidth = 1
browserCanvasContext.strokeStyle = 'rgba(' + UI_COLOR.BLACK + ', ' + 0.15 + ')'
browserCanvasContext.stroke()
}
/* Background */
browserCanvasContext.beginPath()
browserCanvasContext.arc(borderPoint1.x, borderPoint1.y, params.cornerRadious, 1.0 * Math.PI, 1.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint2.x, borderPoint2.y - params.cornerRadious)
browserCanvasContext.arc(borderPoint2.x, borderPoint2.y, params.cornerRadious, 1.5 * Math.PI, 2.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint3.x + params.cornerRadious, borderPoint3.y)
browserCanvasContext.arc(borderPoint3.x, borderPoint3.y, params.cornerRadious, 0 * Math.PI, 0.5 * Math.PI)
browserCanvasContext.lineTo(borderPoint4.x, borderPoint4.y + params.cornerRadious)
browserCanvasContext.arc(borderPoint4.x, borderPoint4.y, params.cornerRadious, 0.5 * Math.PI, 1.0 * Math.PI)
browserCanvasContext.lineTo(borderPoint1.x - params.cornerRadious, borderPoint1.y)
browserCanvasContext.closePath()
browserCanvasContext.fillStyle = 'rgba(' + params.backgroundColor + ', ' + params.opacity + ')'
browserCanvasContext.fill()
browserCanvasContext.lineWidth = params.lineWidth
browserCanvasContext.strokeStyle = 'rgba(' + params.borderColor + ', ' + params.opacity + ')'
browserCanvasContext.stroke()
}
+75 -37
View File
@@ -1,5 +1,12 @@

function newViewPort () {
const MODULE_NAME = 'Viewport'
const INFO_LOG = false
const INTENSIVE_LOG = false
const ERROR_LOG = true
const logger = newWebDebugLog()
logger.fileName = MODULE_NAME
const CONSOLE_LOG = true
let ANIMATION_INCREMENT = 0.25
@@ -7,6 +14,12 @@ function newViewPort () {
const BOTTOM_MARGIN = 15 + BOTTOM_SPACE_HEIGHT
const LEFT_MARGIN = 50
const RIGHT_MARGIN = 50
const MARGINS = {
TOP: TOP_MARGIN,
BOTTOM: BOTTOM_MARGIN,
LEFT: LEFT_MARGIN,
RIGHT: RIGHT_MARGIN
}
let thisObject = {
visibleArea: undefined,
@@ -14,6 +27,7 @@ function newViewPort () {
zoomTargetLevel: undefined,
zoomLevel: undefined,
mousePosition: undefined,
margins: MARGINS,
getDisplacement: getDisplacement,
newZoomLevel: newZoomLevel,
applyZoom: applyZoom,
@@ -55,6 +69,8 @@ function newViewPort () {
thisObject.eventHandler = newEventHandler()
let objectStorage = {}
return thisObject
function initialize () {
@@ -64,6 +80,8 @@ function newViewPort () {
bottomRight: { x: browserCanvas.width - RIGHT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN},
bottomLeft: { x: LEFT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN}
}
readObjectState()
}
function getDisplacement () {
@@ -99,17 +117,6 @@ function newViewPort () {
changeZoom(thisObject.zoomLevel + ANIMATION_INCREMENT, thisObject.zoomLevel)
}
/*
if (offsetIncrement.x !== 0) {
if (Math.trunc(Math.abs(targetOffset.x - offset.x) * 1000) >= Math.trunc(Math.abs(offsetIncrement.x) * 1000)) {
offset.x = offset.x + offsetIncrement.x;
} else {
offsetIncrement.x = 0;
}
}
*/
if (offsetIncrement.y !== 0) {
if (Math.trunc(Math.abs(targetOffset.y - offset.y) * 1000) >= Math.trunc(Math.abs(offsetIncrement.y) * 1000)) {
offset.y = offset.y + offsetIncrement.y
@@ -125,6 +132,8 @@ function newViewPort () {
offset.x = offset.x + displaceVector.x
offset.y = offset.y + displaceVector.y
saveObjectState()
let event = {
newOffset: offset
}
@@ -150,6 +159,8 @@ function newViewPort () {
thisObject.zoomTargetLevel = level
thisObject.zoomLevel = level
saveObjectState()
ANIMATION_INCREMENT = Math.abs(thisObject.zoomTargetLevel - thisObject.zoomLevel) / 3
let event = {
@@ -244,6 +255,8 @@ function newViewPort () {
offset.x = offset.x - newMouse.x + thisObject.mousePosition.x
offset.y = offset.y - newMouse.y + thisObject.mousePosition.y
saveObjectState()
targetOffset.x = offset.x
targetOffset.y = offset.y
@@ -332,22 +345,21 @@ function newViewPort () {
}
function draw () {
/*
drawGrid(10);
drawGrid(1);
drawGrid(0.1);
*/
drawGrid(0.1)
}
function drawGrid (step) {
if (thisObject.zoomLevel > -17) { return }
let squareWidth = (thisObject.visibleArea.bottomRight.x - thisObject.visibleArea.bottomLeft.x) / step
squareWidth = squareWidth + squareWidth * increment * thisObject.zoomLevel
let startingX = offset.x - Math.trunc(offset.x / squareWidth) * squareWidth
let startingY = offset.y - Math.trunc(offset.y / squareWidth) * squareWidth
let lineWidth = 10 / step + 10 / step * increment * thisObject.zoomLevel
let lineWidth = 0.4 + thisObject.zoomLevel / 100
lineWidth = lineWidth.toFixed(2)
if (lineWidth < 0.5) {
if (lineWidth < 0.1) {
return
}
@@ -357,40 +369,66 @@ function newViewPort () {
browserCanvasContext.beginPath()
for (var i = startingX; i < thisObject.visibleArea.bottomRight.x; i = i + squareWidth) {
for (var j = startingY; j < thisObject.visibleArea.bottomRight.y; j = j + squareWidth) {
let CROSS_SIZE = 4
for (var i = startingX; i < thisObject.visibleArea.bottomRight.x + RIGHT_MARGIN; i = i + squareWidth) {
for (var j = startingY; j < thisObject.visibleArea.bottomRight.y + BOTTOM_MARGIN; j = j + squareWidth) {
let point1 = {
x: thisObject.visibleArea.bottomLeft.x,
y: j
x: Math.trunc(i - CROSS_SIZE),
y: Math.trunc(j)
}
let point2 = {
x: thisObject.visibleArea.bottomRight.x,
y: j
x: Math.trunc(i + CROSS_SIZE),
y: Math.trunc(j)
}
browserCanvasContext.moveTo(point1.x, point1.y)
browserCanvasContext.lineTo(point2.x, point2.y)
}
let point3 = {
x: i,
y: thisObject.visibleArea.topLeft.y
}
let point3 = {
x: Math.trunc(i),
y: Math.trunc(j - CROSS_SIZE)
}
let point4 = {
x: i,
y: thisObject.visibleArea.bottomLeft.y
}
let point4 = {
x: Math.trunc(i),
y: Math.trunc(j + CROSS_SIZE)
}
browserCanvasContext.moveTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
browserCanvasContext.moveTo(point3.x, point3.y)
browserCanvasContext.lineTo(point4.x, point4.y)
}
}
browserCanvasContext.closePath()
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.' + Math.trunc(lineWidth + 1) + ')'
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)'
browserCanvasContext.lineWidth = lineWidth
browserCanvasContext.lineWidth = 1
browserCanvasContext.stroke()
}
function saveObjectState () {
objectStorage.offset = offset
objectStorage.zoomLevel = thisObject.zoomLevel
window.localStorage.setItem(MODULE_NAME, JSON.stringify(objectStorage))
}
function readObjectState () {
let objectStorageString = window.localStorage.getItem(MODULE_NAME)
if (objectStorageString !== null && objectStorageString !== '') {
objectStorage = JSON.parse(objectStorageString)
offset = objectStorage.offset
thisObject.zoomLevel = objectStorage.zoomLevel
thisObject.zoomTargetLevel = objectStorage.zoomLevel
INITIAL_TIME_PERIOD = recalculatePeriod(thisObject.zoomLevel)
} else { // Setting default values for first session
offset = {
x: 0,
y: 0
}
thisObject.zoomLevel = MIN_ZOOM_LEVEL
thisObject.zoomTargetLevel = MIN_ZOOM_LEVEL
}
}
}
-10
View File
@@ -1,10 +0,0 @@
function newVolumeBar () {
var volumeBar = {
amountBuy: 0,
amountSell: 0,
begin: undefined,
end: undefined
}
return volumeBar
}
+1 -1
View File
@@ -2,7 +2,7 @@
function newWebDebugLog () {
let thisObject = {
write: write,
fileName: undefined
fileName: 'undefined'
}
return thisObject