Initial commit

This commit is contained in:
Luis Fernando Molina committed 2018-02-14 13:00:19 +01:00
commit 8070095b92
84 files changed
+66056

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto
Binary file not shown.
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
{
"CurrentProjectSetting": null
}
+6
View File
@@ -0,0 +1,6 @@
{
"ExpandedNodes": [
""
],
"PreviewInSolutionExplorer": false
}
Binary file not shown.
BIN
View File
Binary file not shown.
+165
View File
@@ -0,0 +1,165 @@
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<Name>AAWebPlatform</Name>
<RootNamespace>browser</RootNamespace>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>3ef11619-de26-4b8b-819d-a413df220b76</ProjectGuid>
<ProjectHome>
</ProjectHome>
<StartupFile>server.js</StartupFile>
<SearchPath>
</SearchPath>
<WorkingDirectory>.</WorkingDirectory>
<OutputPath>.</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<ProjectTypeGuids>{3AF33F2E-1136-4D97-BBB7-1795711AC8B8};{349c5851-65df-11da-9384-00065b846f21};{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}</ProjectTypeGuids>
<NodejsPort>1337</NodejsPort>
<StartWebBrowser>true</StartWebBrowser>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Compile Include="AccumulatedVolumeBar.js" />
<Compile Include="AggregatedOrdersArray.js" />
<Compile Include="Animation.js" />
<Compile Include="Azure\azure-storage.common.js" />
<Compile Include="Azure\azure-storage.file.js" />
<Compile Include="Ball.js" />
<Compile Include="Balls.js" />
<Compile Include="Panels\BotsLayersPanel.js">
<SubType>Code</SubType>
</Compile>
<Compile Include="Button.js" />
<Compile Include="Candle.js" />
<Compile Include="CandleTechnicalAnalisys\HighLowFlag.js" />
<Compile Include="CandleTechnicalAnalisys\Resistance.js" />
<Compile Include="CandleTechnicalAnalisys\Stairs.js" />
<Compile Include="CandleTechnicalAnalisys\Support.js" />
<Compile Include="Canvas.js" />
<Compile Include="ChartGrid.js" />
<Compile Include="ChartLayers\AccumulatedVolumeChartLayer.js" />
<Compile Include="ChartLayers\AllTimeChartlayer.js" />
<Compile Include="ChartLayers\CandeStickChartLayer.js" />
<Compile Include="ChartLayers\CandleTechnicalAnalisysChartLayer.js" />
<Compile Include="ChartLayers\ForecastChartLayer.js" />
<Compile Include="ChartLayers\HighLowChartLayer.js" />
<Compile Include="ChartLayers\LinearRegressionCurve.js" />
<Compile Include="ChartLayers\OrderBooksChartLayer.js" />
<Compile Include="ChartLayers\SupportResistanceChartLayer.js" />
<Compile Include="ChartLayers\VolumeChartLayer.js" />
<Compile Include="ChartLayers\VolumeTechnicalAnalisysChartLayer.js" />
<Compile Include="ChartSpace.js" />
<Compile Include="ChartUtilities.js" />
<Compile Include="Container.js" />
<Compile Include="DailyFileCursor.js" />
<Compile Include="Dashboard.js" />
<Compile Include="FileCache.js">
<SubType>Code</SubType>
</Compile>
<Compile Include="FileCloud.js">
<SubType>Code</SubType>
</Compile>
<Compile Include="server.js" />
<Compile Include="Displace.js" />
<Compile Include="EventHandler.js" />
<Compile Include="FloatingSpace.js" />
<Compile Include="Frame.js" />
<Compile Include="Indicators\LRC.js" />
<Compile Include="MarketIndex.js" />
<Compile Include="Markets.js" />
<Compile Include="MarketTrades.js" />
<Compile Include="Order.js" />
<Compile Include="OrderBook.js" />
<Compile Include="OrderBookChart.js" />
<Compile Include="OrderBookDepthChart.js" />
<Compile Include="OrderBookFilesCursor.js" />
<Compile Include="OrderBookSnapShot.js" />
<Compile Include="Panels\ChartLayersPanel.js" />
<Compile Include="Panels\ControlPanel.js" />
<Compile Include="Panels\CurrentCandlePanel.js" />
<Compile Include="Panels\CurrentVolumePanel.js" />
<Compile Include="Panels\OrderBookPanel.js" />
<Compile Include="Physics.js" />
<Compile Include="PlotArea.js" />
<Compile Include="PriceChart.js" />
<Compile Include="Resistance.js" />
<Compile Include="FileServer.js" />
<Compile Include="SplashScreen.js">
<SubType>Code</SubType>
</Compile>
<Compile Include="SpreadChart.js" />
<Compile Include="temp.js" />
<Compile Include="TextButton.js" />
<Compile Include="TimelineChart.js" />
<Compile Include="TimeMachine.js" />
<Compile Include="Trade.js" />
<Compile Include="TradesCursor.js" />
<Compile Include="Utilities.js" />
<Compile Include="ViewPort.js" />
<Compile Include="VolumeBar.js" />
<Compile Include="VolumeTechnicalAnalisys\Stairs.js" />
<Compile Include="Zoom.js" />
<Content Include="index.html" />
<Content Include="package.json" />
<Content Include="README.md" />
</ItemGroup>
<ItemGroup>
<Folder Include="Azure\" />
<Folder Include="CandleTechnicalAnalisys\" />
<Folder Include="ChartLayers\" />
<Folder Include="Indicators\" />
<Folder Include="Panels\" />
<Folder Include="VolumeTechnicalAnalisys\" />
</ItemGroup>
<!-- Do not delete the following Import Project. While this appears to do nothing it is a marker for setting TypeScript properties before our import that depends on them. -->
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="False" />
<Import Project="$(VSToolsPath)\Node.js Tools\Microsoft.NodejsTools.targets" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>False</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>0</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:48022/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>True</UseCustomServer>
<CustomServerUrl>http://localhost:1337</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}" User="">
<WebProjectProperties>
<StartPageUrl>
</StartPageUrl>
<StartAction>CurrentPage</StartAction>
<AspNetDebugging>True</AspNetDebugging>
<SilverlightDebugging>False</SilverlightDebugging>
<NativeDebugging>False</NativeDebugging>
<SQLDebugging>False</SQLDebugging>
<ExternalProgram>
</ExternalProgram>
<StartExternalURL>
</StartExternalURL>
<StartCmdLineArguments>
</StartCmdLineArguments>
<StartWorkingDirectory>
</StartWorkingDirectory>
<EnableENC>False</EnableENC>
<AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9092AA53-FB77-4645-B42D-1CCCA6BD08BD}") = "AAWebPlatform", "AAWebPlatform.njsproj", "{3EF11619-DE26-4B8B-819D-A413DF220B76}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3EF11619-DE26-4B8B-819D-A413DF220B76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3EF11619-DE26-4B8B-819D-A413DF220B76}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EF11619-DE26-4B8B-819D-A413DF220B76}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EF11619-DE26-4B8B-819D-A413DF220B76}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {92DF2F3B-B37A-407F-B313-3897AEFCCAFC}
EndGlobalSection
EndGlobal
+12
View File
@@ -0,0 +1,12 @@
function newAccumulatedVolumeBar() {
var accumulatedVolumeBar = {
begin: undefined,
end: undefined,
accumulatedBuys: 0,
accumulatedSells: 0
};
return accumulatedVolumeBar;
}
+120
View File
@@ -0,0 +1,120 @@
function newAggregatedOrdersArray() {
/* This object generates an array of orders that are aggregated by Amount A. */
var aggregatedOrdersArray = {
eventHandler: undefined,
addOrder: addOrder,
removeOrder: removeOrder,
setSortOrder: setSortOrder,
initialize: initialize
};
var array = [];
var sortOrder = 'ascending';
aggregatedOrdersArray.eventHandler = newEventHandler();
return aggregatedOrdersArray;
function initialize() {
this.eventHandler.initialize();
}
function addOrder(order) {
var wasAdded = false;
for (var i = 0; i < array.length; i++) {
var currentItem = array[i];
if (currentItem.rate === order.rate) {
currentItem.amountSum = currentItem.amountSum + order.amountA;
wasAdded = true;
}
}
if (wasAdded === false) {
var newItem = {
rate: order.rate,
amountSum: order.amountA
};
array.push(newItem);
}
applySortOrder();
aggregatedOrdersArray.eventHandler.raiseEvent('Array Changed', array);
}
function removeOrder(order) {
for (var i = 0; i < array.length; i++) {
var currentItem = array[i];
if (currentItem.rate === order.rate) { // We find the item in the array where the rate is the same as the orders rate.
currentItem.amountSum = currentItem.amountSum - order.amountA;
if (currentItem.amountSum === 0) { // If we reach zero, then there is no reason to keep this element in the array.
array.splice(i, 1); // This means remove this item from the array.
}
}
}
applySortOrder();
aggregatedOrdersArray.eventHandler.raiseEvent('Array Changed', array);
}
function setSortOrder(newSortOrder) {
sortOrder = newSortOrder;
applySortOrder();
aggregatedOrdersArray.eventHandler.raiseEvent('Array Changed', array);
}
function applySortOrder() {
array.sort(compare);
}
function compare(itemA, itemB) {
if (sortOrder === 'ascending') {
return itemA.rate - itemB.rate;
}
if (sortOrder === 'descending') {
return itemB.rate - itemA.rate;
}
return undefined;
}
}
+90
View File
@@ -0,0 +1,90 @@
/*
Essentially, what the animation object does, is to call several functions in order to draw the content of each frame.
To do that, it has an array of functions that need to be called, and it just goes one by one through them. His parent object
is responsible for providing more functions to call, or removing functions from its list when they are not longer needed.
*/
function newAnimation() {
var animationLoopHandle; // This is the handle to the animation loop. With this handle we can cancel the loop, for instance.
var callBackFunctions = new Map();
var clearCanvasFunction;
var animation = {
start: start,
stop: stop,
addCallBackFunction: addCallBackFunction,
removeCallBackFunction: removeCallBackFunction,
initialize: initialize
};
return animation;
function initialize(callBackFunction) {
/* We store the function to be called each time we need to draw a new animation frame. */
clearCanvasFunction = callBackFunction;
}
function start() {
animationLoop(); // Inside this function the animation process is started, and at the same time it creates a loop.
}
function stop() {
window.cancelAnimationFrame(animationLoopHandle);
}
function addCallBackFunction(key, callBackFunction) {
callBackFunctions.set(key, callBackFunction);
}
function removeCallBackFunction(key, callBackFunction) {
callBackFunctions.delete(key);
}
function animationLoop() {
/* First thing is to clear the actual canvas */
clearCanvasFunction();
/* We loop through the callback functions collections and execute them all. */
callBackFunctions.forEach(function (callBackFunction) {
callBackFunction();
});
/* We also draw this array of circles, that is used for debugging purposes. */
drawSmallBall();
/* We request the next frame to be drawn, and stablishing a loop */
animationLoopHandle = window.requestAnimationFrame(animationLoop);
/* We animate the zoom of the viewPort */
viewPort.animate();
viewPort.draw();
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+293
View File
@@ -0,0 +1,293 @@
function newBall() {
var ball = {
currentPosition: 0, // Current x,y position of the ball at the ball's layer, where there is no displacement or zoom. This position is always changing towards the target position.
currentSpeed: 0, // This is the current speed of the ball.
currentRadius: 0, // This is the current radius of the ball, including its zoom applied.
currentMass: 0, // This is the current mass of the ball, including its zoom applied.
friction: 0, // This is a factor that will ultimatelly desacelerate the ball.
rawPosition: 0, // This is the position on the canvas layer, withous displacement or zoom.
rawMass: 0, // This is the mass value without zoom.
rawRadius: 0, // This is the radius of this ball without zoom.
targetPosition: 0, // This is the position of the ball at the canvas plane. This position has the displacement and zoom applied.
targetRadius: 0, // This is the target radius of the ball with zoom applied. It should be animated until reaching this value.
fillStyle: '',
labelStrokeStyle: '',
labelFirstText: '',
labelSecondText: '',
radomizeCurrentPosition: radomizeCurrentPosition,
radomizeCurrentSpeed: radomizeCurrentSpeed,
initializeTargetPosition: initializeTargetPosition,
initializeMass: initializeMass,
initializeRadius: initializeRadius,
drawBackground: drawBallBackgrond, // Function to draw the ball elements on the canvas layer.
drawForeground: drawBallForeground, // Function to draw the ball elements on the balls layer.
updateMass: updateMass, // Function to update the mass when the zoom level changed.
updateRadius: updateRadius, // Function to update the radius when the zoom level changed.
updatePosition: updatePosition, // Function to update the target position when either the displacement changed or the zoom level changed.
linkedObject: undefined, // This is a reference to the object that this ball is representing.
linkedObjectType: "", // Since there might be balls for different types of objects, here we store the type of object we are linking to.
container: undefined // This is a pointer to the object where the ball belongs to.
};
return ball;
function initializeTargetPosition() {
/* The initialization is based on the rawPosition that must be set before calling this function. */
var targetPosition = {
x: this.rawPosition.x,
y: this.rawPosition.y
};
targetPosition = this.container.frame.frameThisPoint(targetPosition);
targetPosition = this.container.displacement.displaceThisPoint(targetPosition);
targetPosition = this.container.zoom.zoomThisPoint(targetPosition);
this.targetPosition = targetPosition;
// We dont need this now> smallBalls.push ([targetPosition.x, targetPosition.y, 3, 'rgba(30, 130, 30, 0.85)']);
}
function initializeMass(suggestedValue) {
var mass = suggestedValue;
if (mass < 0.1) {
mass = 0.1;
}
this.rawMass = mass;
this.currentMass = mass;
}
function initializeRadius(suggestedValue) {
var radius = suggestedValue;
if (radius < 2) {
radius = 2;
}
this.rawRadius = radius;
this.targetRadius = radius;
this.currentRadius = radius / 3;
}
function radomizeCurrentPosition(arroundPoint) {
var position = {
x: Math.floor((Math.random() * (200) - 100)) + arroundPoint.x,
y: Math.floor((Math.random() * (200) - 100)) + arroundPoint.y
};
this.currentPosition = position;
}
function radomizeCurrentSpeed() {
var initialXDirection;
var randomX = Math.floor((Math.random() * 10) + 1);
if (randomX > 5) {
initialXDirection = 1;
} else {
initialXDirection = - 1;
}
var initialYDirection;
var randomY = Math.floor((Math.random() * 10) + 1);
if (randomY > 5) {
initialYDirection = 1;
} else {
initialYDirection = - 1;
}
var velocity = {
x: initialXDirection * Math.floor((Math.random() * 300) + 1) / 100,
y: initialYDirection * Math.floor((Math.random() * 300) + 1) / 100
};
this.currentSpeed = velocity;
}
function updateMass() {
this.currentMass = this.rawMass + this.rawMass * this.container.zoom.incrementM * this.container.zoom.levelM;
}
function updateRadius() {
this.targetRadius = this.rawRadius + this.rawRadius * this.container.zoom.incrementR * this.container.zoom.levelR;
}
function updatePosition() {
var point = {
x: this.rawPosition.x,
y: this.rawPosition.y
};
/* Frame the point */
point = this.container.frame.frameThisPoint(point);
/* Second we apply the displacement. */
point = this.container.displacement.displaceThisPoint(point);
/* Third we apply the zoom factor. */
point = this.container.zoom.zoomThisPoint(point);
this.targetPosition.x = point.x;
this.targetPosition.y = point.y;
}
}
function drawBallBackgrond() {
if (this.currentRadius > 1) {
/* Target Line */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(this.currentPosition.x, this.currentPosition.y);
browserCanvasContext.lineTo(this.targetPosition.x, this.targetPosition.y);
browserCanvasContext.strokeStyle = 'rgba(204, 204, 204, 0.5)';
browserCanvasContext.setLineDash([4, 2]);
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.setLineDash([0, 0]);
}
if (this.currentRadius > 0.5) {
/* Target Spot */
var radius = 1;
browserCanvasContext.beginPath();
browserCanvasContext.arc(this.targetPosition.x, this.targetPosition.y, radius, 0, Math.PI * 2, true);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(30, 30, 30, 1)';
browserCanvasContext.fill();
}
}
function drawBallForeground() {
if (this.currentRadius > 5) {
/* Contourn */
browserCanvasContext.beginPath();
browserCanvasContext.arc(this.currentPosition.x, this.currentPosition.y, this.currentRadius, 0, Math.PI * 2, true);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(30, 30, 30, 0.75)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
if (this.currentRadius > 0.5) {
/* Main Ball */
var alphaA;
if (this.currentRadius < 3) {
alphaA = 1;
} else {
alphaA = 0.75;
}
alphaA = 0.75;
browserCanvasContext.beginPath();
browserCanvasContext.arc(this.currentPosition.x, this.currentPosition.y, this.currentRadius, 0, Math.PI * 2, true);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = this.fillStyle;
browserCanvasContext.fill();
}
/* Label First Text */
if (this.currentRadius > 6) {
browserCanvasContext.strokeStyle = this.labelStrokeStyle;
var xOffset = 0;
if (this.labelFirstText >= 10) {
xOffset = this.currentRadius / 10;
}
browserCanvasContext.font = (this.currentRadius / 4).toFixed(0) + 'px verdana';
try {
browserCanvasContext.fillText(this.labelFirstText.toFixed(0), this.currentPosition.x - 2 - xOffset, this.currentPosition.y + 2);
} catch (err) {
browserCanvasContext.fillText(this.labelFirstText, this.currentPosition.x - 2 - xOffset, this.currentPosition.y + 2);
}
}
/* Label Second Text */
if (this.currentRadius > 10) {
browserCanvasContext.strokeStyle = this.labelStrokeStyle;
var xOffset = 0;
xOffset = this.currentRadius / 2;
browserCanvasContext.font = (this.currentRadius / 6).toFixed(0) + 'px verdana';
try {
browserCanvasContext.fillText(this.labelSecondText.toFixed(8), this.currentPosition.x - xOffset, this.currentPosition.y + xOffset);
} catch (err) {
browserCanvasContext.fillText(this.labelSecondText, this.currentPosition.x - xOffset, this.currentPosition.y + xOffset);
}
}
}
+15
View File
@@ -0,0 +1,15 @@
function updateBallsTargets() {
/* Whenever there is a change in the currentZoom level, all targets needs to be recalculated in order to fit in the new plotArea. */
for (var i = 0; i < balls.length; i++) {
balls[i].updateMass();
balls[i].updateRadius();
balls[i].updatePosition();
}
}
+734
View File
@@ -0,0 +1,734 @@
function newButton() {
var button = {
container: undefined,
press: press,
draw: draw,
offFillStyle: 'rgba(150, 150, 250, 1)',
onFillStyle: 'rgba(250, 150, 150, 1)',
status: 'off',
type: undefined,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
container.isDraggeable = false;
container.isZoomeable = false;
container.isClickeable = true;
button.container = container;
const REDUCTION_FACTOR = 3;
return button;
function initialize() {
/* Lets set the basic dimensions of this button. */
var position = {
x: 0,
y: 0
};
this.container.frame.position = position;
this.container.frame.width = 50 / REDUCTION_FACTOR;
this.container.frame.height = 50 / REDUCTION_FACTOR;
/* Now we start listening to the onClick event from the mouse, so that we can allow users operate this button. */
this.container.eventHandler.listenToEvent('onMouseClick', press, undefined);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function press(event, extraData) {
button.status = 'on';
}
function draw() {
switch (this.type) {
case "Fast Backwards":
drawFastBackwards();
break;
case "Play Backwards":
drawPlayBackwards();
break;
case "Step Backwards":
drawStepBackwards();
break;
case "Pause":
drawPause();
break;
case "Step Forward":
drawStepForward();
break;
case "Play Forward":
drawPlayForward();
break;
case "Fast Forward":
drawFastForward();
break;
default:
}
}
function drawFastBackwards() {
point1 = {
x: 40 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 25 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 40 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point5 = {
x: 25 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point6 = {
x: 10 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point7 = {
x: 25 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point5 = button.container.frame.frameThisPoint(point5);
point6 = button.container.frame.frameThisPoint(point6);
point7 = button.container.frame.frameThisPoint(point7);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point5 = button.container.displacement.displaceThisPoint(point5);
point6 = button.container.displacement.displaceThisPoint(point6);
point7 = button.container.displacement.displaceThisPoint(point7);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
point5 = button.container.zoom.zoomThisPoint(point5);
point6 = button.container.zoom.zoomThisPoint(point6);
point7 = button.container.zoom.zoomThisPoint(point7);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.moveTo(point5.x, point5.y);
browserCanvasContext.lineTo(point6.x, point6.y);
browserCanvasContext.lineTo(point7.x, point7.y);
browserCanvasContext.lineTo(point5.x, point5.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawPlayBackwards() {
point1 = {
x: 40 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 10 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 40 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawStepBackwards() {
point1 = {
x: 40 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 20 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 40 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point5 = {
x: 10 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point6 = {
x: 20 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point7 = {
x: 20 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point8 = {
x: 10 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point5 = button.container.frame.frameThisPoint(point5);
point6 = button.container.frame.frameThisPoint(point6);
point7 = button.container.frame.frameThisPoint(point7);
point8 = button.container.frame.frameThisPoint(point8);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point5 = button.container.displacement.displaceThisPoint(point5);
point6 = button.container.displacement.displaceThisPoint(point6);
point7 = button.container.displacement.displaceThisPoint(point7);
point8 = button.container.displacement.displaceThisPoint(point8);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
point5 = button.container.zoom.zoomThisPoint(point5);
point6 = button.container.zoom.zoomThisPoint(point6);
point7 = button.container.zoom.zoomThisPoint(point7);
point8 = button.container.zoom.zoomThisPoint(point8);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.moveTo(point5.x, point5.y);
browserCanvasContext.lineTo(point6.x, point6.y);
browserCanvasContext.lineTo(point7.x, point7.y);
browserCanvasContext.lineTo(point8.x, point8.y);
browserCanvasContext.lineTo(point5.x, point5.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawPause() {
point1 = {
x: 10 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 20 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point3 = {
x: 20 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point4 = {
x: 10 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point5 = {
x: 30 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point6 = {
x: 40 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point7 = {
x: 40 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point8 = {
x: 30 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point4 = button.container.frame.frameThisPoint(point4);
point5 = button.container.frame.frameThisPoint(point5);
point6 = button.container.frame.frameThisPoint(point6);
point7 = button.container.frame.frameThisPoint(point7);
point8 = button.container.frame.frameThisPoint(point8);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point4 = button.container.displacement.displaceThisPoint(point4);
point5 = button.container.displacement.displaceThisPoint(point5);
point6 = button.container.displacement.displaceThisPoint(point6);
point7 = button.container.displacement.displaceThisPoint(point7);
point8 = button.container.displacement.displaceThisPoint(point8);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
point4 = button.container.zoom.zoomThisPoint(point4);
point5 = button.container.zoom.zoomThisPoint(point5);
point6 = button.container.zoom.zoomThisPoint(point6);
point7 = button.container.zoom.zoomThisPoint(point7);
point8 = button.container.zoom.zoomThisPoint(point8);
/* Lets start the drawing. */
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.moveTo(point5.x, point5.y);
browserCanvasContext.lineTo(point6.x, point6.y);
browserCanvasContext.lineTo(point7.x, point7.y);
browserCanvasContext.lineTo(point8.x, point8.y);
browserCanvasContext.lineTo(point5.x, point5.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawStepForward() {
point1 = {
x: 10 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 30 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 10 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point5 = {
x: 30 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point6 = {
x: 40 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point7 = {
x: 40 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point8 = {
x: 30 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point5 = button.container.frame.frameThisPoint(point5);
point6 = button.container.frame.frameThisPoint(point6);
point7 = button.container.frame.frameThisPoint(point7);
point8 = button.container.frame.frameThisPoint(point8);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point5 = button.container.displacement.displaceThisPoint(point5);
point6 = button.container.displacement.displaceThisPoint(point6);
point7 = button.container.displacement.displaceThisPoint(point7);
point8 = button.container.displacement.displaceThisPoint(point8);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
point5 = button.container.zoom.zoomThisPoint(point5);
point6 = button.container.zoom.zoomThisPoint(point6);
point7 = button.container.zoom.zoomThisPoint(point7);
point8 = button.container.zoom.zoomThisPoint(point8);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.moveTo(point5.x, point5.y);
browserCanvasContext.lineTo(point6.x, point6.y);
browserCanvasContext.lineTo(point7.x, point7.y);
browserCanvasContext.lineTo(point8.x, point8.y);
browserCanvasContext.lineTo(point5.x, point5.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawPlayForward() {
point1 = {
x: 10 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 40 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 10 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function drawFastForward() {
point1 = {
x: 10 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point2 = {
x: 25 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point3 = {
x: 10 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
point5 = {
x: 25 / REDUCTION_FACTOR,
y: 10 / REDUCTION_FACTOR
};
point6 = {
x: 40 / REDUCTION_FACTOR,
y: 25 / REDUCTION_FACTOR
};
point7 = {
x: 25 / REDUCTION_FACTOR,
y: 40 / REDUCTION_FACTOR
};
/* Now the transformations. */
point1 = button.container.frame.frameThisPoint(point1);
point2 = button.container.frame.frameThisPoint(point2);
point3 = button.container.frame.frameThisPoint(point3);
point5 = button.container.frame.frameThisPoint(point5);
point6 = button.container.frame.frameThisPoint(point6);
point7 = button.container.frame.frameThisPoint(point7);
point1 = button.container.displacement.displaceThisPoint(point1);
point2 = button.container.displacement.displaceThisPoint(point2);
point3 = button.container.displacement.displaceThisPoint(point3);
point5 = button.container.displacement.displaceThisPoint(point5);
point6 = button.container.displacement.displaceThisPoint(point6);
point7 = button.container.displacement.displaceThisPoint(point7);
point1 = button.container.zoom.zoomThisPoint(point1);
point2 = button.container.zoom.zoomThisPoint(point2);
point3 = button.container.zoom.zoomThisPoint(point3);
point5 = button.container.zoom.zoomThisPoint(point5);
point6 = button.container.zoom.zoomThisPoint(point6);
point7 = button.container.zoom.zoomThisPoint(point7);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
browserCanvasContext.lineTo(point3.x, point3.y);
browserCanvasContext.lineTo(point1.x, point1.y);
browserCanvasContext.moveTo(point5.x, point5.y);
browserCanvasContext.lineTo(point6.x, point6.y);
browserCanvasContext.lineTo(point7.x, point7.y);
browserCanvasContext.lineTo(point5.x, point5.y);
browserCanvasContext.closePath();
if (button.status === "on") {
browserCanvasContext.fillStyle = button.onFillStyle;
} else {
browserCanvasContext.fillStyle = button.offFillStyle;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.5)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
}
+17
View File
@@ -0,0 +1,17 @@
function newCandle() {
var candle = {
open: undefined,
close: undefined,
min: 10000000000000,
max: 0,
begin: undefined,
end: undefined,
direction: undefined,
beginId: undefined,
endId: undefined
};
return candle;
}
+16
View File
@@ -0,0 +1,16 @@
function newHighLowFlag() {
var highLowFlag = {
rate: undefined,
type: undefined,
begin: undefined,
end: undefined,
firstBegin: undefined,
lastEnd: undefined,
pastCandles: 0,
futureCandles: 0
};
return highLowFlag;
}
+12
View File
@@ -0,0 +1,12 @@
function newResistance() {
var resistance = {
rate: undefined,
begin: undefined,
end: undefined,
candleCount: 0
};
return resistance;
}
+21
View File
@@ -0,0 +1,21 @@
function newCandleStairs() {
var candleStairs = {
open: undefined,
close: undefined,
min: 10000000000000,
max: 0,
begin: undefined,
end: undefined,
direction: undefined,
candleCount: 0,
firstMin: 0,
firstMax: 0,
lastMin: 0,
lastMax: 0,
slope: undefined
};
return candleStairs;
}
+12
View File
@@ -0,0 +1,12 @@
function newSupport() {
var support = {
rate: undefined,
begin: undefined,
end: undefined,
candleCount: 0
};
return support;
}
+414
View File
@@ -0,0 +1,414 @@
/*
Whithin this system, the canvas object represents a layer on top of the browser canvas object, and it is the one who should interact with it.
Graphically, the system has 3 spaces:
1) The "Chart Space": It is where the charts are plotted.
2) The "Floating Space": It is where floating elements live. There is a physics engine for this layer that allows these elements to flow.
3) The "Control Panel": It is where the main controls are. This is a fix panel that sits on top of everything else.
All these spaces are child objects of the Canvas object.
*/
var browserCanvas; // This is the canvas object of the browser.
var browserCanvasContext; // The context of the canvas object.
let stepsInitializationCounter = 0; // This counter the initialization steps required to be able to turn off the splash screen.
let marketInitializationCounter = 0; // This counter the initialization of markets required to be able to turn off the splash screen.
let splashScreenNeeded = true;
function newCanvas() {
/* Mouse event related variables. */
var containerDragStarted = false;
var ballDragStarted = false;
var ballBeingDragged;
var containerBeingDragged;
var viewPortBeingDragged = false;
var dragVector = {
downX: 0,
downY: 0,
upX: 0,
upY: 0
};
/* canvas object */
var canvas = {
eventHandler: undefined,
chartSpace: undefined,
floatingSpace: undefined,
animation: undefined,
initialize: initialize
};
canvas.eventHandler = newEventHandler();
let splashScreen;
return canvas;
function initialize() {
initializeBrowserCanvas();
addCanvasEvents();
/* The canvas has one ChartSpace child. Here is where we get it. */
var chartSpace = newChartSpace();
chartSpace.initialize();
this.chartSpace = chartSpace;
var floatingSpace = newFloatingSpace();
floatingSpace.initialize();
this.floatingSpace = floatingSpace;
splashScreen = newSplashScreen();
splashScreen.initialize();
var animation = newAnimation();
animation.initialize(clearBrowserCanvas);
this.animation = animation;
animation.addCallBackFunction("Chart Space", this.chartSpace.draw);
animation.addCallBackFunction("Floating Space", this.floatingSpace.physicsLoop);
animation.addCallBackFunction("Splash Screen", splashScreen.draw);
animation.start();
}
function initializeBrowserCanvas() {
browserCanvas = document.getElementById('canvas');
browserCanvasContext = browserCanvas.getContext('2d');
var body = document.getElementById('body');
browserCanvas.width = window.innerWidth;
browserCanvas.height = window.innerHeight;
browserCanvas.style.border = "none";
viewPort.initialize();
}
function clearBrowserCanvas() {
browserCanvasContext.clearRect(0, 0, browserCanvas.width, browserCanvas.height);
}
function addCanvasEvents() {
/* Mouse down and up events to control the drag of the canvas. */
browserCanvas.addEventListener('mousedown', onMouseDown, false);
browserCanvas.addEventListener('mouseup', onMouseUp, false);
browserCanvas.addEventListener('mousemove', onMouseMove, false);
browserCanvas.addEventListener('click', onMouseClick, false);
/* Mouse wheel events. */
if (browserCanvas.addEventListener) {
// IE9, Chrome, Safari, Opera
browserCanvas.addEventListener("mousewheel", onMouseWheel, false);
// Firefox
browserCanvas.addEventListener("DOMMouseScroll", onMouseWheel, false);
}
// IE 6/7/8
else browserCanvas.attachEvent("onmousewheel", onMouseWheel);
}
function onMouseDown(event) {
dragVector.downX = event.pageX;
dragVector.downY = event.pageY;
/* We check first if the mouse is over a ball/ */
ballBeingDragged = isInside(event.pageX, event.pageY);
if (ballBeingDragged >= 0) {
ballDragStarted = true;
} else {
/* If it is not, then we check if it is over any of the existing containers. */
var point = {
x: event.pageX,
y: event.pageY
};
var container = canvas.chartSpace.getContainer(point);
if (container !== undefined && container.isDraggeable === true) {
containerBeingDragged = container;
containerDragStarted = true;
} else {
viewPortBeingDragged = true;
}
}
}
function onMouseClick(event) {
dragVector.downX = event.pageX;
dragVector.downY = event.pageY;
/* We check first if the mouse is over a ball/ */
var ballBeingClicked = isInside(event.pageX, event.pageY);
if (ballBeingClicked >= 0) {
/* Right now we do nothing with this. */
} else {
/* If it is not, then we check if it is over any of the existing containers. */
var point = {
x: event.pageX,
y: event.pageY
};
var container = canvas.chartSpace.getContainer(point);
if (container !== undefined && container.isClickeable === true) {
/* We deliver the event to the container that is waiting for it. */
container.eventHandler.raiseEvent('onMouseClick', event);
}
}
}
function onMouseUp(event) {
if (containerDragStarted || viewPortBeingDragged || ballDragStarted) {
canvas.eventHandler.raiseEvent("Drag Finished", undefined);
}
/* Turn off all the possible things that can be dragged. */
containerDragStarted = false;
ballDragStarted = false;
viewPortBeingDragged = false;
containerBeingDragged = undefined;
browserCanvas.style.cursor = "auto";
}
function onMouseMove(event) {
viewPort.mousePosition.x = event.pageX;
viewPort.mousePosition.y = event.pageY;
if (containerDragStarted === true || ballDragStarted === true || viewPortBeingDragged === true) {
if (ballDragStarted === true) {
if (isInsideBall(ballBeingDragged, event.pageX, event.pageY) === false) {
/* This means that the user stop moving the mouse and the ball ball out of the pointer.
In this case we cancell the drag operation . */
ballDragStarted = false;
browserCanvas.style.cursor = "auto";
return;
}
}
dragVector.upX = event.pageX;
dragVector.upY = event.pageY;
checkDrag();
}
}
function checkDrag() {
if (containerDragStarted === true || ballDragStarted === true || viewPortBeingDragged === true) {
browserCanvas.style.cursor = "grabbing";
canvas.eventHandler.raiseEvent("Dragging", undefined);
var targetBall = isInside(event.pageX, event.pageY);
if (ballDragStarted) {
var ball = balls[ballBeingDragged];
ball.currentPosition.x = dragVector.upX;
ball.currentPosition.y = dragVector.upY;
/* Now we estimate if the drag was towards the Target Point of the ball or not. */
var distDown = distance(dragVector.downX, dragVector.downY, ball.targetPosition.x, ball.targetPosition.y);
var distUp = distance(dragVector.upX, dragVector.upY, ball.targetPosition.x, ball.targetPosition.y);
var mZoomValue;
if (distDown < distUp) {
mZoomValue = 1;
} else {
mZoomValue = -1;
}
ball.container.zoom.mZoom(mZoomValue); // Zoom is applied to ball mass of all balls in the same container.
}
if (containerDragStarted || viewPortBeingDragged) {
/* The parameters received have been captured with zoom applied. We must remove the zoom in order to correctly modify the displacement. */
var downCopy = {
x: dragVector.downX,
y: dragVector.downY
};
var downCopyNoTransf;
downCopyNoTransf = viewPort.unzoomThisPoint(downCopy);
//downCopyNoTransf = containerBeingDragged.zoom.unzoomThisPoint(downCopyNoTransf);
var upCopy = {
x: dragVector.upX,
y: dragVector.upY
};
var upCopyNoTranf;
upCopyNoTranf = viewPort.unzoomThisPoint(upCopy);
//upCopyNoTranf = containerBeingDragged.zoom.unzoomThisPoint(upCopyNoTranf);
/*
let displaceVector = {
x: upCopyNoTranf.x - downCopyNoTransf.x,
y: upCopyNoTranf.y - downCopyNoTransf.y
};
*/
let displaceVector = {
x: dragVector.upX - dragVector.downX,
y: dragVector.upY - dragVector.downY
};
if (viewPortBeingDragged) {
viewPort.displace(displaceVector);
}
if (containerBeingDragged !== undefined) {
containerBeingDragged.frame.position.x = containerBeingDragged.frame.position.x + displaceVector.x;
containerBeingDragged.frame.position.y = containerBeingDragged.frame.position.y + displaceVector.y;
}
/*
if (containerBeingDragged.displacement.displace(diffX, diffY) === true) {
updateBallsTargets(); // TODO: this should not be here
} else
{
// If the displacement can not be performed, then we dont abort the dragging operation, just allow the user to move the mouse in some other direction.
}
*/
}
/* Finally we set the starting point of the new dragVector at this current point. */
dragVector.downX = dragVector.upX;
dragVector.downY = dragVector.upY;
}
}
function onMouseWheel(event) {
// cross-browser wheel delta
var event = window.event || event; // old IE support
var delta = Math.max(-1, Math.min(1, event.wheelDelta || -event.detail));
var ballIndex = isInside(event.pageX, event.pageY);
if (ballIndex >= 0) {
/* We need to apply the Radius zoom to the cointainer of the ball where the zoom was made, for that reason, we need the ball. */
balls[ballIndex].container.zoom.rZoom(delta); // Zoom is applied to ball radius.
} else {
/* We check if the mouse is over any of the existing containers. */
var point = {
x: event.pageX,
y: event.pageY
};
/*
var container = canvas.chartSpace.getContainer(point);
if (container !== undefined && container.isZoomeable === true) {
if (container.zoom.xyZoom(delta) === true) {
updateBallsTargets();
}
} */
viewPort.applyZoom(delta);
}
return false; // This instructs the browser not to take the event and scroll the page.
}
}
+644
View File
@@ -0,0 +1,644 @@
function newChartGrid() {
var chartGrid = {
draw: draw
};
return chartGrid;
function draw(container, plotArea) {
let periods = [];
let boxes = [];
let labels = [];
const basePeriod = {
x: 8 * 60 * 60 * 1000,
y: plotArea.max.y / 1000 / CHART_ASPECT_RATIO
};
let period = {
x: basePeriod.x,
y: basePeriod.y
};
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 = plotArea.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 = plotArea.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 = plotArea.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 = plotArea.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 = plotArea.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());
}
printLabels(1000, 10000);
function plotGrid(period) {
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 = plotArea.unInverseTransform(visiblePoint1, container.frame.height);
let visiblePoint2 = {
x: viewPort.visibleArea.bottomRight.x,
y: viewPort.visibleArea.topRight.y
};
visiblePoint2 = unTransformThisPoint(visiblePoint2, container);
visiblePoint2 = plotArea.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 lastLabelPosition = {
x: 0,
y: 0
};
for (var j = startingPoint.y; j <= endingPoint.y + periodHeight; j = j + periodHeight) {
if (j >= 0 && j <= plotArea.max.y) {
let point1 = {
x: visiblePoint1.x,
y: j
};
let point2 = {
x: visiblePoint2.x,
y: j
};
point1 = plotArea.inverseTransform(point1, container.frame.height);
point2 = plotArea.inverseTransform(point2, container.frame.height);
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 */
let fontSize = 10;
let label = ' ' + Math.round(j * 1000000) / 1000000;
let labelPoint = {
x: viewPort.visibleArea.bottomRight.x + 1,
y: point1.y + fontSize / 2 * FONT_ASPECT_RATIO
};
if (Math.abs(lastLabelPosition.y - labelPoint.y > fontSize || lastLabelPosition.y === 0)) {
if (labelPoint.y > viewPort.visibleArea.topLeft.y + fontSize && labelPoint.y < viewPort.visibleArea.bottomRight.y - fontSize) {
browserCanvasContext.font = fontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
}
lastLabelPosition.x = labelPoint.x;
lastLabelPosition.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: plotArea.max.y
};
point3 = plotArea.inverseTransform(point3, container.frame.height);
point4 = plotArea.inverseTransform(point4, container.frame.height);
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(0, 37, 224, 0.' + 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(255, 255, 255, 1)';
browserCanvasContext.fill();
browserCanvasContext.closePath();
browserCanvasContext.font = fontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
browserCanvasContext.fillStyle = 'rgba(255, 255, 255, 1)';
browserCanvasContext.beginPath();
browserCanvasContext.rect(0, 0, viewPort.visibleArea.topLeft.x, viewPort.visibleArea.topLeft.y);
browserCanvasContext.rect(viewPort.visibleArea.topRight.x, 0, 500, viewPort.visibleArea.topLeft.y);
browserCanvasContext.closePath();
browserCanvasContext.fill();
}
}
}
+672
View File
@@ -0,0 +1,672 @@
function newAccumulatedVolumeChartLayer() {
var volumeBars = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var plotAreaFrame = newPlotArea();
let datetime = INITIAL_DATE;
var accumulatedVolumeChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
accumulatedVolumeChartLayer.container = container;
container.displacement.containerName = "Accumulated Volume Chart";
container.zoom.containerName = "Accumulated Volume Chart";
container.frame.containerName = "Accumulated Volume Chart";
var marketId;
var exchangeId;
let marketIndex;
let dailyFilesCursor;
let maxAccumulatedBalance = 0;
const MAX_ACCUMULATED_BALANCE_BARS_HEIGHT = 250;
const PLOT_Y_BASE_LINE = viewPort.visibleArea.bottomLeft.y * 0.50;
let layerStatus = 'off';
let parentLayerStatus = 'off';
return accumulatedVolumeChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.BUY_SELL_BALANCE);
parentLayerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.VOLUME);
}
function getContainer(point) {
if (layerStatus === 'off') { return; }
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Volume') {
parentLayerStatus = eventData.status;
}
if (eventData.layer === 'Buy Sell Balance') {
layerStatus = eventData.status;
}
}
function onZoomChanged(event) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
function onDragFinished() {
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
recalculateVolumeBars();
}
function draw() {
if (layerStatus !== 'on') { return; }
if (parentLayerStatus === 'off') { return; }
this.container.frame.draw();
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
if (Math.random() * 100 > 98) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
}
plotAccumulatedVolumeBalanceChart();
}
function recalculateVolumeBars() {
if (layerStatus === 'off') { return; }
if (parentLayerStatus === 'off') { return; }
if (timePeriod === ONE_DAY_IN_MILISECONDS) {
recalculateVolumeBarsUsingMarketIndex();
} else {
recalculateVolumeBarsUsingDailyFiles();
}
}
function recalculateVolumeBarsUsingMarketIndex() {
volumeBars = [];
let accumulatedBuys = 0;
let accumulatedSells = 0;
maxAccumulatedBalance = 0;
for (var i = 0; i < marketIndex.volumes.length; i++) {
var volumeBar = newAccumulatedVolumeBar();
let amountBuy = 0;
let amountSell = 0;
volumeBar.begin = (new Date(marketIndex.volumes[i][2])).valueOf();
volumeBar.end = (new Date(marketIndex.volumes[i][3])).valueOf();
amountBuy = marketIndex.volumes[i][0];
amountSell = marketIndex.volumes[i][1];
accumulatedBuys = accumulatedBuys + amountBuy;
accumulatedSells = accumulatedSells + amountSell;
volumeBar.accumulatedBuys = accumulatedBuys;
volumeBar.accumulatedSells = accumulatedSells;
let balance = volumeBar.accumulatedBuys - volumeBar.accumulatedSells;
if (maxAccumulatedBalance < Math.abs(balance)) { maxAccumulatedBalance = Math.abs(balance); }
volumeBars.push(volumeBar);
}
}
function calculateAccumulatedBalance(currentDate) {
let accumulatedBuys = 0;
let accumulatedSells = 0;
let volumeBar = newAccumulatedVolumeBar();
let lastValidBar;
let found = false;
for (var i = 0; i < marketIndex.volumes.length; i++) {
let barDate = new Date(marketIndex.volumes[i][3]);
if (barDate.valueOf() > currentDate.valueOf() && found === false) {
lastValidBar = volumeBar; // return the last valid one.
found = true;
}
volumeBar = newAccumulatedVolumeBar();
let amountBuy = 0;
let amountSell = 0;
volumeBar.begin = (new Date(marketIndex.volumes[i][2])).valueOf();
volumeBar.end = (new Date(marketIndex.volumes[i][3])).valueOf();
amountBuy = marketIndex.volumes[i][0];
amountSell = marketIndex.volumes[i][1];
accumulatedBuys = accumulatedBuys + amountBuy;
accumulatedSells = accumulatedSells + amountSell;
volumeBar.accumulatedBuys = accumulatedBuys;
volumeBar.accumulatedSells = accumulatedSells;
let balance = volumeBar.accumulatedBuys - volumeBar.accumulatedSells;
if (maxAccumulatedBalance < Math.abs(balance)) { maxAccumulatedBalance = Math.abs(balance); }
}
return lastValidBar;
}
function recalculateVolumeBarsUsingDailyFiles(currentDateOnly) {
let daysOnSides = getSideDays(timePeriod);
let leftDate;
let rightDate;
if (currentDateOnly === true) {
leftDate = new Date(datetime.getTime());
rightDate = new Date(datetime.getTime());
leftDate = removeTime(datetime);
rightDate = removeTime(datetime);
} else {
leftDate = getDateFromPoint(viewPort.visibleArea.topLeft, accumulatedVolumeChartLayer.container, plotArea);
rightDate = getDateFromPoint(viewPort.visibleArea.topRight, accumulatedVolumeChartLayer.container, plotArea);
leftDate.setDate(leftDate.getDate() - daysOnSides);
rightDate.setDate(rightDate.getDate() + daysOnSides);
}
let currentDate = new Date(leftDate.getTime());
volumeBars = [];
let firstFile = true;
let accumulatedBuys = 0;
let accumulatedSells = 0;
maxAccumulatedBalance = 0;
while (currentDate.getTime() <= rightDate.getTime()) {
let stringDate = currentDate.getFullYear() + '-' + pad(currentDate.getMonth() + 1, 2) + '-' + pad(currentDate.getDate(), 2);
let dailyFile = dailyFilesCursor.dailyFiles.get(stringDate);
if (dailyFile !== undefined) {
let lastVolumeBar;
if (firstFile === true) {
/* We calculate the initial Accumulated Balance based on the Index Files upto this current date*/
lastVolumeBar = calculateAccumulatedBalance(currentDate);
try {
accumulatedBuys = lastVolumeBar.accumulatedBuys;
accumulatedSells = lastVolumeBar.accumulatedSells;
}
catch (err) {
// In the situation where there are daily files for a certain date but the index file is not reaching that date, an error is catched here.
}
firstFile = false;
}
const fileTimePeriod = 60 * 1000;
const totalVolumeBars = dailyFile.length * fileTimePeriod / timePeriod;
const recordsPerVolumeBar = timePeriod / fileTimePeriod;
for (var i = 0; i < totalVolumeBars; i++) {
var volumeBar = newAccumulatedVolumeBar();
let amountBuy = 0;
let amountSell = 0;
for (var j = 0; j < recordsPerVolumeBar; j++) {
amountBuy = amountBuy + dailyFile[i * recordsPerVolumeBar + j][8];
amountSell = amountSell + dailyFile[i * recordsPerVolumeBar + j][9];
}
volumeBar.begin = dailyFile[i * recordsPerVolumeBar][4];
volumeBar.end = dailyFile[i * recordsPerVolumeBar + recordsPerVolumeBar - 1][5];
accumulatedBuys = accumulatedBuys + amountBuy;
accumulatedSells = accumulatedSells + amountSell;
volumeBar.accumulatedBuys = accumulatedBuys;
volumeBar.accumulatedSells = accumulatedSells;
let balance = volumeBar.accumulatedBuys - volumeBar.accumulatedSells;
volumeBars.push(volumeBar);
}
}
currentDate.setDate(currentDate.getDate() + 1);
}
}
function recalculateScaleX() {
var minValue = {
x: EARLIEST_DATE.valueOf()
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf()
};
plotArea.initializeX(
minValue,
maxValue,
accumulatedVolumeChartLayer.container.frame.width
);
plotAreaFrame.initializeX(
minValue,
maxValue,
accumulatedVolumeChartLayer.container.frame.width
);
}
function recalculateScaleY() {
var minValue = {
y: 0
};
var maxValue = {
y: 0
};
let timePeriodRatio = ONE_DAY_IN_MILISECONDS / timePeriod;
maxValue.y = marketIndex.maxVolume() / (timePeriodRatio / 10);
plotArea.initializeY(
minValue,
maxValue,
viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y
);
plotAreaFrame.initializeY(
minValue,
maxValue,
accumulatedVolumeChartLayer.container.frame.height
);
}
function plotAccumulatedVolumeBalanceChart() {
let visibleHeight = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y;
let frameCorner1 = {
x: 0,
y: 0
};
let frameCorner2 = {
x: accumulatedVolumeChartLayer.container.frame.width,
y: accumulatedVolumeChartLayer.container.frame.height
};
/* Now the transformations. */
frameCorner1 = transformThisPoint(frameCorner1, accumulatedVolumeChartLayer.container.frame.container);
frameCorner2 = transformThisPoint(frameCorner2, accumulatedVolumeChartLayer.container.frame.container);
let frameHeightInViewPort = frameCorner2.y - frameCorner1.y;
if (volumeBars.length > 0) {
for (var i = 0; i < volumeBars.length; i++) {
volumeBar = volumeBars[i];
let volumeBarPointA1;
let volumeBarPointA2;
let volumeBarPointA3;
let volumeBarPointA4;
function calculateBuys(plot, height) {
volumeBarPointA1 = {
x: volumeBar.begin,
y: 0
};
volumeBarPointA2 = {
x: volumeBar.begin,
y: 0
};
volumeBarPointA3 = {
x: volumeBar.end,
y: 0
};
volumeBarPointA4 = {
x: volumeBar.end,
y: 0
};
volumeBarPointA1 = plot.inverseTransform(volumeBarPointA1, height);
volumeBarPointA2 = plot.inverseTransform(volumeBarPointA2, height);
volumeBarPointA3 = plot.inverseTransform(volumeBarPointA3, height);
volumeBarPointA4 = plot.inverseTransform(volumeBarPointA4, height);
volumeBarPointA1 = transformThisPoint(volumeBarPointA1, accumulatedVolumeChartLayer.container);
volumeBarPointA2 = transformThisPoint(volumeBarPointA2, accumulatedVolumeChartLayer.container);
volumeBarPointA3 = transformThisPoint(volumeBarPointA3, accumulatedVolumeChartLayer.container);
volumeBarPointA4 = transformThisPoint(volumeBarPointA4, accumulatedVolumeChartLayer.container);
if (volumeBarPointA4.x < viewPort.visibleArea.bottomLeft.x || volumeBarPointA1.x > viewPort.visibleArea.bottomRight.x) {
return false;
}
return true;
}
if (calculateBuys(plotAreaFrame, accumulatedVolumeChartLayer.container.frame.height) === false) { continue; } // We try to see if it fits in the visible area.
let volumeBarPointB1;
let volumeBarPointB2;
let volumeBarPointB3;
let volumeBarPointB4;
function calculateSells(plot, height) {
volumeBarPointB1 = {
x: volumeBar.begin,
y: height
};
volumeBarPointB2 = {
x: volumeBar.begin,
y: height - volumeBar.amountSell
};
volumeBarPointB3 = {
x: volumeBar.end,
y: height - volumeBar.amountSell
};
volumeBarPointB4 = {
x: volumeBar.end,
y: height
};
volumeBarPointB1 = plot.inverseTransform2(volumeBarPointB1, height);
volumeBarPointB2 = plot.inverseTransform2(volumeBarPointB2, height);
volumeBarPointB3 = plot.inverseTransform2(volumeBarPointB3, height);
volumeBarPointB4 = plot.inverseTransform2(volumeBarPointB4, height);
volumeBarPointB1 = transformThisPoint(volumeBarPointB1, accumulatedVolumeChartLayer.container);
volumeBarPointB2 = transformThisPoint(volumeBarPointB2, accumulatedVolumeChartLayer.container);
volumeBarPointB3 = transformThisPoint(volumeBarPointB3, accumulatedVolumeChartLayer.container);
volumeBarPointB4 = transformThisPoint(volumeBarPointB4, accumulatedVolumeChartLayer.container);
}
calculateSells(plotAreaFrame, accumulatedVolumeChartLayer.container.frame.height); // We try to see if it fits in the visible area.
if (volumeBarPointB1.y < viewPort.visibleArea.topLeft.y && frameHeightInViewPort > visibleHeight * 2 / 3) {
calculateSells(plotArea, visibleHeight); // We snap it to the view port.
/* Now we set the real value of y. */
volumeBarPointB1.y = viewPort.visibleArea.topLeft.y;
volumeBarPointB2.y = viewPort.visibleArea.topLeft.y + volumeBar.amountSell * plotArea.scale.y;
volumeBarPointB3.y = viewPort.visibleArea.topLeft.y + volumeBar.amountSell * plotArea.scale.y;
volumeBarPointB4.y = viewPort.visibleArea.topLeft.y;
}
/* Everything must fit within the visible area */
volumeBarPointA1 = viewPort.fitIntoVisibleArea(volumeBarPointA1);
volumeBarPointA2 = viewPort.fitIntoVisibleArea(volumeBarPointA2);
volumeBarPointA3 = viewPort.fitIntoVisibleArea(volumeBarPointA3);
volumeBarPointA4 = viewPort.fitIntoVisibleArea(volumeBarPointA4);
volumeBarPointB1 = viewPort.fitIntoVisibleArea(volumeBarPointB1);
volumeBarPointB2 = viewPort.fitIntoVisibleArea(volumeBarPointB2);
volumeBarPointB3 = viewPort.fitIntoVisibleArea(volumeBarPointB3);
volumeBarPointB4 = viewPort.fitIntoVisibleArea(volumeBarPointB4);
/* Everything must fit within the Frame. We know that that is equivalent to say that each bar con not be higher than the base of the opposite . */
if (volumeBarPointA2.y < volumeBarPointB1.y) {
volumeBarPointA2.y = volumeBarPointB1.y;
volumeBarPointA3.y = volumeBarPointB1.y;
}
if (volumeBarPointB2.y > volumeBarPointA1.y) {
volumeBarPointB2.y = volumeBarPointA1.y;
volumeBarPointB3.y = volumeBarPointA1.y;
}
/* Here we will plot the balance of accumulated buys and sells */
let balance = volumeBar.accumulatedBuys - volumeBar.accumulatedSells;
let heigh = MAX_ACCUMULATED_BALANCE_BARS_HEIGHT;
let scale = MAX_ACCUMULATED_BALANCE_BARS_HEIGHT / maxAccumulatedBalance;
const OPACITY = '0.15';
if (balance > 0) {
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointA1.x, PLOT_Y_BASE_LINE);
browserCanvasContext.lineTo(volumeBarPointA2.x, PLOT_Y_BASE_LINE - balance * scale);
browserCanvasContext.lineTo(volumeBarPointA3.x, PLOT_Y_BASE_LINE - balance * scale);
browserCanvasContext.lineTo(volumeBarPointA4.x, PLOT_Y_BASE_LINE);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= volumeBar.begin && dateValue <= volumeBar.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + OPACITY + ')'; // Current bar accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + OPACITY + ')';
}
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + OPACITY + ')';
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + OPACITY + ')';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
} else {
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointB2.x, PLOT_Y_BASE_LINE);
browserCanvasContext.lineTo(volumeBarPointB3.x, PLOT_Y_BASE_LINE);
browserCanvasContext.lineTo(volumeBarPointB3.x, PLOT_Y_BASE_LINE - balance * scale);
browserCanvasContext.lineTo(volumeBarPointB2.x, PLOT_Y_BASE_LINE - balance * scale);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= volumeBar.begin && dateValue <= volumeBar.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + OPACITY + ')'; // Current bar accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + OPACITY + ')';
}
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + OPACITY + ')';
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + OPACITY + ')';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
}
+382
View File
@@ -0,0 +1,382 @@
function newAllTimeChartLayer() {
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var plotAreaFrame = newPlotArea();
let datetime = INITIAL_DATE;
var allTimeChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
allTimeChartLayer.container = container;
container.displacement.containerName = "All Time Chart";
container.zoom.containerName = "All Time Chart";
container.frame.containerName = "All Time Chart";
var marketId;
var exchangeId;
let marketIndex;
let allTimeHigh;
let allTimeLow;
let allTimeHighs = [];
let allTimeLows = [];
let layerStatus = 'off';
return allTimeChartLayer;
function initialize(exchange, market, index, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
recalculateScale();
let server = newFileServer();
server.initialize();
server.getAllTimes(exchangeId, marketId, onFileReady);
function onFileReady(file) {
allTimes = file;
for (let i = 0; i < allTimes.length; i++) {
if (allTimes[i][0] === 'high') {
allTimeHighs.push([allTimes[i][1], allTimes[i][2]]);
}
if (allTimes[i][0] === 'low') {
allTimeLows.push([allTimes[i][1], allTimes[i][2]]);
}
}
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.ATH);
}
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'All-time Highs and Lows') {
layerStatus = eventData.status;
}
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') { return; }
this.container.frame.draw();
plotAllTimeChart();
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
allTimeChartLayer.container.frame.width,
allTimeChartLayer.container.frame.height
);
}
function plotAllTimeChart() {
let firstHighRate = 0;
let firstLowRate = 0;
if (marketIndex.candles.length > 0) {
firstHighRate = marketIndex.candles[0][2];
firstLowRate = marketIndex.candles[0][2];
}
if (allTimeHighs.length > 0) {
browserCanvasContext.beginPath();
let leftCornerPoint = {
x: plotArea.min.x,
y: plotArea.max.y
};
leftCornerPoint = plotArea.inverseTransform(leftCornerPoint, allTimeChartLayer.container.frame.height);
leftCornerPoint = transformThisPoint(leftCornerPoint, allTimeChartLayer.container);
leftCornerPoint = viewPort.fitIntoVisibleArea(leftCornerPoint);
browserCanvasContext.moveTo(leftCornerPoint.x, leftCornerPoint.y);
let firstPoint = {
x: plotArea.min.x,
y: firstHighRate
};
firstPoint = plotArea.inverseTransform(firstPoint, allTimeChartLayer.container.frame.height);
firstPoint = transformThisPoint(firstPoint, allTimeChartLayer.container);
firstPoint = viewPort.fitIntoVisibleArea(firstPoint);
browserCanvasContext.lineTo(firstPoint.x, firstPoint.y);
let lastRate = firstHighRate;
for (var i = 0; i < allTimeHighs.length; i++) {
let rate = allTimeHighs[i][0];
let begin = Math.trunc(allTimeHighs[i][1] / timePeriod) * timePeriod + timePeriod / 2;
let allTimePointA;
allTimePointA = {
x: begin,
y: lastRate
};
allTimePointA = plotArea.inverseTransform(allTimePointA, allTimeChartLayer.container.frame.height);
allTimePointA = transformThisPoint(allTimePointA, allTimeChartLayer.container);
allTimePointA = viewPort.fitIntoVisibleArea(allTimePointA);
browserCanvasContext.lineTo(allTimePointA.x, allTimePointA.y);
let allTimePointB;
allTimePointB = {
x: begin,
y: rate
};
allTimePointB = plotArea.inverseTransform(allTimePointB, allTimeChartLayer.container.frame.height);
allTimePointB = transformThisPoint(allTimePointB, allTimeChartLayer.container);
allTimePointB = viewPort.fitIntoVisibleArea(allTimePointB);
browserCanvasContext.lineTo(allTimePointB.x, allTimePointB.y);
lastRate = rate;
}
let lastPoint = {
x: plotArea.max.x,
y: allTimeHighs[allTimeHighs.length - 1][0]
};
lastPoint = plotArea.inverseTransform(lastPoint, allTimeChartLayer.container.frame.height);
lastPoint = transformThisPoint(lastPoint, allTimeChartLayer.container);
lastPoint = viewPort.fitIntoVisibleArea(lastPoint);
browserCanvasContext.lineTo(lastPoint.x, lastPoint.y);
let rightCornerPoint = {
x: plotArea.max.x,
y: plotArea.max.y
};
rightCornerPoint = plotArea.inverseTransform(rightCornerPoint, allTimeChartLayer.container.frame.height);
rightCornerPoint = transformThisPoint(rightCornerPoint, allTimeChartLayer.container);
rightCornerPoint = viewPort.fitIntoVisibleArea(rightCornerPoint);
browserCanvasContext.lineTo(rightCornerPoint.x, rightCornerPoint.y);
browserCanvasContext.closePath();
const OPACITY = '0.05';
browserCanvasContext.fillStyle = 'rgba(0, 229, 255, ' + OPACITY + ')';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(0, 140, 255, ' + OPACITY + ')';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
if (allTimeLows.length > 0) {
browserCanvasContext.beginPath();
let leftCornerPoint = {
x: plotArea.min.x,
y: plotArea.min.y
};
leftCornerPoint = plotArea.inverseTransform(leftCornerPoint, allTimeChartLayer.container.frame.height);
leftCornerPoint = transformThisPoint(leftCornerPoint, allTimeChartLayer.container);
leftCornerPoint = viewPort.fitIntoVisibleArea(leftCornerPoint);
browserCanvasContext.moveTo(leftCornerPoint.x, leftCornerPoint.y);
let firstPoint = {
x: plotArea.min.x,
y: firstLowRate
};
firstPoint = plotArea.inverseTransform(firstPoint, allTimeChartLayer.container.frame.height);
firstPoint = transformThisPoint(firstPoint, allTimeChartLayer.container);
firstPoint = viewPort.fitIntoVisibleArea(firstPoint);
browserCanvasContext.lineTo(firstPoint.x, firstPoint.y);
let lastRate = firstLowRate;
for (var i = 0; i < allTimeLows.length; i++) {
let rate = allTimeLows[i][0];
let begin = Math.trunc(allTimeLows[i][1] / timePeriod) * timePeriod + timePeriod / 2;
let allTimePointA;
allTimePointA = {
x: begin,
y: lastRate
};
allTimePointA = plotArea.inverseTransform(allTimePointA, allTimeChartLayer.container.frame.height);
allTimePointA = transformThisPoint(allTimePointA, allTimeChartLayer.container);
allTimePointA = viewPort.fitIntoVisibleArea(allTimePointA);
browserCanvasContext.lineTo(allTimePointA.x, allTimePointA.y);
let allTimePointB;
allTimePointB = {
x: begin,
y: rate
};
allTimePointB = plotArea.inverseTransform(allTimePointB, allTimeChartLayer.container.frame.height);
allTimePointB = transformThisPoint(allTimePointB, allTimeChartLayer.container);
allTimePointB = viewPort.fitIntoVisibleArea(allTimePointB);
browserCanvasContext.lineTo(allTimePointB.x, allTimePointB.y);
lastRate = rate;
}
let lastPoint = {
x: plotArea.max.x,
y: allTimeLows[allTimeLows.length - 1][0]
};
lastPoint = plotArea.inverseTransform(lastPoint, allTimeChartLayer.container.frame.height);
lastPoint = transformThisPoint(lastPoint, allTimeChartLayer.container);
lastPoint = viewPort.fitIntoVisibleArea(lastPoint);
browserCanvasContext.lineTo(lastPoint.x, lastPoint.y);
let rightCornerPoint = {
x: plotArea.max.x,
y: plotArea.min.y
};
rightCornerPoint = plotArea.inverseTransform(rightCornerPoint, allTimeChartLayer.container.frame.height);
rightCornerPoint = transformThisPoint(rightCornerPoint, allTimeChartLayer.container);
rightCornerPoint = viewPort.fitIntoVisibleArea(rightCornerPoint);
browserCanvasContext.lineTo(rightCornerPoint.x, rightCornerPoint.y);
browserCanvasContext.closePath();
const OPACITY = '0.05';
browserCanvasContext.fillStyle = 'rgba(168, 77, 2, ' + OPACITY + ')';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(255, 115, 0, ' + OPACITY + ')';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
+601
View File
@@ -0,0 +1,601 @@
function newCandleStickChartLayer() {
var candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var candleStickChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
currentCandle: undefined,
positionAtDatetime: positionAtDatetime,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
candleStickChartLayer.container = container;
container.displacement.containerName = "Candle Stick Chart";
container.zoom.containerName = "Candle Stick Chart";
container.frame.containerName = "Candle Stick Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let layerStatus = 'off';
return candleStickChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
recalculateCandlesUsingDailyFiles(true); // We need the first day of candles so as to see which is going to be the center of the viewport.
if (marketId === INITIAL_DEFAULT_MARKET) { // For now, lets position the view port at the market USDT/BTC
postitionViewPort();
}
recalculateCandles();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLESTICKS);
}
function getContainer(point) {
if (layerStatus !== 'on') { return; }
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Candlesticks') {
layerStatus = eventData.status;
}
}
function onZoomChanged(event) {
recalculateCandles();
}
function onDragFinished() {
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
recalculateCandles();
}
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
recalculateCandles();
}
function postitionViewPort() {
try {
let targetPoint = {
x: candles[Math.round(candles.length / 2)].begin,
y: candles[Math.round(candles.length / 2)].min + (candles[Math.round(candles.length / 2)].max - candles[Math.round(candles.length / 2)].min)
};
targetPoint = plotArea.inverseTransform(targetPoint, candleStickChartLayer.container.frame.height);
targetPoint = transformThisPoint(targetPoint, candleStickChartLayer.container);
let displaceVector = {
x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.topLeft.x) / 2 - targetPoint.x,
y: (viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y) / 2 - targetPoint.y
};
viewPort.displace(displaceVector);
} catch (err) {
// if there data is missing of the days it must position in then an exception is raised.
}
}
function positionAtDatetime(newDatetime) {
value = newDatetime.valueOf();
/* Now we calculate which candle has this new time, because it will give us the y coordinate. */
for (let i = 0; i < candles.length; i++) {
if (value >= candles[i].begin && value <= candles[i].end) {
let targetPoint = {
x: value,
y: candles[i].open
};
targetPoint = plotArea.inverseTransform(targetPoint, candleStickChartLayer.container.frame.height);
targetPoint = transformThisPoint(targetPoint, candleStickChartLayer.container);
let targetMax = {
x: value,
y: candles[i].max
};
targetMax = plotArea.inverseTransform(targetMax, candleStickChartLayer.container.frame.height);
targetMax = transformThisPoint(targetMax, candleStickChartLayer.container);
let targetMin = {
x: value,
y: candles[i].min
};
targetMin = plotArea.inverseTransform(targetMin, candleStickChartLayer.container.frame.height);
targetMin = transformThisPoint(targetMin, candleStickChartLayer.container);
let center = {
x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2,
y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2
};
if (targetMax.y < viewPort.visibleArea.topLeft.y || targetMin.y > viewPort.visibleArea.bottomRight.y) {
let displaceVector = {
x: 0,
y: center.y - targetPoint.y
};
viewPort.displaceTarget(displaceVector);
}
let displaceVector = {
x: center.x - targetPoint.x,
y: 0
};
viewPort.displace(displaceVector);
return;
}
}
}
function draw() {
if (layerStatus !== 'on') { return; }
this.container.frame.draw();
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
if (Math.random() * 100 > 98) {
recalculateCandles();
}
}
plotCandleChart();
}
function recalculateCandles() {
if (layerStatus === 'off') { return; }
if (timePeriod === ONE_DAY_IN_MILISECONDS) {
recalculateCandlesUsingMarketIndex();
} else {
recalculateCandlesUsingDailyFiles();
}
candleStickChartLayer.container.eventHandler.raiseEvent("Candles Changed", candles);
}
function recalculateCandlesUsingDailyFiles(currentDateOnly) {
let daysOnSides = getSideDays(timePeriod);
let leftDate;
let rightDate;
if (currentDateOnly === true) {
leftDate = new Date(datetime.getTime());
rightDate = new Date(datetime.getTime());
leftDate = removeTime(datetime);
rightDate = removeTime(datetime);
} else {
leftDate = getDateFromPoint(viewPort.visibleArea.topLeft, candleStickChartLayer.container, plotArea);
rightDate = getDateFromPoint(viewPort.visibleArea.topRight, candleStickChartLayer.container, plotArea);
leftDate.setDate(leftDate.getDate() - daysOnSides);
rightDate.setDate(rightDate.getDate() + daysOnSides);
}
let currentDate = new Date(leftDate.getTime());
candles = [];
while (currentDate.getTime() <= rightDate.getTime()) {
let stringDate = currentDate.getFullYear() + '-' + pad(currentDate.getMonth() + 1, 2) + '-' + pad(currentDate.getDate(), 2);
let dailyFile = dailyFilesCursor.dailyFiles.get(stringDate);
if (dailyFile !== undefined) {
const fileTimePeriod = 60 * 1000;
const totalCandles = dailyFile.length * fileTimePeriod / timePeriod;
const recordsPerCandle = timePeriod / fileTimePeriod;
for (var i = 0; i < totalCandles; i++) {
var candle = newCandle();
let min = dailyFile[i * recordsPerCandle][0];
let max = dailyFile[i * recordsPerCandle][1];
for (var j = 0; j < recordsPerCandle; j++) {
if (dailyFile[i * recordsPerCandle + j][0] < min) {
min = dailyFile[i * recordsPerCandle + j][0];
}
if (dailyFile[i * recordsPerCandle + j][1] > max) {
max = dailyFile[i * recordsPerCandle + j][1];
}
}
candle.min = min;
candle.max = max;
candle.open = dailyFile[i * recordsPerCandle][2];
candle.close = dailyFile[i * recordsPerCandle + recordsPerCandle - 1][3];
candle.begin = dailyFile[i * recordsPerCandle][4];
candle.end = dailyFile[i * recordsPerCandle + recordsPerCandle - 1][5];
candle.beginId = dailyFile[i * recordsPerCandle][6];
candle.endId = dailyFile[i * recordsPerCandle + recordsPerCandle - 1][7];
if (candle.open > candle.close) { candle.direction = 'down'; }
if (candle.open < candle.close) { candle.direction = 'up'; }
if (candle.open === candle.close) { candle.direction = 'side'; }
candles.push(candle);
if (datetime.valueOf() >= candle.begin && datetime.valueOf() <= candle.end) {
candleStickChartLayer.currentCandle = candle;
candleStickChartLayer.container.eventHandler.raiseEvent("Current Candle Changed", candleStickChartLayer.currentCandle);
}
}
}
currentDate.setDate(currentDate.getDate() + 1);
}
}
function recalculateCandlesUsingMarketIndex() {
candles = [];
for (var i = 0; i < marketIndex.candles.length; i++) {
var candle = newCandle();
candle.min = marketIndex.candles[i][0];
candle.max = marketIndex.candles[i][1];
candle.open = marketIndex.candles[i][2];
candle.close = marketIndex.candles[i][3];
candle.begin = (new Date(marketIndex.candles[i][4])).valueOf();
candle.end = (new Date(marketIndex.candles[i][5])).valueOf();
candle.beginId = marketIndex.candles[i][6];
candle.endId = marketIndex.candles[i][7];
if (candle.open > candle.close) { candle.direction = 'down'; }
if (candle.open < candle.close) { candle.direction = 'up'; }
if (candle.open === candle.close) { candle.direction = 'side'; }
candles.push(candle);
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
candleStickChartLayer.container.frame.width,
candleStickChartLayer.container.frame.height
);
}
function plotCandleChart() {
if (candles.length > 0) {
/* Now we calculate and plot the candles */
for (var i = 0; i < candles.length; i++) {
candle = candles[i];
var candlePoint1 = {
x: candle.begin + timePeriod / 7 * 1.5,
y: candle.open
};
var candlePoint2 = {
x: candle.begin + timePeriod / 7 * 5.5,
y: candle.open
};
var candlePoint3 = {
x: candle.begin + timePeriod / 7 * 5.5,
y: candle.close
};
var candlePoint4 = {
x: candle.begin + timePeriod / 7 * 1.5,
y: candle.close
};
candlePoint1 = plotArea.inverseTransform(candlePoint1, candleStickChartLayer.container.frame.height);
candlePoint2 = plotArea.inverseTransform(candlePoint2, candleStickChartLayer.container.frame.height);
candlePoint3 = plotArea.inverseTransform(candlePoint3, candleStickChartLayer.container.frame.height);
candlePoint4 = plotArea.inverseTransform(candlePoint4, candleStickChartLayer.container.frame.height);
candlePoint1 = transformThisPoint(candlePoint1, candleStickChartLayer.container);
candlePoint2 = transformThisPoint(candlePoint2, candleStickChartLayer.container);
candlePoint3 = transformThisPoint(candlePoint3, candleStickChartLayer.container);
candlePoint4 = transformThisPoint(candlePoint4, candleStickChartLayer.container);
if (candlePoint2.x < viewPort.visibleArea.bottomLeft.x || candlePoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
candlePoint1 = viewPort.fitIntoVisibleArea(candlePoint1);
candlePoint2 = viewPort.fitIntoVisibleArea(candlePoint2);
candlePoint3 = viewPort.fitIntoVisibleArea(candlePoint3);
candlePoint4 = viewPort.fitIntoVisibleArea(candlePoint4);
var stickPoint1 = {
x: candle.begin + timePeriod / 7 * 3.2,
y: candle.max
};
var stickPoint2 = {
x: candle.begin + timePeriod / 7 * 3.8,
y: candle.max
};
var stickPoint3 = {
x: candle.begin + timePeriod / 7 * 3.8,
y: candle.min
};
var stickPoint4 = {
x: candle.begin + timePeriod / 7 * 3.2,
y: candle.min
};
stickPoint1 = plotArea.inverseTransform(stickPoint1, candleStickChartLayer.container.frame.height);
stickPoint2 = plotArea.inverseTransform(stickPoint2, candleStickChartLayer.container.frame.height);
stickPoint3 = plotArea.inverseTransform(stickPoint3, candleStickChartLayer.container.frame.height);
stickPoint4 = plotArea.inverseTransform(stickPoint4, candleStickChartLayer.container.frame.height);
stickPoint1 = transformThisPoint(stickPoint1, candleStickChartLayer.container);
stickPoint2 = transformThisPoint(stickPoint2, candleStickChartLayer.container);
stickPoint3 = transformThisPoint(stickPoint3, candleStickChartLayer.container);
stickPoint4 = transformThisPoint(stickPoint4, candleStickChartLayer.container);
stickPoint1 = viewPort.fitIntoVisibleArea(stickPoint1);
stickPoint2 = viewPort.fitIntoVisibleArea(stickPoint2);
stickPoint3 = viewPort.fitIntoVisibleArea(stickPoint3);
stickPoint4 = viewPort.fitIntoVisibleArea(stickPoint4);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(stickPoint1.x, stickPoint1.y);
browserCanvasContext.lineTo(stickPoint2.x, stickPoint2.y);
browserCanvasContext.lineTo(stickPoint3.x, stickPoint3.y);
browserCanvasContext.lineTo(stickPoint4.x, stickPoint4.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(54, 54, 54, 1)';
browserCanvasContext.fill();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= candle.begin && dateValue <= candle.end) {
browserCanvasContext.strokeStyle = 'rgba(255, 233, 31, 1)'; // Current candle accroding to time
} else {
browserCanvasContext.strokeStyle = 'rgba(212, 206, 201, 1)';
}
} else {
browserCanvasContext.strokeStyle = 'rgba(212, 206, 201, 1)';
}
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(candlePoint1.x, candlePoint1.y);
browserCanvasContext.lineTo(candlePoint2.x, candlePoint2.y);
browserCanvasContext.lineTo(candlePoint3.x, candlePoint3.y);
browserCanvasContext.lineTo(candlePoint4.x, candlePoint4.y);
browserCanvasContext.closePath();
if (candle.direction === 'up') { browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, 1)'; }
if (candle.direction === 'down') { browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, 1)'; }
if (candle.direction === 'side') { browserCanvasContext.strokeStyle = 'rgba(27, 7, 105, 1)'; }
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= candle.begin && dateValue <= candle.end) {
/* highlight the current candle */
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 1)'; // Current candle accroding to time
let currentCandle = {
bodyWidth: candlePoint2.x - candlePoint1.x,
bodyHeight: candlePoint3.y - candlePoint2.y,
stickHeight: stickPoint4.y - stickPoint2.y,
stickWidth: stickPoint2.x - stickPoint1.x,
stickStart: candlePoint2.y - stickPoint2.y,
period: timePeriod,
innerCandle: candle
};
candleStickChartLayer.container.eventHandler.raiseEvent("Current Candle Info Changed", currentCandle);
} else {
if (candle.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, 1)'; }
if (candle.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, 1)'; }
if (candle.direction === 'side') { browserCanvasContext.fillStyle = 'rgba(64, 26, 217, 1)'; }
}
} else {
if (candle.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, 1)'; }
if (candle.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, 1)'; }
if (candle.direction === 'side') { browserCanvasContext.fillStyle = 'rgba(64, 26, 217, 1)'; }
}
if (
candlePoint1.x < viewPort.visibleArea.topLeft.x + 50
||
candlePoint1.x > viewPort.visibleArea.bottomRight.x - 50
) {
// we leave this candles without fill.
} else {
browserCanvasContext.fill();
}
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
@@ -0,0 +1,364 @@
function newCandleTechnicalAnalisysChartLayer() {
var candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var candleTechnicalAnalisysChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
onCandlesChanged: onCandlesChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
candleTechnicalAnalisysChartLayer.container = container;
container.displacement.containerName = "Candle Technical Analisys Chart";
container.zoom.containerName = "Candle Technical Analisys Chart";
container.frame.containerName = "Candle Technical Analisys Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let stairsArray = [];
let layerStatus = 'off';
let parentLayerStatus = 'off';
return candleTechnicalAnalisysChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLE_STAIRS);
parentLayerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLESTICKS);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Candlesticks') {
parentLayerStatus = eventData.status;
}
if (eventData.layer === 'Candle Stairs') {
layerStatus = eventData.status;
}
}
function onCandlesChanged(newCandles) {
candles = newCandles;
recalculatePatterns();
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') { return; }
if (parentLayerStatus === 'off') { return; }
this.container.frame.draw();
plotPatternChart();
}
function recalculatePatterns() {
if (layerStatus === 'off') { return; }
if (parentLayerStatus === 'off') { return; }
/* Finding stairs */
stairsArray = [];
let stairs;
for (let i = 0; i < candles.length - 1; i++) {
let currentCandle = candles[i];
let nextCandle = candles[i + 1];
if (currentCandle.direction === nextCandle.direction && currentCandle.direction !== 'side') {
if (stairs === undefined) {
stairs = newCandleStairs();
stairs.direction = currentCandle.direction;
stairs.candleCount = 2;
stairs.begin = currentCandle.begin;
stairs.end = nextCandle.end;
stairs.open = currentCandle.open;
stairs.close = nextCandle.close;
if (currentCandle.min < nextCandle.min) { stairs.min = currentCandle.min; } else { stairs.min = nextCandle.min; }
if (currentCandle.max > nextCandle.max) { stairs.max = currentCandle.max; } else { stairs.max = nextCandle.max; }
if (stairs.direction === 'up') {
stairs.firstMin = currentCandle.open;
stairs.firstMax = currentCandle.close;
stairs.lastMin = nextCandle.open;
stairs.lastMax = nextCandle.close;
} else {
stairs.firstMin = currentCandle.close;
stairs.firstMax = currentCandle.open;
stairs.lastMin = nextCandle.close;
stairs.lastMax = nextCandle.open;
}
} else {
stairs.candleCount++;
stairs.end = nextCandle.end;
stairs.close = nextCandle.close;
if (stairs.min < nextCandle.min) { stairs.min = currentCandle.min; }
if (stairs.max > nextCandle.max) { stairs.max = currentCandle.max; }
if (stairs.direction === 'up') {
stairs.lastMin = nextCandle.open;
stairs.lastMax = nextCandle.close;
} else {
stairs.lastMin = nextCandle.close;
stairs.lastMax = nextCandle.open;
}
}
} else {
if (stairs !== undefined) {
stairsArray.push(stairs);
stairs = undefined;
}
}
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
candleTechnicalAnalisysChartLayer.container.frame.width,
candleTechnicalAnalisysChartLayer.container.frame.height
);
}
function plotPatternChart() {
if (stairsArray.length > 0) {
for (var i = 0; i < stairsArray.length; i++) {
stairs = stairsArray[i];
let stairsPoint1;
let stairsPoint2;
let stairsPoint3;
let stairsPoint4;
if (stairs.direction === 'up') {
stairsPoint1 = {
x: stairs.begin + timePeriod / 7 * 5.5,
y: stairs.firstMin
};
stairsPoint2 = {
x: stairs.end - timePeriod / 7 * 1.5,
y: stairs.lastMin
};
stairsPoint3 = {
x: stairs.end - timePeriod / 7 * 5.5,
y: stairs.lastMax
};
stairsPoint4 = {
x: stairs.begin + timePeriod / 7 * 1.5,
y: stairs.firstMax
};
} else {
stairsPoint1 = {
x: stairs.begin + timePeriod / 7 * 1.5,
y: stairs.firstMin
};
stairsPoint2 = {
x: stairs.end - timePeriod / 7 * 5.5,
y: stairs.lastMin
};
stairsPoint3 = {
x: stairs.end - timePeriod / 7 * 1.5,
y: stairs.lastMax
};
stairsPoint4 = {
x: stairs.begin + timePeriod / 7 * 5.5,
y: stairs.firstMax
};
}
stairsPoint1 = plotArea.inverseTransform(stairsPoint1, candleTechnicalAnalisysChartLayer.container.frame.height);
stairsPoint2 = plotArea.inverseTransform(stairsPoint2, candleTechnicalAnalisysChartLayer.container.frame.height);
stairsPoint3 = plotArea.inverseTransform(stairsPoint3, candleTechnicalAnalisysChartLayer.container.frame.height);
stairsPoint4 = plotArea.inverseTransform(stairsPoint4, candleTechnicalAnalisysChartLayer.container.frame.height);
stairsPoint1 = transformThisPoint(stairsPoint1, candleTechnicalAnalisysChartLayer.container);
stairsPoint2 = transformThisPoint(stairsPoint2, candleTechnicalAnalisysChartLayer.container);
stairsPoint3 = transformThisPoint(stairsPoint3, candleTechnicalAnalisysChartLayer.container);
stairsPoint4 = transformThisPoint(stairsPoint4, candleTechnicalAnalisysChartLayer.container);
if (stairsPoint2.x < viewPort.visibleArea.bottomLeft.x || stairsPoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
stairsPoint1 = viewPort.fitIntoVisibleArea(stairsPoint1);
stairsPoint2 = viewPort.fitIntoVisibleArea(stairsPoint2);
stairsPoint3 = viewPort.fitIntoVisibleArea(stairsPoint3);
stairsPoint4 = viewPort.fitIntoVisibleArea(stairsPoint4);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(stairsPoint1.x, stairsPoint1.y);
browserCanvasContext.lineTo(stairsPoint2.x, stairsPoint2.y);
browserCanvasContext.lineTo(stairsPoint3.x, stairsPoint3.y);
browserCanvasContext.lineTo(stairsPoint4.x, stairsPoint4.y);
browserCanvasContext.closePath();
let opacity = '0.25';
if (stairs.direction === 'up') { browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')'; }
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= stairs.begin && dateValue <= stairs.end) {
/* highlight the current stairs */
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 0.1)'; // Current stairs accroding to time
} else {
if (stairs.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')'; }
}
} else {
if (stairs.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')'; }
}
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
+484
View File
@@ -0,0 +1,484 @@
function newForecastChartLayer() {
let candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
let plotArea = newPlotArea();
var datetime = INITIAL_DATE;
let forecastChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
setCurrentCandle: setCurrentCandle,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
forecastChartLayer.container = container;
container.displacement.containerName = "Forecast Chart";
container.zoom.containerName = "Forecast Chart";
container.frame.containerName = "Forecast Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let forecastCandles = [];
let currentCandle;
let layerStatus = 'off';
let parentLayerStatus = 'off';
return forecastChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.FORECAST);
parentLayerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLESTICKS);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Candlesticks') {
parentLayerStatus = eventData.status;
}
if (eventData.layer === 'Forecast') {
layerStatus = eventData.status;
}
}
function onZoomChanged(event) {
//recalculateCandles();
}
function onDragFinished() {
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
//recalculateCandles();
}
}
function setTimePeriod(period) {
timePeriod = period;
}
function setCurrentCandle(newCurrentCandle) {
currentCandle = newCurrentCandle;
recalculateForecastCandles();
recalculateCandles();
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') { return; }
if (parentLayerStatus === 'off') { return; }
this.container.frame.draw();
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
plotCandleChart();
}
}
function recalculateForecastCandles() {
if (layerStatus === 'off') { return; }
if (parentLayerStatus === 'off') { return; }
if (timePeriod < _5_MINUTES_IN_MILISECONDS || timePeriod > _1_HOUR_IN_MILISECONDS) {
forecastCandles = [];
candles = [];
return;
}
let daysOnSides = 30;
let leftDate;
let rightDate;
leftDate = getDateFromPoint(viewPort.visibleArea.topLeft, forecastChartLayer.container, plotArea);
rightDate = new Date(leftDate.getTime());
leftDate.setDate(leftDate.getDate() - daysOnSides);
let currentDate = new Date(leftDate.getTime());
forecastCandles = [];
let clonned = 0;
let clonningCandles = false;
let candleDistance;
while (currentDate.getTime() <= rightDate.getTime()) {
let stringDate = currentDate.getFullYear() + '-' + pad(currentDate.getMonth() + 1, 2) + '-' + pad(currentDate.getDate(), 2);
let dailyFile = dailyFilesCursor.dailyFiles.get(stringDate);
if (dailyFile !== undefined) {
const totalCandles = dailyFile.length;
for (var i = 0; i < totalCandles; i++) {
var candle = newCandle();
candle.min = dailyFile[i][0];
candle.max = dailyFile[i][1];
candle.open = dailyFile[i][2];
candle.close = dailyFile[i][3];
candle.begin = dailyFile[i][4];
candle.end = dailyFile[i][5];
candle.beginId = dailyFile[i][6];
candle.endId = dailyFile[i][7];
if (clonningCandles === false && currentCandle.open > candle.open - candle.open * 0.001 && currentCandle.open < candle.open + candle.open * 0.001) {
clonningCandles = true;
candleDistance = currentCandle.end - candle.begin;
}
if (clonningCandles === true) {
candle.begin = candle.begin + candleDistance;
candle.end = candle.end + candleDistance;
forecastCandles.push(candle);
clonned++;
if (clonned === Math.trunc(totalCandles / 2)) {
return;
}
}
}
}
currentDate.setDate(currentDate.getDate() + 1);
}
}
function recalculateCandles() {
try {
candles = [];
const fileTimePeriod = 60 * 1000;
const totalCandles = forecastCandles.length * fileTimePeriod / timePeriod;
const recordsPerCandle = timePeriod / fileTimePeriod;
for (var i = 0; i < totalCandles; i++) {
var candle = newCandle();
let min = forecastCandles[i * recordsPerCandle].min;
let max = forecastCandles[i * recordsPerCandle].max;
for (var j = 0; j < recordsPerCandle; j++) {
if (forecastCandles[i * recordsPerCandle + j].min < min) {
min = forecastCandles[i * recordsPerCandle + j].min;
}
if (forecastCandles[i * recordsPerCandle + j][1] > max) {
max = forecastCandles[i * recordsPerCandle + j].max;
}
}
candle.min = min;
candle.max = max;
candle.open = forecastCandles[i * recordsPerCandle].open;
candle.close = forecastCandles[i * recordsPerCandle + recordsPerCandle - 1].close;
candle.begin = forecastCandles[i * recordsPerCandle].begin;
candle.end = forecastCandles[i * recordsPerCandle + recordsPerCandle - 1].end;
candle.beginId = forecastCandles[i * recordsPerCandle].beginId;
candle.endId = forecastCandles[i * recordsPerCandle + recordsPerCandle - 1].endId;
candles.push(candle);
}
} catch (err) {
let errorDescription = err; // For now, if there is some problem we just dont have a forecast, or a complete one.
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
forecastChartLayer.container.frame.width,
forecastChartLayer.container.frame.height
);
}
function plotCandleChart() {
if (candles.length > 0) {
/* Now we calculate and plot the candles */
for (var i = 0; i < candles.length; i++) {
let candleOpacity = 0.5 - i / candles.length;
if (candleOpacity < 0) {
candleOpacity = 0;
}
let stickOpacity = 0.25 - i / candles.length * 2;
if (stickOpacity < 0) {
stickOpacity = 0;
}
candle = candles[i];
var candlePoint1 = {
x: candle.begin + timePeriod / 7 * 1.5,
y: candle.open
};
var candlePoint2 = {
x: candle.begin + timePeriod / 7 * 5.5,
y: candle.open
};
var candlePoint3 = {
x: candle.begin + timePeriod / 7 * 5.5,
y: candle.close
};
var candlePoint4 = {
x: candle.begin + timePeriod / 7 * 1.5,
y: candle.close
};
candlePoint1 = plotArea.inverseTransform(candlePoint1, forecastChartLayer.container.frame.height);
candlePoint2 = plotArea.inverseTransform(candlePoint2, forecastChartLayer.container.frame.height);
candlePoint3 = plotArea.inverseTransform(candlePoint3, forecastChartLayer.container.frame.height);
candlePoint4 = plotArea.inverseTransform(candlePoint4, forecastChartLayer.container.frame.height);
candlePoint1 = transformThisPoint(candlePoint1, forecastChartLayer.container);
candlePoint2 = transformThisPoint(candlePoint2, forecastChartLayer.container);
candlePoint3 = transformThisPoint(candlePoint3, forecastChartLayer.container);
candlePoint4 = transformThisPoint(candlePoint4, forecastChartLayer.container);
candlePoint1 = viewPort.fitIntoVisibleArea(candlePoint1);
candlePoint2 = viewPort.fitIntoVisibleArea(candlePoint2);
candlePoint3 = viewPort.fitIntoVisibleArea(candlePoint3);
candlePoint4 = viewPort.fitIntoVisibleArea(candlePoint4);
if (candlePoint2.x < viewPort.visibleArea.bottomLeft.x || candlePoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
var stickPoint1 = {
x: candle.begin + timePeriod / 7 * 3.2,
y: candle.max
};
var stickPoint2 = {
x: candle.begin + timePeriod / 7 * 3.8,
y: candle.max
};
var stickPoint3 = {
x: candle.begin + timePeriod / 7 * 3.8,
y: candle.min
};
var stickPoint4 = {
x: candle.begin + timePeriod / 7 * 3.2,
y: candle.min
};
stickPoint1 = plotArea.inverseTransform(stickPoint1, forecastChartLayer.container.frame.height);
stickPoint2 = plotArea.inverseTransform(stickPoint2, forecastChartLayer.container.frame.height);
stickPoint3 = plotArea.inverseTransform(stickPoint3, forecastChartLayer.container.frame.height);
stickPoint4 = plotArea.inverseTransform(stickPoint4, forecastChartLayer.container.frame.height);
stickPoint1 = transformThisPoint(stickPoint1, forecastChartLayer.container);
stickPoint2 = transformThisPoint(stickPoint2, forecastChartLayer.container);
stickPoint3 = transformThisPoint(stickPoint3, forecastChartLayer.container);
stickPoint4 = transformThisPoint(stickPoint4, forecastChartLayer.container);
stickPoint1 = viewPort.fitIntoVisibleArea(stickPoint1);
stickPoint2 = viewPort.fitIntoVisibleArea(stickPoint2);
stickPoint3 = viewPort.fitIntoVisibleArea(stickPoint3);
stickPoint4 = viewPort.fitIntoVisibleArea(stickPoint4);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(stickPoint1.x, stickPoint1.y);
browserCanvasContext.lineTo(stickPoint2.x, stickPoint2.y);
browserCanvasContext.lineTo(stickPoint3.x, stickPoint3.y);
browserCanvasContext.lineTo(stickPoint4.x, stickPoint4.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(54, 54, 54, ' + stickOpacity + ')';
browserCanvasContext.fill();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= candle.begin && dateValue <= candle.end) {
browserCanvasContext.strokeStyle = 'rgba(255, 233, 31, ' + stickOpacity + ')'; // Current candle accroding to time
currentCandle = i;
} else {
browserCanvasContext.strokeStyle = 'rgba(212, 206, 201, ' + stickOpacity + ')';
}
} else {
browserCanvasContext.strokeStyle = 'rgba(212, 206, 201, ' + stickOpacity + ')';
}
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(candlePoint1.x, candlePoint1.y);
browserCanvasContext.lineTo(candlePoint2.x, candlePoint2.y);
browserCanvasContext.lineTo(candlePoint3.x, candlePoint3.y);
browserCanvasContext.lineTo(candlePoint4.x, candlePoint4.y);
browserCanvasContext.closePath();
if (candle.open < candle.close) {
browserCanvasContext.strokeStyle = 'rgba(27, 145, 143, ' + candleOpacity + ')';
} else {
browserCanvasContext.strokeStyle = 'rgba(30, 28, 119, ' + candleOpacity + ')';
}
if (candle.open < candle.close) {
browserCanvasContext.fillStyle = 'rgba(49, 247, 244, ' + candleOpacity + ')';
} else {
browserCanvasContext.fillStyle = 'rgba(28, 22, 226, ' + candleOpacity + ')';
}
if (
candlePoint1.x < viewPort.visibleArea.topLeft.x + 50
||
candlePoint1.x > viewPort.visibleArea.bottomRight.x - 50
) {
// we leave this candles without fill.
} else {
browserCanvasContext.fill();
}
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
+587
View File
@@ -0,0 +1,587 @@
function newHighLowChartLayer() {
var candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var highLowChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
onCandlesChanged: onCandlesChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
highLowChartLayer.container = container;
container.displacement.containerName = "Candle Stick Chart";
container.zoom.containerName = "Candle Stick Chart";
container.frame.containerName = "Candle Stick Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let highLowFlagArray = [];
let layerStatus = 'off';
let parentLayerStatus = 'off';
return highLowChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.HIGH_LOWS);
parentLayerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLESTICKS);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Candlesticks') {
parentLayerStatus = eventData.status;
}
if (eventData.layer === 'High and Lows') {
layerStatus = eventData.status;
}
}
function onCandlesChanged(newCandles) {
candles = newCandles;
recalculateHighLow();
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
recalculateHighLow();
}
function draw() {
if (layerStatus !== 'on') { return; }
if (parentLayerStatus === 'off') { return; }
this.container.frame.draw();
plotHighLowChart();
}
function recalculateHighLow() {
if (layerStatus === 'off') { return; }
if (parentLayerStatus === 'off') { return; }
highLowFlagArray = [];
for (let i = 0; i < candles.length - 2; i++) {
let previousCandle = candles[i];
let currentCandle = candles[i + 1];
let nextCandle = candles[i + 2];
if (currentCandle.max >= previousCandle.max && currentCandle.max >= nextCandle.max) {
let highLowFlag = newHighLowFlag();
highLowFlag.rate = currentCandle.max;
highLowFlag.type = 'max-high';
highLowFlag.begin = currentCandle.begin;
highLowFlag.end = currentCandle.end;
let scanIndex;
scanIndex= i + 1;
while (scanIndex > 0) {
scanIndex--;
let scanCandle = candles[scanIndex];
if (currentCandle.max >= scanCandle.max) {
highLowFlag.firstBegin = scanCandle.begin;
highLowFlag.pastCandles++;
} else {
break;
}
}
scanIndex = i + 1;
while (scanIndex < candles.length - 1) {
scanIndex++;
let scanCandle = candles[scanIndex];
if (currentCandle.max >= scanCandle.max) {
highLowFlag.lastEnd = scanCandle.end;
highLowFlag.futureCandles++;
} else {
break;
}
}
if (highLowFlag.pastCandles >= 1 && highLowFlag.futureCandles >= 1) {
highLowFlagArray.push(highLowFlag);
}
}
if (currentCandle.min <= previousCandle.min && currentCandle.min <= nextCandle.min) {
let highLowFlag = newHighLowFlag();
highLowFlag.rate = currentCandle.min;
highLowFlag.type = 'min-low';
highLowFlag.begin = currentCandle.begin;
highLowFlag.end = currentCandle.end;
let scanIndex;
scanIndex = i + 1;
while (scanIndex > 0) {
scanIndex--;
let scanCandle = candles[scanIndex];
if (currentCandle.min <= scanCandle.min) {
highLowFlag.firstBegin = scanCandle.begin;
highLowFlag.pastCandles++;
} else {
break;
}
}
scanIndex = i + 1;
while (scanIndex < candles.length - 1) {
scanIndex++;
let scanCandle = candles[scanIndex];
if (currentCandle.min <= scanCandle.min) {
highLowFlag.lastEnd = scanCandle.end;
highLowFlag.futureCandles++;
} else {
break;
}
}
if (highLowFlag.pastCandles >= 1 && highLowFlag.futureCandles >= 1) {
highLowFlagArray.push(highLowFlag);
}
}
if (currentCandle.max <= previousCandle.max && currentCandle.max <= nextCandle.max) {
let highLowFlag = newHighLowFlag();
highLowFlag.rate = currentCandle.max;
highLowFlag.type = 'min-high';
highLowFlag.begin = currentCandle.begin;
highLowFlag.end = currentCandle.end;
let scanIndex;
scanIndex = i + 1;
while (scanIndex > 0) {
scanIndex--;
let scanCandle = candles[scanIndex];
if (currentCandle.max <= scanCandle.max) {
highLowFlag.firstBegin = scanCandle.begin;
highLowFlag.pastCandles++;
} else {
break;
}
}
scanIndex = i + 1;
while (scanIndex < candles.length - 1) {
scanIndex++;
let scanCandle = candles[scanIndex];
if (currentCandle.max <= scanCandle.max) {
highLowFlag.lastEnd = scanCandle.end;
highLowFlag.futureCandles++;
} else {
break;
}
}
if (highLowFlag.pastCandles >= 1 && highLowFlag.futureCandles >= 1) {
highLowFlagArray.push(highLowFlag);
}
}
if (currentCandle.min >= previousCandle.min && currentCandle.min >= nextCandle.min) {
let highLowFlag = newHighLowFlag();
highLowFlag.rate = currentCandle.min;
highLowFlag.type = 'max-low';
highLowFlag.begin = currentCandle.begin;
highLowFlag.end = currentCandle.end;
let scanIndex;
scanIndex = i + 1;
while (scanIndex > 0) {
scanIndex--;
let scanCandle = candles[scanIndex];
if (currentCandle.min >= scanCandle.min) {
highLowFlag.firstBegin = scanCandle.begin;
highLowFlag.pastCandles++;
} else {
break;
}
}
scanIndex = i + 1;
while (scanIndex < candles.length - 1) {
scanIndex++;
let scanCandle = candles[scanIndex];
if (currentCandle.min >= scanCandle.min) {
highLowFlag.lastEnd = scanCandle.end;
highLowFlag.futureCandles++;
} else {
break;
}
}
if (highLowFlag.pastCandles >= 1 && highLowFlag.futureCandles >= 1) {
highLowFlagArray.push(highLowFlag);
}
}
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
highLowChartLayer.container.frame.width,
highLowChartLayer.container.frame.height
);
}
function plotHighLowChart() {
if (highLowFlagArray.length > 0) {
for (var i = 0; i < highLowFlagArray.length; i++) {
flag = highLowFlagArray[i];
let flagPoint1;
let flagPoint2;
let flagPoint3;
let flagPoint4;
let flagPoint5;
let flagPoint6;
flagPoint1 = {
x: flag.begin + timePeriod / 2,
y: flag.rate
};
flagPoint2 = {
x: flag.lastEnd,
y: flag.rate
};
flagPoint3 = {
x: flag.begin + timePeriod / 2,
y: flag.rate
};
flagPoint4 = {
x: flag.begin + timePeriod / 2,
y: flag.rate
};
flagPoint5 = {
x: flag.begin + timePeriod / 2,
y: flag.rate
};
flagPoint6 = {
x: flag.begin + timePeriod / 2,
y: flag.rate
};
flagPoint7 = {
x: flag.begin + timePeriod / 7 * 1.5,
y: flag.rate
};
flagPoint8 = {
x: flag.begin + timePeriod / 7 * 5.5,
y: flag.rate
};
flagPoint1 = plotArea.inverseTransform(flagPoint1, highLowChartLayer.container.frame.height);
flagPoint2 = plotArea.inverseTransform(flagPoint2, highLowChartLayer.container.frame.height);
flagPoint3 = plotArea.inverseTransform(flagPoint3, highLowChartLayer.container.frame.height);
flagPoint4 = plotArea.inverseTransform(flagPoint4, highLowChartLayer.container.frame.height);
flagPoint5 = plotArea.inverseTransform(flagPoint5, highLowChartLayer.container.frame.height);
flagPoint6 = plotArea.inverseTransform(flagPoint6, highLowChartLayer.container.frame.height);
flagPoint7 = plotArea.inverseTransform(flagPoint7, highLowChartLayer.container.frame.height);
flagPoint8 = plotArea.inverseTransform(flagPoint8, highLowChartLayer.container.frame.height);
flagPoint1 = transformThisPoint(flagPoint1, highLowChartLayer.container);
flagPoint2 = transformThisPoint(flagPoint2, highLowChartLayer.container);
flagPoint3 = transformThisPoint(flagPoint3, highLowChartLayer.container);
flagPoint4 = transformThisPoint(flagPoint4, highLowChartLayer.container);
flagPoint5 = transformThisPoint(flagPoint5, highLowChartLayer.container);
flagPoint6 = transformThisPoint(flagPoint6, highLowChartLayer.container);
flagPoint7 = transformThisPoint(flagPoint7, highLowChartLayer.container);
flagPoint8 = transformThisPoint(flagPoint8, highLowChartLayer.container);
if (flagPoint2.x < viewPort.visibleArea.bottomLeft.x || flagPoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
let opacity = '0.50';
let POLE_HEIGHT = (flagPoint8.x - flagPoint7.x);
if (flag.type === 'max-high') {
flagPoint4.y = flagPoint4.y - POLE_HEIGHT;
flagPoint5.y = flagPoint5.y - POLE_HEIGHT * 3 / 4;
flagPoint6.y = flagPoint6.y - POLE_HEIGHT / 2;
flagPoint5.x = flagPoint5.x + POLE_HEIGHT / 2;
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')';
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')';
}
if (flag.type === 'min-low') {
flagPoint4.y = flagPoint4.y + POLE_HEIGHT;
flagPoint5.y = flagPoint5.y + POLE_HEIGHT * 3 / 4;
flagPoint6.y = flagPoint6.y + POLE_HEIGHT / 2;
flagPoint5.x = flagPoint5.x - POLE_HEIGHT / 2;
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')';
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')';
}
if (flag.type === 'min-high') {
flagPoint4.y = flagPoint4.y - POLE_HEIGHT;
flagPoint5.y = flagPoint5.y - POLE_HEIGHT * 3 / 4;
flagPoint6.y = flagPoint6.y - POLE_HEIGHT / 2;
flagPoint5.x = flagPoint5.x - POLE_HEIGHT / 2;
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')';
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')';
}
if (flag.type === 'max-low') {
flagPoint4.y = flagPoint4.y + POLE_HEIGHT;
flagPoint5.y = flagPoint5.y + POLE_HEIGHT * 3 / 4;
flagPoint6.y = flagPoint6.y + POLE_HEIGHT / 2;
flagPoint5.x = flagPoint5.x + POLE_HEIGHT / 2;
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')';
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')';
}
flagPoint1 = viewPort.fitIntoVisibleArea(flagPoint1);
flagPoint2 = viewPort.fitIntoVisibleArea(flagPoint2);
flagPoint3 = viewPort.fitIntoVisibleArea(flagPoint3);
flagPoint4 = viewPort.fitIntoVisibleArea(flagPoint4);
flagPoint5 = viewPort.fitIntoVisibleArea(flagPoint5);
flagPoint6 = viewPort.fitIntoVisibleArea(flagPoint6);
flagPoint7 = viewPort.fitIntoVisibleArea(flagPoint7);
flagPoint8 = viewPort.fitIntoVisibleArea(flagPoint8);
if (flag.direction === 'up') { browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')'; }
if (flag.direction === 'down') { browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')'; }
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= flag.begin && dateValue <= flag.end) {
/* highlight the current flag */
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 0.1)'; // Current flag accroding to time
}
}
/* Draw the flag body */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(flagPoint4.x, flagPoint4.y);
browserCanvasContext.lineTo(flagPoint5.x, flagPoint5.y);
browserCanvasContext.lineTo(flagPoint6.x, flagPoint6.y);
browserCanvasContext.closePath();
browserCanvasContext.fill();
if (flag.type === 'max-high' || flag.type === 'min-low') {
/* Draw the multi candle line */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(flagPoint1.x, flagPoint1.y);
browserCanvasContext.lineTo(flagPoint2.x, flagPoint2.y);
browserCanvasContext.closePath();
browserCanvasContext.lineWidth = 0.1;
browserCanvasContext.stroke();
}
/* Draw the floor and the pole */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(flagPoint3.x, flagPoint3.y);
browserCanvasContext.lineTo(flagPoint4.x, flagPoint4.y);
browserCanvasContext.lineTo(flagPoint5.x, flagPoint5.y);
browserCanvasContext.lineTo(flagPoint6.x, flagPoint6.y);
browserCanvasContext.moveTo(flagPoint7.x, flagPoint7.y);
browserCanvasContext.lineTo(flagPoint8.x, flagPoint8.y);
browserCanvasContext.closePath();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
+171
View File
@@ -0,0 +1,171 @@
/**
* Base File: CandleTechnicalAnalisysChartLayer.js
*/
function newLinearRegressionCurve() {
var candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var linearRegressionCurveChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
onCandlesChanged: onCandlesChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
linearRegressionCurveChartLayer.container = container;
container.displacement.containerName = "Linear Regression Curve Chart";
container.zoom.containerName = container.displacement.containerName;
container.frame.containerName = container.displacement.containerName;
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let LRCArray15 = [];
let LRCArray30 = [];
let LRCArray60 = [];
let layerStatus = 'off';
return linearRegressionCurveChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.LINEAR_REGRESION_CURVE);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Linear Regression Curve')
layerStatus = eventData.status;
}
function onCandlesChanged(newCandles) {
candles = newCandles;
recalculatePatterns();
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') return;
this.container.frame.draw();
plotPatternChart(LRCArray15, 'rgba(182, 190, 255, 0.95)');
plotPatternChart(LRCArray30, 'rgba(109, 125, 255, 0.95)');
plotPatternChart(LRCArray60, 'rgba(57, 79, 255, 0.95)');
}
function recalculatePatterns() {
if (layerStatus === 'off') return;
LRCArray15 = calculateLRC(15); //TODO Maybe one single for statement will be more efficient to calculate the 3 LRC at once.
LRCArray30 = calculateLRC(30);
LRCArray60 = calculateLRC(60);
}
function calculateLRC(depth){
let LRCArray = [];
let lrc15 = new LRCIndicator(depth);
for (let i = 0; i < candles.length - 1; i++) {
let currentCandle = candles[i];
let averagePrice = ( currentCandle.open + currentCandle.close ) / 2; // TODO Check which price should be take to get the LRC
lrc15.update(averagePrice);
let yValue = averagePrice;
if(lrc15.result != false) // TODO Check the history to get correct values on the calculation
yValue = lrc15.result;
let lrcPoint = {
x: currentCandle.begin,
y: yValue
};
LRCArray.push(lrcPoint);
}
return LRCArray;
}
function plotPatternChart(LRCArray, color) {
if (LRCArray.length > 0) {
for (var i = 0; i < LRCArray.length; i++) {
let currentLRCPoint = LRCArray[i];
let nextLRCPoint = LRCArray[i+1];
if(nextLRCPoint === undefined) continue; // TODO Make sure this works well when there is data being received from the server
currentLRCPoint = plotArea.inverseTransform(currentLRCPoint, linearRegressionCurveChartLayer.container.frame.height);
nextLRCPoint = plotArea.inverseTransform(nextLRCPoint, linearRegressionCurveChartLayer.container.frame.height);
currentLRCPoint = transformThisPoint(currentLRCPoint, linearRegressionCurveChartLayer.container);
nextLRCPoint = transformThisPoint(nextLRCPoint, linearRegressionCurveChartLayer.container);
currentLRCPoint = viewPort.fitIntoVisibleArea(currentLRCPoint);
nextLRCPoint = viewPort.fitIntoVisibleArea(nextLRCPoint);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(currentLRCPoint.x, currentLRCPoint.y);
browserCanvasContext.lineTo(nextLRCPoint.x, nextLRCPoint.y);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = color;
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
linearRegressionCurveChartLayer.container.frame.width,
linearRegressionCurveChartLayer.container.frame.height
);
}
}
+600
View File
@@ -0,0 +1,600 @@
function newOrderBooksChartLayer() {
var orderBooks = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var orderBooksChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
orderBooksChartLayer.container = container;
container.displacement.containerName = "Order Books Chart Layer";
container.zoom.containerName = "Order Books Chart Layer";
container.frame.containerName = "Order Books Chart Layer";
let marketId;
let exchangeId;
let marketIndex;
let orderBookFilesCursor;
let amountScale;
let maxAmount = 0;
const TIME_FOR_RESOLUTION_CHANGE = 10;
const MAX_RESOLUTION = 1;
const MIN_RESOLUTION = 10;
let resolution = MIN_RESOLUTION;
let timeWithoutZoomOrPane = 0;
const RECALCULATE_COUNTER_MAX_VALUE = 100;
let recalculateCounter = 0;
let layerStatus = 'off';
return orderBooksChartLayer;
function initialize(exchange, market, index, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
orderBookFilesCursor = newOrderBookFilesCursor();
orderBookFilesCursor.initialize(exchangeId, marketId);
recalculateScale();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
canvas.eventHandler.listenToEvent("Dragging", onDragging);
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.ORDER_BOOKS);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Order Books') {
layerStatus = eventData.status;
}
if (layerStatus !== 'on') { return; }
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
orderBookFilesCursor.setDatetime(datetime);
}
}
function onZoomChanged(event) {
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
timeWithoutZoomOrPane = 0;
resolution++;
if (resolution > MIN_RESOLUTION) {
resolution = MIN_RESOLUTION;
}
recalculateCounter = recalculateCounter + RECALCULATE_COUNTER_MAX_VALUE / 10;
}
/* Defining when the file cursor is updated */
if (layerStatus === 'off') { return; }
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
orderBookFilesCursor.setDatetime(datetime);
}
}
function onDragFinished() {
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
recalculateOrderBooks();
recalculateCounter = 0;
}
/* Defining when the file cursor is updated */
if (layerStatus === 'off') { return; }
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
orderBookFilesCursor.setDatetime(datetime);
}
}
function onDragging() {
recalculateCounter = 0;
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') { return; }
if (timePeriod <= _1_HOUR_IN_MILISECONDS) {
timeWithoutZoomOrPane++;
if (timeWithoutZoomOrPane > TIME_FOR_RESOLUTION_CHANGE) {
resolution--;
timeWithoutZoomOrPane = 0;
if (resolution < MAX_RESOLUTION) {
resolution = MAX_RESOLUTION;
}
//recalculateOrderBooks();
}
this.container.frame.draw();
recalculateCounter++;
if (recalculateCounter > RECALCULATE_COUNTER_MAX_VALUE) {
recalculateOrderBooks();
recalculateCounter = 0;
}
plotOrderBooksChart();
}
}
function recalculateOrderBooks() {
if (layerStatus === 'off') { return; }
/* get the bounderies */
let rateAtTop = getRateFromPoint(viewPort.visibleArea.topLeft, orderBooksChartLayer.container, plotArea);
let rateAtBottom = getRateFromPoint(viewPort.visibleArea.bottomLeft, orderBooksChartLayer.container, plotArea);
let maxPossibleRate = rateAtTop + (rateAtTop - rateAtBottom);
let minPossibleRate = rateAtBottom - (rateAtTop - rateAtBottom);
let timeAtLeft = getMilisecondsFromPoint(viewPort.visibleArea.topLeft, orderBooksChartLayer.container, plotArea);
let timeAtRight = getMilisecondsFromPoint(viewPort.visibleArea.bottomRight, orderBooksChartLayer.container, plotArea);
let maxPossibleTime = timeAtRight + (timeAtRight - timeAtLeft);
let minPossibleTime = timeAtLeft - (timeAtRight - timeAtLeft);
/* continue with the files */
let minutesOnSides = 1440 * 5;
let leftDateTime;
let rightDateTime;
leftDateTime = new Date(datetime.getTime());
leftDateTime.setMinutes(leftDateTime.getMinutes() - minutesOnSides);
let absoluteLeft = Math.trunc(leftDateTime.valueOf() / timePeriod) * timePeriod;
leftDateTime = new Date(absoluteLeft);
rightDateTime = new Date(leftDateTime.getTime());
rightDateTime.setMinutes(rightDateTime.getMinutes() + minutesOnSides * 2 );
let currentDate = new Date(leftDateTime.getTime());
orderBooks = [];
/* Lets calculate the current datetime with minutes precision */
let currentDatetime = new Date(datetime.getTime());
let currentMoment = Math.trunc(currentDatetime.valueOf() / _1_MINUTE_IN_MILISECONDS) * _1_MINUTE_IN_MILISECONDS;
/* Lets calculate the precision */
let presicion = calculatePresicion(marketIndex.maxRate());
function calculatePresicion(number) {
for (let i = -10; i <= 10; i++) {
if (number < Math.pow(10, i)) {
return Math.pow(10, i - 3);
}
}
}
let orderBook = new Map();
const fileTimePeriod = 60 * 1000;
const recordsPerCandle = timePeriod / fileTimePeriod * resolution;
let currentRecord = 0;
while (currentDate.getTime() < rightDateTime.getTime()) {
currentRecord++;
let stringDate = currentDate.getFullYear() + '-' + pad(currentDate.getMonth() + 1, 2) + '-' + pad(currentDate.getDate(), 2) + '-' + pad(currentDate.getHours(), 2) + '-' + pad(currentDate.getMinutes(), 2);
let orderBookFile = orderBookFilesCursor.orderBookFiles.get(stringDate);
if (orderBookFile !== undefined) {
if (orderBookFile.length > 0) {
let condensedMap;
condensedMap = condenceArray(orderBookFile[0], currentDate.valueOf());
for (let key of condensedMap.keys()) {
aggregate('ask', [key, condensedMap.get(key)]);
}
condensedMap = condenceArray(orderBookFile[1], currentDate.valueOf());
for (let key of condensedMap.keys()) {
aggregate('bid', [key, condensedMap.get(key)]);
}
function aggregate(type, fileRecord) {
let rate = fileRecord[0];
if (rate >= plotArea.max.y) { return; }
if (rate <= plotArea.min.y) { return; }
let amount = fileRecord[1];
if (type === 'bid' && amount > maxAmount) { maxAmount = amount; }
let orderBookPosition = orderBook.get(type + rate) || newResistance();
if (orderBookPosition.type === undefined) {
orderBookPosition.type = type;
orderBookPosition.rate = rate;
orderBookPosition.open = amount;
orderBookPosition.close = amount;
orderBookPosition.min = amount;
orderBookPosition.max = amount;
orderBookPosition.begin = currentDate.valueOf();
orderBookPosition.end = currentDate.valueOf() + fileTimePeriod;
} else {
if (amount < orderBookPosition.min) { orderBookPosition.min = amount; }
if (amount > orderBookPosition.max) { orderBookPosition.max = amount; }
orderBookPosition.end = currentDate.valueOf() + fileTimePeriod;
orderBookPosition.close = amount;
}
orderBook.set(type + rate, orderBookPosition);
}
}
}
currentDate.setMinutes(currentDate.getMinutes() + 1);
if (currentRecord === recordsPerCandle) {
orderBooks.push(orderBook);
/* Lets see now if this order book is the one corresponding to the current moment in time */
let fisrtPosition = orderBook.values().next().value;
if (fisrtPosition !== undefined) {
if (currentMoment >= fisrtPosition.begin && currentMoment < fisrtPosition.end) {
orderBooksChartLayer.container.eventHandler.raiseEvent("Current Order Book Changed", orderBook);
}
}
/* Reset map and counter */
orderBook = new Map();
currentRecord = 0;
}
}
/* Now the amount scale */
amountScale = presicion / maxAmount * 10;
function condenceArray(arrayToCondence, currentDatetime) {
let condencedMap = new Map();
let condenseFactor = getCondenseFactor(timePeriod);
for (var i = 0; i < arrayToCondence.length; i++) {
let fileRate = arrayToCondence[i][0];
let rate = Math.round(fileRate / presicion / condenseFactor) * presicion * condenseFactor;
let amount = arrayToCondence[i][1];
let storedAmount = condencedMap.get(rate) || 0;
amount = amount + storedAmount;
if (rate < maxPossibleRate && rate > minPossibleRate && currentDatetime > minPossibleTime && currentDatetime < maxPossibleTime ) {
condencedMap.set(rate, amount);
}
}
return condencedMap;
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
orderBooksChartLayer.container.frame.width,
orderBooksChartLayer.container.frame.height
);
}
function plotOrderBooksChart() {
let transparencyLevel = getTransparenceFactor(timePeriod);
/* Now we calculate and plot the orderBooks */
for (let i = 0; i < orderBooks.length; i++) {
let orderBooksMap = orderBooks[i];
for (let key of orderBooksMap.keys()) {
let orderBookPosition = orderBooksMap.get(key);
let resistancePoint1 = {
x: orderBookPosition.begin - (orderBookPosition.end - orderBookPosition.begin) * 2,
y: orderBookPosition.rate
};
let resistancePoint2 = {
x: orderBookPosition.end + (orderBookPosition.end - orderBookPosition.begin) * 2,
y: orderBookPosition.rate
};
let resistancePoint3 = {
x: orderBookPosition.end,
y: orderBookPosition.rate + orderBookPosition.close * amountScale
};
let resistancePoint4 = {
x: orderBookPosition.begin,
y: orderBookPosition.rate + orderBookPosition.open * amountScale
};
let resistancePoint5 = {
x: orderBookPosition.end,
y: orderBookPosition.rate - orderBookPosition.close * amountScale
};
let resistancePoint6 = {
x: orderBookPosition.begin,
y: orderBookPosition.rate - orderBookPosition.open * amountScale
};
resistancePoint1 = plotArea.inverseTransform(resistancePoint1, orderBooksChartLayer.container.frame.height);
resistancePoint2 = plotArea.inverseTransform(resistancePoint2, orderBooksChartLayer.container.frame.height);
resistancePoint3 = plotArea.inverseTransform(resistancePoint3, orderBooksChartLayer.container.frame.height);
resistancePoint4 = plotArea.inverseTransform(resistancePoint4, orderBooksChartLayer.container.frame.height);
resistancePoint5 = plotArea.inverseTransform(resistancePoint5, orderBooksChartLayer.container.frame.height);
resistancePoint6 = plotArea.inverseTransform(resistancePoint6, orderBooksChartLayer.container.frame.height);
resistancePoint1 = transformThisPoint(resistancePoint1, orderBooksChartLayer.container);
resistancePoint2 = transformThisPoint(resistancePoint2, orderBooksChartLayer.container);
resistancePoint3 = transformThisPoint(resistancePoint3, orderBooksChartLayer.container);
resistancePoint4 = transformThisPoint(resistancePoint4, orderBooksChartLayer.container);
resistancePoint5 = transformThisPoint(resistancePoint5, orderBooksChartLayer.container);
resistancePoint6 = transformThisPoint(resistancePoint6, orderBooksChartLayer.container);
if (resistancePoint2.x < viewPort.visibleArea.bottomLeft.x || resistancePoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
if (resistancePoint6.y < viewPort.visibleArea.topLeft.y || resistancePoint4.y > viewPort.visibleArea.bottomRight.y) {
continue;
}
resistancePoint1 = viewPort.fitIntoVisibleArea(resistancePoint1);
resistancePoint2 = viewPort.fitIntoVisibleArea(resistancePoint2);
resistancePoint3 = viewPort.fitIntoVisibleArea(resistancePoint3);
resistancePoint4 = viewPort.fitIntoVisibleArea(resistancePoint4);
resistancePoint5 = viewPort.fitIntoVisibleArea(resistancePoint5);
resistancePoint6 = viewPort.fitIntoVisibleArea(resistancePoint6);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(resistancePoint1.x, resistancePoint1.y);
browserCanvasContext.lineTo(resistancePoint2.x, resistancePoint2.y);
browserCanvasContext.lineTo(resistancePoint3.x, resistancePoint3.y);
//browserCanvasContext.lineTo(resistancePoint6.x, resistancePoint6.y);
browserCanvasContext.lineTo(resistancePoint4.x, resistancePoint4.y);
browserCanvasContext.closePath();
if (orderBookPosition.type === 'bid') {
browserCanvasContext.fillStyle = 'rgba(61, 135, 235, ' + transparencyLevel + ')';
browserCanvasContext.strokeStyle = 'rgba(51, 112, 211, 0.20)';
}
if (orderBookPosition.type === 'ask') {
browserCanvasContext.fillStyle = 'rgba(60, 233, 252, ' + transparencyLevel + ')';
browserCanvasContext.strokeStyle = 'rgba(8, 86, 94, ' + transparencyLevel + ')';
}
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= orderBookPosition.begin && dateValue < orderBookPosition.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + transparencyLevel + ')'; // Current orderBookPosition accroding to time
}
}
if (
resistancePoint1.x < viewPort.visibleArea.topLeft.x + 50
||
resistancePoint1.x > viewPort.visibleArea.bottomRight.x - 50
) {
// we leave this orderBooks without fill.
} else {
browserCanvasContext.fill();
}
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(resistancePoint1.x, resistancePoint1.y);
browserCanvasContext.lineTo(resistancePoint2.x, resistancePoint2.y);
browserCanvasContext.lineTo(resistancePoint5.x, resistancePoint5.y);
browserCanvasContext.lineTo(resistancePoint6.x, resistancePoint6.y);
browserCanvasContext.closePath();
if (
resistancePoint1.x < viewPort.visibleArea.topLeft.x + 50
||
resistancePoint1.x > viewPort.visibleArea.bottomRight.x - 50
) {
// we leave this orderBooks without fill.
} else {
browserCanvasContext.fill();
}
browserCanvasContext.stroke();
}
}
}
}
+337
View File
@@ -0,0 +1,337 @@
function newSupportResistanceChartLayer() {
var candles = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var datetime = INITIAL_DATE;
var supportResistanceChartLayer = {
onCandlesChanged: onCandlesChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
supportResistanceChartLayer.container = container;
container.displacement.containerName = "Candle Stick Chart";
container.zoom.containerName = "Candle Stick Chart";
container.frame.containerName = "Candle Stick Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let supportArray = [];
return supportResistanceChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScale();
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.CANDLESTICKS); // TODO : Put the right layer name here when it exists.
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onCandlesChanged(newCandles) {
candles = newCandles;
recalculateSupportResistance();
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
recalculateSupportResistance();
}
function draw() {
this.container.frame.draw();
plotSupportResistanceChart();
}
function recalculateSupportResistance() {
supportArray = [];
let stairs;
for (let i = 0; i < candles.length - 1; i++) {
let currentCandle = candles[i];
let nextCandle = candles[i + 1];
if (currentCandle.direction === nextCandle.direction && currentCandle.direction !== 'side') {
if (stairs === undefined) {
stairs = newCandleStairs();
stairs.direction = currentCandle.direction;
stairs.candleCount = 2;
stairs.begin = currentCandle.begin;
stairs.end = nextCandle.end;
stairs.open = currentCandle.open;
stairs.close = nextCandle.close;
if (currentCandle.min < nextCandle.min) { stairs.min = currentCandle.min; } else { stairs.min = nextCandle.min }
if (currentCandle.max > nextCandle.max) { stairs.max = currentCandle.max; } else { stairs.max = nextCandle.max }
if (stairs.direction === 'up') {
stairs.firstMin = currentCandle.open;
stairs.firstMax = currentCandle.close;
stairs.lastMin = nextCandle.open;
stairs.lastMax = nextCandle.close;
} else {
stairs.firstMin = currentCandle.close;
stairs.firstMax = currentCandle.open;
stairs.lastMin = nextCandle.close;
stairs.lastMax = nextCandle.open;
}
} else {
stairs.candleCount++;
stairs.end = nextCandle.end;
stairs.close = nextCandle.close;
if (stairs.min < nextCandle.min) { stairs.min = currentCandle.min; }
if (stairs.max > nextCandle.max) { stairs.max = currentCandle.max; }
if (stairs.direction === 'up') {
stairs.lastMin = nextCandle.open;
stairs.lastMax = nextCandle.close;
} else {
stairs.lastMin = nextCandle.close;
stairs.lastMax = nextCandle.open;
}
}
} else {
if (stairs !== undefined) {
supportArray.push(stairs);
stairs = undefined;
}
}
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
supportResistanceChartLayer.container.frame.width,
supportResistanceChartLayer.container.frame.height
);
}
function plotSupportResistanceChart() {
if (supportArray.length > 0) {
for (var i = 0; i < supportArray.length; i++) {
stairs = supportArray[i];
let stairsPoint1;
let stairsPoint2;
let stairsPoint3;
let stairsPoint4;
if (stairs.direction === 'up') {
stairsPoint1 = {
x: stairs.begin + timePeriod / 7 * 5.5,
y: stairs.firstMin
};
stairsPoint2 = {
x: stairs.end - timePeriod / 7 * 1.5,
y: stairs.lastMin
};
stairsPoint3 = {
x: stairs.end - timePeriod / 7 * 5.5,
y: stairs.lastMax
};
stairsPoint4 = {
x: stairs.begin + timePeriod / 7 * 1.5,
y: stairs.firstMax
};
} else {
stairsPoint1 = {
x: stairs.begin + timePeriod / 7 * 1.5,
y: stairs.firstMin
};
stairsPoint2 = {
x: stairs.end - timePeriod / 7 * 5.5,
y: stairs.lastMin
};
stairsPoint3 = {
x: stairs.end - timePeriod / 7 * 1.5,
y: stairs.lastMax
};
stairsPoint4 = {
x: stairs.begin + timePeriod / 7 * 5.5,
y: stairs.firstMax
};
}
stairsPoint1 = plotArea.inverseTransform(stairsPoint1, supportResistanceChartLayer.container.frame.height);
stairsPoint2 = plotArea.inverseTransform(stairsPoint2, supportResistanceChartLayer.container.frame.height);
stairsPoint3 = plotArea.inverseTransform(stairsPoint3, supportResistanceChartLayer.container.frame.height);
stairsPoint4 = plotArea.inverseTransform(stairsPoint4, supportResistanceChartLayer.container.frame.height);
stairsPoint1 = transformThisPoint(stairsPoint1, supportResistanceChartLayer.container);
stairsPoint2 = transformThisPoint(stairsPoint2, supportResistanceChartLayer.container);
stairsPoint3 = transformThisPoint(stairsPoint3, supportResistanceChartLayer.container);
stairsPoint4 = transformThisPoint(stairsPoint4, supportResistanceChartLayer.container);
if (stairsPoint2.x < viewPort.visibleArea.bottomLeft.x || stairsPoint1.x > viewPort.visibleArea.bottomRight.x) {
continue;
}
stairsPoint1 = viewPort.fitIntoVisibleArea(stairsPoint1);
stairsPoint2 = viewPort.fitIntoVisibleArea(stairsPoint2);
stairsPoint3 = viewPort.fitIntoVisibleArea(stairsPoint3);
stairsPoint4 = viewPort.fitIntoVisibleArea(stairsPoint4);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(stairsPoint1.x, stairsPoint1.y);
browserCanvasContext.lineTo(stairsPoint2.x, stairsPoint2.y);
browserCanvasContext.lineTo(stairsPoint3.x, stairsPoint3.y);
browserCanvasContext.lineTo(stairsPoint4.x, stairsPoint4.y);
browserCanvasContext.closePath();
let opacity = '0.25';
if (stairs.direction === 'up') { browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')'; }
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= stairs.begin && dateValue <= stairs.end) {
/* highlight the current stairs */
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 0.1)'; // Current stairs accroding to time
} else {
if (stairs.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')'; }
}
} else {
if (stairs.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')'; }
if (stairs.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')'; }
}
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
+609
View File
@@ -0,0 +1,609 @@
function newVolumeChartLayer() {
var volumeBars = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var plotAreaFrame = newPlotArea();
let datetime = INITIAL_DATE;
var volumeChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
volumeChartLayer.container = container;
container.displacement.containerName = "VolumeBar Stick Chart";
container.zoom.containerName = "VolumeBar Stick Chart";
container.frame.containerName = "VolumeBar Stick Chart";
var marketId;
var exchangeId;
let marketIndex;
let dailyFilesCursor;
let maxAccumulatedBalance = 0;
const MAX_ACCUMULATED_BALANCE_BARS_HEIGHT = 150;
let layerStatus = 'off';
return volumeChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.VOLUME);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Volume') {
layerStatus = eventData.status;
}
}
function onZoomChanged(event) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
function onDragFinished() {
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
recalculateVolumeBars();
}
function draw() {
if (layerStatus !== 'on') { return; }
this.container.frame.draw();
if (timePeriod !== ONE_DAY_IN_MILISECONDS) {
if (Math.random() * 100 > 98) {
recalculateScaleX();
recalculateVolumeBars();
recalculateScaleY();
}
}
plotVolumeBarChart();
}
function recalculateVolumeBars() {
if (layerStatus === 'off') { return; }
if (timePeriod === ONE_DAY_IN_MILISECONDS) {
recalculateVolumeBarsUsingMarketIndex();
} else {
recalculateVolumeBarsUsingDailyFiles();
}
volumeChartLayer.container.eventHandler.raiseEvent("Volumes Changed", volumeBars);
}
function recalculateVolumeBarsUsingMarketIndex() {
volumeBars = [];
let accumulatedBuys = 0;
let accumulatedSells = 0;
maxAccumulatedBalance = 0;
for (var i = 0; i < marketIndex.volumes.length; i++) {
var volumeBar = newVolumeBar();
volumeBar.begin = (new Date(marketIndex.volumes[i][2])).valueOf();
volumeBar.end = (new Date(marketIndex.volumes[i][3])).valueOf();
volumeBar.amountBuy = marketIndex.volumes[i][0];
volumeBar.amountSell = marketIndex.volumes[i][1];
accumulatedBuys = accumulatedBuys + volumeBar.amountBuy;
accumulatedSells = accumulatedSells + volumeBar.amountSell;
volumeBars.push(volumeBar);
}
}
function recalculateVolumeBarsUsingDailyFiles(currentDateOnly) {
let daysOnSides = getSideDays(timePeriod);
let leftDate;
let rightDate;
if (currentDateOnly === true) {
leftDate = new Date(datetime.getTime());
rightDate = new Date(datetime.getTime());
leftDate = removeTime(datetime);
rightDate = removeTime(datetime);
} else {
leftDate = getDateFromPoint(viewPort.visibleArea.topLeft, volumeChartLayer.container, plotArea);
rightDate = getDateFromPoint(viewPort.visibleArea.topRight, volumeChartLayer.container, plotArea);
leftDate.setDate(leftDate.getDate() - daysOnSides);
rightDate.setDate(rightDate.getDate() + daysOnSides);
}
let currentDate = new Date(leftDate.getTime());
volumeBars = [];
while (currentDate.getTime() <= rightDate.getTime()) {
let stringDate = currentDate.getFullYear() + '-' + pad(currentDate.getMonth() + 1, 2) + '-' + pad(currentDate.getDate(), 2);
let dailyFile = dailyFilesCursor.dailyFiles.get(stringDate);
if (dailyFile !== undefined) {
const fileTimePeriod = 60 * 1000;
const totalVolumeBars = dailyFile.length * fileTimePeriod / timePeriod;
const recordsPerVolumeBar = timePeriod / fileTimePeriod;
for (var i = 0; i < totalVolumeBars; i++) {
var volumeBar = newVolumeBar();
for (var j = 0; j < recordsPerVolumeBar; j++) {
volumeBar.amountBuy = volumeBar.amountBuy + dailyFile[i * recordsPerVolumeBar + j][8];
volumeBar.amountSell = volumeBar.amountSell + dailyFile[i * recordsPerVolumeBar + j][9];
}
volumeBar.begin = dailyFile[i * recordsPerVolumeBar][4];
volumeBar.end = dailyFile[i * recordsPerVolumeBar + recordsPerVolumeBar - 1][5];
volumeBars.push(volumeBar);
}
}
currentDate.setDate(currentDate.getDate() + 1);
}
}
function recalculateScaleX() {
var minValue = {
x: EARLIEST_DATE.valueOf()
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf()
};
plotArea.initializeX(
minValue,
maxValue,
volumeChartLayer.container.frame.width
);
plotAreaFrame.initializeX(
minValue,
maxValue,
volumeChartLayer.container.frame.width
);
}
function recalculateScaleY() {
var minValue = {
y: 0
};
var maxValue = {
y: 0
};
let timePeriodRatio = ONE_DAY_IN_MILISECONDS / timePeriod;
maxValue.y = marketIndex.maxVolume() / (timePeriodRatio / 10);
plotArea.initializeY(
minValue,
maxValue,
viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y
);
plotAreaFrame.initializeY(
minValue,
maxValue,
volumeChartLayer.container.frame.height
);
}
function plotVolumeBarChart() {
let visibleHeight = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y;
let frameCorner1 = {
x: 0,
y: 0
};
let frameCorner2 = {
x: volumeChartLayer.container.frame.width,
y: volumeChartLayer.container.frame.height
};
/* Now the transformations. */
frameCorner1 = transformThisPoint(frameCorner1, volumeChartLayer.container.frame.container);
frameCorner2 = transformThisPoint(frameCorner2, volumeChartLayer.container.frame.container);
let frameHeightInViewPort = frameCorner2.y - frameCorner1.y;
if (volumeBars.length > 0) {
for (var i = 0; i < volumeBars.length; i++) {
volumeBar = volumeBars[i];
let volumeBarPointA1;
let volumeBarPointA2;
let volumeBarPointA3;
let volumeBarPointA4;
function calculateBuys(plot, height) {
volumeBarPointA1 = {
x: volumeBar.begin + timePeriod / 7 * 2,
y: 0
};
volumeBarPointA2 = {
x: volumeBar.begin + timePeriod / 7 * 2,
y: volumeBar.amountBuy
};
volumeBarPointA3 = {
x: volumeBar.begin + timePeriod / 7 * 5,
y: volumeBar.amountBuy
};
volumeBarPointA4 = {
x: volumeBar.begin + timePeriod / 7 * 5,
y: 0
};
volumeBarPointA1 = plot.inverseTransform(volumeBarPointA1, height);
volumeBarPointA2 = plot.inverseTransform(volumeBarPointA2, height);
volumeBarPointA3 = plot.inverseTransform(volumeBarPointA3, height);
volumeBarPointA4 = plot.inverseTransform(volumeBarPointA4, height);
volumeBarPointA1 = transformThisPoint(volumeBarPointA1, volumeChartLayer.container);
volumeBarPointA2 = transformThisPoint(volumeBarPointA2, volumeChartLayer.container);
volumeBarPointA3 = transformThisPoint(volumeBarPointA3, volumeChartLayer.container);
volumeBarPointA4 = transformThisPoint(volumeBarPointA4, volumeChartLayer.container);
let baseIncrement = (volumeBarPointA3.x - volumeBarPointA1.x) * WIDHTER_VOLUME_BAR_BASE_FACTOR;
volumeBarPointA1.x = volumeBarPointA1.x - baseIncrement;
volumeBarPointA4.x = volumeBarPointA4.x + baseIncrement;
if (volumeBarPointA4.x < viewPort.visibleArea.bottomLeft.x || volumeBarPointA1.x > viewPort.visibleArea.bottomRight.x) {
return false;
}
return true;
}
if (calculateBuys(plotAreaFrame, volumeChartLayer.container.frame.height) === false) { continue; } // We try to see if it fits in the visible area.
if (volumeBarPointA1.y > viewPort.visibleArea.bottomLeft.y && frameHeightInViewPort > visibleHeight * 2 / 3) {
if (calculateBuys(plotArea, visibleHeight) === false) { continue; } // We snap t to the view port.
/* Now we set the real value of y. */
volumeBarPointA1.y = viewPort.visibleArea.bottomRight.y;
volumeBarPointA2.y = viewPort.visibleArea.bottomRight.y - volumeBar.amountBuy * plotArea.scale.y;
volumeBarPointA3.y = viewPort.visibleArea.bottomRight.y - volumeBar.amountBuy * plotArea.scale.y;
volumeBarPointA4.y = viewPort.visibleArea.bottomRight.y;
}
let volumeBarPointB1;
let volumeBarPointB2;
let volumeBarPointB3;
let volumeBarPointB4;
function calculateSells(plot, height) {
volumeBarPointB1 = {
x: volumeBar.begin + timePeriod / 7 * 2,
y: height
};
volumeBarPointB2 = {
x: volumeBar.begin + timePeriod / 7 * 2,
y: height - volumeBar.amountSell
};
volumeBarPointB3 = {
x: volumeBar.begin + timePeriod / 7 * 5,
y: height - volumeBar.amountSell
};
volumeBarPointB4 = {
x: volumeBar.begin + timePeriod / 7 * 5,
y: height
};
volumeBarPointB1 = plot.inverseTransform2(volumeBarPointB1, height);
volumeBarPointB2 = plot.inverseTransform2(volumeBarPointB2, height);
volumeBarPointB3 = plot.inverseTransform2(volumeBarPointB3, height);
volumeBarPointB4 = plot.inverseTransform2(volumeBarPointB4, height);
volumeBarPointB1 = transformThisPoint(volumeBarPointB1, volumeChartLayer.container);
volumeBarPointB2 = transformThisPoint(volumeBarPointB2, volumeChartLayer.container);
volumeBarPointB3 = transformThisPoint(volumeBarPointB3, volumeChartLayer.container);
volumeBarPointB4 = transformThisPoint(volumeBarPointB4, volumeChartLayer.container);
}
calculateSells(plotAreaFrame, volumeChartLayer.container.frame.height); // We try to see if it fits in the visible area.
if (volumeBarPointB1.y < viewPort.visibleArea.topLeft.y && frameHeightInViewPort > visibleHeight * 2 / 3) {
calculateSells(plotArea, visibleHeight); // We snap it to the view port.
/* Now we set the real value of y. */
volumeBarPointB1.y = viewPort.visibleArea.topLeft.y;
volumeBarPointB2.y = viewPort.visibleArea.topLeft.y + volumeBar.amountSell * plotArea.scale.y;
volumeBarPointB3.y = viewPort.visibleArea.topLeft.y + volumeBar.amountSell * plotArea.scale.y;
volumeBarPointB4.y = viewPort.visibleArea.topLeft.y;
}
/* We put a wider base */
let baseIncrement = (volumeBarPointB3.x - volumeBarPointB1.x) * WIDHTER_VOLUME_BAR_BASE_FACTOR;
volumeBarPointB1.x = volumeBarPointB1.x - baseIncrement;
volumeBarPointB4.x = volumeBarPointB4.x + baseIncrement;
/* We put a less wider top */
let baseDencrement = (volumeBarPointA3.x - volumeBarPointA2.x) * LESS_WIDHTER_VOLUME_BAR_TOP_FACTOR;
volumeBarPointA2.x = volumeBarPointA2.x + baseDencrement;
volumeBarPointA3.x = volumeBarPointA3.x - baseDencrement;
volumeBarPointB2.x = volumeBarPointB2.x + baseDencrement;
volumeBarPointB3.x = volumeBarPointB3.x - baseDencrement;
/* Everything must fit within the visible area */
volumeBarPointA1 = viewPort.fitIntoVisibleArea(volumeBarPointA1);
volumeBarPointA2 = viewPort.fitIntoVisibleArea(volumeBarPointA2);
volumeBarPointA3 = viewPort.fitIntoVisibleArea(volumeBarPointA3);
volumeBarPointA4 = viewPort.fitIntoVisibleArea(volumeBarPointA4);
volumeBarPointB1 = viewPort.fitIntoVisibleArea(volumeBarPointB1);
volumeBarPointB2 = viewPort.fitIntoVisibleArea(volumeBarPointB2);
volumeBarPointB3 = viewPort.fitIntoVisibleArea(volumeBarPointB3);
volumeBarPointB4 = viewPort.fitIntoVisibleArea(volumeBarPointB4);
/* Everything must fit within the Frame. We know that that is equivalent to say that each bar con not be higher than the base of the opposite . */
if (volumeBarPointA2.y < volumeBarPointB1.y) {
volumeBarPointA2.y = volumeBarPointB1.y;
volumeBarPointA3.y = volumeBarPointB1.y;
}
if (volumeBarPointB2.y > volumeBarPointA1.y) {
volumeBarPointB2.y = volumeBarPointA1.y;
volumeBarPointB3.y = volumeBarPointA1.y;
}
/* Now the drawing of the volume bars*/
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointA1.x, volumeBarPointA1.y);
browserCanvasContext.lineTo(volumeBarPointA2.x, volumeBarPointA2.y);
browserCanvasContext.lineTo(volumeBarPointA3.x, volumeBarPointA3.y);
browserCanvasContext.lineTo(volumeBarPointA4.x, volumeBarPointA4.y);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= volumeBar.begin && dateValue <= volumeBar.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 0.40)'; // Current bar accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, 0.40)';
}
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, 0.40)';
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, 0.40)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointB1.x, volumeBarPointB1.y);
browserCanvasContext.lineTo(volumeBarPointB2.x, volumeBarPointB2.y);
browserCanvasContext.lineTo(volumeBarPointB3.x, volumeBarPointB3.y);
browserCanvasContext.lineTo(volumeBarPointB4.x, volumeBarPointB4.y);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= volumeBar.begin && dateValue <= volumeBar.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, 0.40)'; // Current candle accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, 0.40)';
}
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, 0.40)';
}
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, 0.40)';
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= volumeBar.begin && dateValue <= volumeBar.end) {
let buyInfo = {
baseWidth: volumeBarPointA4.x - volumeBarPointA1.x,
topWidth: volumeBarPointA3.x - volumeBarPointA2.x,
height: volumeBarPointA2.y - volumeBarPointA1.y
};
let sellInfo = {
baseWidth: volumeBarPointB4.x - volumeBarPointB1.x,
topWidth: volumeBarPointB3.x - volumeBarPointB2.x,
height: volumeBarPointB2.y - volumeBarPointB1.y
};
let currentVolume = {
buyInfo: buyInfo,
sellInfo: sellInfo,
period: timePeriod,
innerVolumeBar: volumeBar
};
volumeChartLayer.container.eventHandler.raiseEvent("Current Volume Info Changed", currentVolume);
}
}
}
}
}
}
@@ -0,0 +1,628 @@
function newVolumeTechnicalAnalisysChartLayer() {
var volumes = [];
let timePeriod = INITIAL_TIME_PERIOD;
var plotArea = newPlotArea();
var plotAreaFrame = newPlotArea();
var datetime = INITIAL_DATE;
var volumeTechnicalAnalisysChartLayer = {
onLayerStatusChanged: onLayerStatusChanged,
onVolumesChanged: onVolumesChanged,
setTimePeriod: setTimePeriod,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
volumeTechnicalAnalisysChartLayer.container = container;
container.displacement.containerName = "Volume Technical Analisys Chart";
container.zoom.containerName = "Volume Technical Analisys Chart";
container.frame.containerName = "Volume Technical Analisys Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let stairsArray = [];
let layerStatus = 'off';
let parentLayerStatus = 'off';
return volumeTechnicalAnalisysChartLayer;
function initialize(exchange, market, index, dailyFiles, chartLayersPanel) {
marketId = market;
exchangeId = exchange;
marketIndex = index;
dailyFilesCursor = dailyFiles;
layerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.VOLUME_STAIRS);
parentLayerStatus = chartLayersPanel.getLayerStatus(chartLayersPanel.layerNames.VOLUME);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onLayerStatusChanged(eventData) {
if (eventData.layer === 'Volume') {
parentLayerStatus = eventData.status;
}
if (eventData.layer === 'Volume Stairs') {
layerStatus = eventData.status;
}
}
function onVolumesChanged(newVolumes) {
volumes = newVolumes;
recalculateScaleX();
recalculatePatterns();
recalculateScaleY();
}
function setTimePeriod(period) {
timePeriod = period;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function draw() {
if (layerStatus !== 'on') { return; }
if (parentLayerStatus === 'off') { return; }
this.container.frame.draw();
plotPatternChart();
}
function recalculatePatterns() {
if (layerStatus === 'off') { return; }
if (parentLayerStatus === 'off') { return; }
/* Finding stairs */
stairsArray = [];
let buyUpStairs;
let buyDownStairs;
let sellUpStairs;
let sellDownStairs;
for (let i = 0; i < volumes.length - 1; i++) {
let currentVolume = volumes[i];
let nextVolume = volumes[i + 1];
/* buy volume going up */
if (currentVolume.amountBuy < nextVolume.amountBuy) {
if (buyUpStairs === undefined) {
buyUpStairs = newVolumeStairs();
buyUpStairs.type = 'buy';
buyUpStairs.direction = 'up';
buyUpStairs.barsCount = 2;
buyUpStairs.begin = currentVolume.begin;
buyUpStairs.end = nextVolume.end;
buyUpStairs.firstAmount = currentVolume.amountBuy;
buyUpStairs.lastAmount = nextVolume.amountBuy;
} else {
buyUpStairs.barsCount++;
buyUpStairs.end = nextVolume.end;
buyUpStairs.lastAmount = nextVolume.amountBuy;
}
} else {
if (buyUpStairs !== undefined) {
if (buyUpStairs.barsCount > 2) {
stairsArray.push(buyUpStairs);
}
buyUpStairs = undefined;
}
}
/* buy volume going down */
if (currentVolume.amountBuy > nextVolume.amountBuy) {
if (buyDownStairs === undefined) {
buyDownStairs = newVolumeStairs();
buyDownStairs.type = 'buy';
buyDownStairs.direction = 'down';
buyDownStairs.barsCount = 2;
buyDownStairs.begin = currentVolume.begin;
buyDownStairs.end = nextVolume.end;
buyDownStairs.firstAmount = currentVolume.amountBuy;
buyDownStairs.lastAmount = nextVolume.amountBuy;
} else {
buyDownStairs.barsCount++;
buyDownStairs.end = nextVolume.end;
buyDownStairs.lastAmount = nextVolume.amountBuy;
}
} else {
if (buyDownStairs !== undefined) {
if (buyDownStairs.barsCount > 2) {
stairsArray.push(buyDownStairs);
}
buyDownStairs = undefined;
}
}
/* sell volume going up */
if (currentVolume.amountSell < nextVolume.amountSell) {
if (sellUpStairs === undefined) {
sellUpStairs = newVolumeStairs();
sellUpStairs.type = 'sell';
sellUpStairs.direction = 'up';
sellUpStairs.barsCount = 2;
sellUpStairs.begin = currentVolume.begin;
sellUpStairs.end = nextVolume.end;
sellUpStairs.firstAmount = currentVolume.amountSell;
sellUpStairs.lastAmount = nextVolume.amountSell;
} else {
sellUpStairs.barsCount++;
sellUpStairs.end = nextVolume.end;
sellUpStairs.lastAmount = nextVolume.amountSell;
}
} else {
if (sellUpStairs !== undefined) {
if (sellUpStairs.barsCount > 2) {
stairsArray.push(sellUpStairs);
}
sellUpStairs = undefined;
}
}
/* sell volume going down */
if (currentVolume.amountSell > nextVolume.amountSell) {
if (sellDownStairs === undefined) {
sellDownStairs = newVolumeStairs();
sellDownStairs.type = 'sell';
sellDownStairs.direction = 'down';
sellDownStairs.barsCount = 2;
sellDownStairs.begin = currentVolume.begin;
sellDownStairs.end = nextVolume.end;
sellDownStairs.firstAmount = currentVolume.amountSell;
sellDownStairs.lastAmount = nextVolume.amountSell;
} else {
sellDownStairs.barsCount++;
sellDownStairs.end = nextVolume.end;
sellDownStairs.lastAmount = nextVolume.amountSell;
}
} else {
if (sellDownStairs !== undefined) {
if (sellDownStairs.barsCount > 2) {
stairsArray.push(sellDownStairs);
}
sellDownStairs = undefined;
}
}
}
}
function recalculateScaleX() {
var minValue = {
x: EARLIEST_DATE.valueOf()
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf()
};
plotArea.initializeX(
minValue,
maxValue,
volumeTechnicalAnalisysChartLayer.container.frame.width
);
plotAreaFrame.initializeX(
minValue,
maxValue,
volumeTechnicalAnalisysChartLayer.container.frame.width
);
}
function recalculateScaleY() {
var minValue = {
y: 0
};
var maxValue = {
y: 0
};
let timePeriodRatio = ONE_DAY_IN_MILISECONDS / timePeriod;
maxValue.y = marketIndex.maxVolume() / (timePeriodRatio / 10);
plotArea.initializeY(
minValue,
maxValue,
viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y
);
plotAreaFrame.initializeY(
minValue,
maxValue,
volumeTechnicalAnalisysChartLayer.container.frame.height
);
}
function plotPatternChart() {
let opacity = '0.25';
let visibleHeight = viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topLeft.y;
let frameCorner1 = {
x: 0,
y: 0
};
let frameCorner2 = {
x: volumeTechnicalAnalisysChartLayer.container.frame.width,
y: volumeTechnicalAnalisysChartLayer.container.frame.height
};
/* Now the transformations. */
frameCorner1 = transformThisPoint(frameCorner1, volumeTechnicalAnalisysChartLayer.container.frame.container);
frameCorner2 = transformThisPoint(frameCorner2, volumeTechnicalAnalisysChartLayer.container.frame.container);
let frameHeightInViewPort = frameCorner2.y - frameCorner1.y;
if (stairsArray.length > 0) {
for (var i = 0; i < stairsArray.length; i++) {
stairs = stairsArray[i];
let volumeBarPointA1;
let volumeBarPointA2;
let volumeBarPointA3;
let volumeBarPointA4;
if (stairs.type === 'buy') {
function calculateBuys(plot, height) {
volumeBarPointA1 = {
x: stairs.begin + timePeriod / 2,
y: 0
};
volumeBarPointA2 = {
x: stairs.begin + timePeriod / 2,
y: stairs.firstAmount * 2
};
volumeBarPointA3 = {
x: stairs.end - timePeriod / 2,
y: stairs.lastAmount * 2
};
volumeBarPointA4 = {
x: stairs.end - timePeriod / 2,
y: 0
};
volumeBarPointA1 = plot.inverseTransform(volumeBarPointA1, height);
volumeBarPointA2 = plot.inverseTransform(volumeBarPointA2, height);
volumeBarPointA3 = plot.inverseTransform(volumeBarPointA3, height);
volumeBarPointA4 = plot.inverseTransform(volumeBarPointA4, height);
volumeBarPointA1 = transformThisPoint(volumeBarPointA1, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointA2 = transformThisPoint(volumeBarPointA2, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointA3 = transformThisPoint(volumeBarPointA3, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointA4 = transformThisPoint(volumeBarPointA4, volumeTechnicalAnalisysChartLayer.container);
if (volumeBarPointA4.x < viewPort.visibleArea.bottomLeft.x || volumeBarPointA1.x > viewPort.visibleArea.bottomRight.x) {
return false;
}
return true;
}
if (calculateBuys(plotAreaFrame, volumeTechnicalAnalisysChartLayer.container.frame.height) === false) { continue; } // We try to see if it fits in the visible area.
if (volumeBarPointA1.y > viewPort.visibleArea.bottomLeft.y && frameHeightInViewPort > visibleHeight * 2 / 3) {
if (calculateBuys(plotArea, visibleHeight) === false) { continue; } // We snap t to the view port.
/* Now we set the real value of y. */
volumeBarPointA1.y = viewPort.visibleArea.bottomRight.y;
volumeBarPointA2.y = viewPort.visibleArea.bottomRight.y - stairs.firstAmount * 2 * plotArea.scale.y;
volumeBarPointA3.y = viewPort.visibleArea.bottomRight.y - stairs.lastAmount * 2 * plotArea.scale.y;
volumeBarPointA4.y = viewPort.visibleArea.bottomRight.y;
}
}
let volumeBarPointB1;
let volumeBarPointB2;
let volumeBarPointB3;
let volumeBarPointB4;
if (stairs.type === 'sell') {
function calculateSells(plot, height) {
volumeBarPointB1 = {
x: stairs.begin + timePeriod / 2,
y: height
};
volumeBarPointB2 = {
x: stairs.begin + timePeriod / 2,
y: height - stairs.firstAmount * 2
};
volumeBarPointB3 = {
x: stairs.end - timePeriod / 2,
y: height - stairs.lastAmount * 2
};
volumeBarPointB4 = {
x: stairs.end - timePeriod / 2,
y: height
};
volumeBarPointB1 = plot.inverseTransform2(volumeBarPointB1, height);
volumeBarPointB2 = plot.inverseTransform2(volumeBarPointB2, height);
volumeBarPointB3 = plot.inverseTransform2(volumeBarPointB3, height);
volumeBarPointB4 = plot.inverseTransform2(volumeBarPointB4, height);
volumeBarPointB1 = transformThisPoint(volumeBarPointB1, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointB2 = transformThisPoint(volumeBarPointB2, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointB3 = transformThisPoint(volumeBarPointB3, volumeTechnicalAnalisysChartLayer.container);
volumeBarPointB4 = transformThisPoint(volumeBarPointB4, volumeTechnicalAnalisysChartLayer.container);
}
calculateSells(plotAreaFrame, volumeTechnicalAnalisysChartLayer.container.frame.height); // We try to see if it fits in the visible area.
if (volumeBarPointB1.y < viewPort.visibleArea.topLeft.y && frameHeightInViewPort > visibleHeight * 2 / 3) {
calculateSells(plotArea, visibleHeight); // We snap it to the view port.
/* Now we set the real value of y. */
volumeBarPointB1.y = viewPort.visibleArea.topLeft.y;
volumeBarPointB2.y = viewPort.visibleArea.topLeft.y + stairs.firstAmount * 2 * plotArea.scale.y;
volumeBarPointB3.y = viewPort.visibleArea.topLeft.y + stairs.lastAmount * 2 * plotArea.scale.y;
volumeBarPointB4.y = viewPort.visibleArea.topLeft.y;
}
}
/* Everything must fit within the visible area */
if (stairs.type === 'buy') {
volumeBarPointA1 = viewPort.fitIntoVisibleArea(volumeBarPointA1);
volumeBarPointA2 = viewPort.fitIntoVisibleArea(volumeBarPointA2);
volumeBarPointA3 = viewPort.fitIntoVisibleArea(volumeBarPointA3);
volumeBarPointA4 = viewPort.fitIntoVisibleArea(volumeBarPointA4);
} else {
volumeBarPointB1 = viewPort.fitIntoVisibleArea(volumeBarPointB1);
volumeBarPointB2 = viewPort.fitIntoVisibleArea(volumeBarPointB2);
volumeBarPointB3 = viewPort.fitIntoVisibleArea(volumeBarPointB3);
volumeBarPointB4 = viewPort.fitIntoVisibleArea(volumeBarPointB4);
}
/* Now the drawing */
if (stairs.type === 'buy') {
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointA1.x, volumeBarPointA1.y);
browserCanvasContext.lineTo(volumeBarPointA2.x, volumeBarPointA2.y);
browserCanvasContext.lineTo(volumeBarPointA3.x, volumeBarPointA3.y);
browserCanvasContext.lineTo(volumeBarPointA4.x, volumeBarPointA4.y);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= stairs.begin && dateValue <= stairs.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + opacity + ')'; // Current bar accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')';
}
} else {
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + opacity + ')';
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + opacity + ')';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
} else {
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(volumeBarPointB1.x, volumeBarPointB1.y);
browserCanvasContext.lineTo(volumeBarPointB2.x, volumeBarPointB2.y);
browserCanvasContext.lineTo(volumeBarPointB3.x, volumeBarPointB3.y);
browserCanvasContext.lineTo(volumeBarPointB4.x, volumeBarPointB4.y);
browserCanvasContext.closePath();
if (datetime !== undefined) {
let dateValue = datetime.valueOf();
if (dateValue >= stairs.begin && dateValue <= stairs.end) {
browserCanvasContext.fillStyle = 'rgba(255, 233, 31, ' + opacity + ')'; // Current candle accroding to time
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')';
}
} else {
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + opacity + ')';
}
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + opacity + ')';
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
}
}
}
+117
View File
@@ -0,0 +1,117 @@
/*
The chart space is where all the charts live. What this space contains is a type of object we call Time Machine. A Time Machine is a cointainer of
charts objects. The idea is simple, all the chart objects are ploted according to the time of the Time Machine object. When the time of the Time Machine
changes, then all charts in it are replotted with the corresponging data.
*/
function newChartSpace() {
var chartSpace = {
container: undefined,
draw: draw,
timeMachines: [],
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
chartSpace.container = container;
chartSpace.container.frame.width = browserCanvas.width * 1000;
chartSpace.container.frame.height = browserCanvas.height * 100;
container.displacement.containerName = "Chart Space";
container.zoom.containerName = "Chart Space";
container.frame.containerName = "Chart Space";
container.frame.position.x = browserCanvas.width / 2 - chartSpace.container.frame.width / 2;
container.frame.position.y = browserCanvas.height / 2 - chartSpace.container.frame.height / 2;
container.isZoomeable = false;
container.isDraggeable = false;
return chartSpace;
function initialize() {
/* We create the first of many possible time machines that could live at the Chart Space. */
var timeMachine = newTimeMachine();
timeMachine.container.displacement.parentDisplacement = this.container.displacement;
timeMachine.container.zoom.parentZoom = this.container.zoom;
timeMachine.container.frame.parentFrame = this.container.frame;
timeMachine.container.parentContainer = this.container;
/* We make the time machine a little bit smaller than the current space. */
timeMachine.container.frame.width = this.container.frame.width * 1;
timeMachine.container.frame.height = this.container.frame.height * 1;
timeMachine.container.frame.position.x = this.container.frame.width / 2 - timeMachine.container.frame.width / 2;
timeMachine.container.frame.position.y = this.container.frame.height / 2 - timeMachine.container.frame.height / 2;
timeMachine.initialize();
this.timeMachines.push(timeMachine);
}
function draw() {
chartSpace.container.frame.draw(false, false);
/* When we draw the chart space, that means we draw all the time machines in it. */
for (var i = 0; i < chartSpace.timeMachines.length; i++ ) {
var timeMachine = chartSpace.timeMachines[i];
timeMachine.draw();
}
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
/* Now we see which is the inner most container that has it */
for (var i = 0; i < this.timeMachines.length; i++) {
container = this.timeMachines[i].getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
}
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
}
+197
View File
@@ -0,0 +1,197 @@
function getSideDays(timePeriod) {
if (timePeriod < _1_HOUR_IN_MILISECONDS) {
daysOnSides = 1;
}
if (timePeriod === _1_HOUR_IN_MILISECONDS) {
daysOnSides = 2;
}
if (timePeriod === _3_HOURS_IN_MILISECONDS) {
daysOnSides = 6;
}
if (timePeriod === _6_HOURS_IN_MILISECONDS) {
daysOnSides = 10;
}
if (timePeriod === _12_HOURS_IN_MILISECONDS) {
daysOnSides = 12;
}
return daysOnSides;
}
function getCondenseFactor(timePeriod) {
switch (timePeriod) {
case _1_MINUTE_IN_MILISECONDS: return 1;
case _5_MINUTES_IN_MILISECONDS: return 5;
case _10_MINUTES_IN_MILISECONDS: return 10;
case _30_MINUTES_IN_MILISECONDS: return 50;
case _1_HOUR_IN_MILISECONDS: return 100;
}
}
function getTransparenceFactor(timePeriod) {
switch (timePeriod) {
case _1_MINUTE_IN_MILISECONDS: return "0.12";
case _5_MINUTES_IN_MILISECONDS: return "0.10";
case _10_MINUTES_IN_MILISECONDS: return "0.08";
case _30_MINUTES_IN_MILISECONDS: return "0.06";
case _1_HOUR_IN_MILISECONDS: return "0.04";
}
}
function recalculatePeriod(zoomLevel) {
if (zoomLevel > 600) {
return _1_MINUTE_IN_MILISECONDS;
}
if (zoomLevel > 300) {
return _1_MINUTE_IN_MILISECONDS;
}
if (zoomLevel > 120) {
return _1_MINUTE_IN_MILISECONDS;
}
if (zoomLevel > 60) {
return _5_MINUTES_IN_MILISECONDS;
}
if (zoomLevel > 15) {
return _5_MINUTES_IN_MILISECONDS;
}
if (zoomLevel > - 7) {
return _10_MINUTES_IN_MILISECONDS;
}
if (zoomLevel > - 13) {
return _30_MINUTES_IN_MILISECONDS;
}
if (zoomLevel > - 24) {
return _1_HOUR_IN_MILISECONDS;
}
if (zoomLevel > - 25) {
return _3_HOURS_IN_MILISECONDS;
}
if (zoomLevel > - 26) {
return _6_HOURS_IN_MILISECONDS;
}
if (zoomLevel > - 27) {
return _12_HOURS_IN_MILISECONDS;
}
if (zoomLevel <= - 27) {
return ONE_DAY_IN_MILISECONDS;
}
}
function checkIfMoreTradesAreNeeded(trades, container, plotArea, marketTrades, callBackFunction) {
/*
To know when to load more trades, we will see were the first candle is in relation to the viewport.
If we are too close to the visible area, we will request more trades, so as to have more candles ready.
If we are to far, we will request a new set of trades with fewer than the ones we have, so as to have les candles.
*/
let firstTrade = trades[0];
let lastTrade = trades[trades.length - 1];
let firstTradePoint = {
x: firstTrade.datetime.valueOf(),
y: 0
};
let lastTradePoint = {
x: lastTrade.datetime.valueOf(),
y: 0
};
firstTradePoint = plotArea.inverseTransform(firstTradePoint, container.frame.height);
firstTradePoint = transformThisPoint(firstTradePoint, container);
lastTradePoint = plotArea.inverseTransform(lastTradePoint, container.frame.height);
lastTradePoint = transformThisPoint(lastTradePoint, container);
let totalDistance = lastTradePoint.x - firstTradePoint.x; // Is the screen distance between the first and last trade.
let tradesDistance = lastTrade.id - firstTrade.id; // It is the distance in Id between the first and last trade.
let viewPortWidth = viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x;
/*
Knowing the distance in the screen and the distance in Ids from the first and last trade, can leads us to know the distance in ids, from
where the first trade is, to where it should be.
To do that we will first calculate how many trades are currently fitting in the viewport.
*/
let viewPortTrades = Math.round(viewPortWidth * tradesDistance / totalDistance);
let estimatedFisrtTradeId = firstTrade.id;
let estimatedLastTradeId = lastTrade.id;
let needToRequestMoreTrades = false;
if (firstTradePoint.x > viewPort.visibleArea.bottomLeft.x - viewPortWidth) {
/* We need more trades before the first one. The first trade should be less than 2 times the view port width. Lets estimate an Id for a trade just there. */
estimatedFisrtTradeId = firstTrade.id - viewPortTrades;
needToRequestMoreTrades = true;
}
if (firstTradePoint.x < viewPort.visibleArea.bottomLeft.x - viewPortWidth * 2) {
/* We need more get rid of some trades after the first one. */
estimatedFisrtTradeId = firstTrade.id + viewPortTrades;
needToRequestMoreTrades = true;
}
if (lastTradePoint.x < viewPort.visibleArea.bottomRight.x + viewPortWidth) {
/* We need more trades after the last one. */
estimatedLastTradeId = lastTrade.id + viewPortTrades;
needToRequestMoreTrades = true;
}
if (lastTradePoint.x > viewPort.visibleArea.bottomRight.x + viewPortWidth * 2) {
/* We need more get rid of some trades before the last one. */
estimatedLastTradeId = lastTrade.id - viewPortTrades;
needToRequestMoreTrades = true;
}
if (needToRequestMoreTrades === true) {
marketTrades.getTradesById(estimatedFisrtTradeId, estimatedLastTradeId, callBackFunction);
}
}
+41
View File
@@ -0,0 +1,41 @@
function newContainer() {
var container = {
frame: undefined,
displacement: undefined,
zoom: undefined,
eventHandler: undefined,
parentContainer: undefined,
isDraggeable: true,
isZoomeable: true,
isClickeable: false,
initialize: initialize
};
return container;
function initialize() {
var frame = newFrame();
frame.initialize();
this.frame = frame;
frame.container = container;
var eventHandler = newEventHandler();
eventHandler.initialize();
this.eventHandler = eventHandler;
var displacement = newDisplacement();
this.displacement = displacement;
displacement.container = container;
var zoom = newZoom();
this.zoom = zoom;
zoom.container = container;
}
}
+154
View File
@@ -0,0 +1,154 @@
function newDailyFilesCursor() {
const CURSOR_SIZE = 30;
let dailyFiles = new Map;
let cursorDate = new Date(INITIAL_DATE);
let dailyFilesCursor = {
setDatetime: setDatetime,
dailyFiles: undefined,
initialize: initialize
}
dailyFilesCursor.dailyFiles = dailyFiles;
let marketId;
let exchangeId;
let server = newFileServer();
return dailyFilesCursor;
function initialize(exchange, market, callBackFunction) {
marketId = market;
exchangeId = exchange;
server.initialize();
getFiles(callBackFunction);
}
function setDatetime(datetime) {
if (datetime === undefined) { return; }
cursorDate = datetime;
getFiles();
collectGarbage();
}
function getFiles(callBackFunction) {
let i = 0;
let j = 0;
let dateString;
getNextFile();
function getNextFile() {
let targetDate = new Date(cursorDate);
targetDate.setDate(targetDate.getDate() + j);
if (j === 0) { j++; }
else {
if (j < 0) {
j = -j;
j++;
}
else {
j = -j;
}
}
dateString = targetDate.getUTCFullYear() + '-' + pad(targetDate.getUTCMonth() + 1, 2) + '-' + pad(targetDate.getUTCDate(), 2);
let currentDay = Math.trunc((new Date()).valueOf() / (24 * 60 * 60 * 1000));
let targetDay = Math.trunc(targetDate.valueOf() / (24 * 60 * 60 * 1000));
if (targetDay > currentDay) {
controlLoop();
} else {
if (dailyFilesCursor.dailyFiles.get(dateString) === undefined) {
server.getDailyFile(exchangeId, marketId, targetDate, newDailyFilesReady)
} else {
controlLoop();
}
}
}
function newDailyFilesReady(dailyFileReceived) {
dailyFilesCursor.dailyFiles.set(dateString, dailyFileReceived);
controlLoop();
}
function controlLoop() {
if (j === 3) { // We call the callBack after we have the first few files.
if (callBackFunction !== undefined) {
callBackFunction();
if (marketId === INITIAL_DEFAULT_MARKET) { // This is when we dont need a splash screen anymore!
splashScreenNeeded = false;
}
}
}
i++;
if (i < CURSOR_SIZE) {
getNextFile();
}
}
}
function collectGarbage() {
date = removeTime(cursorDate);
let minDate = date.valueOf() - CURSOR_SIZE / 2 * 24 * 60 * 60 * 1000;
let maxDate = date.valueOf() + CURSOR_SIZE / 2 * 24 * 60 * 60 * 1000;
for (let key of dailyFilesCursor.dailyFiles.keys()) {
let keyDate = new Date(key);
if (keyDate.valueOf() < minDate || keyDate.valueOf() > maxDate) {
dailyFilesCursor.dailyFiles.delete(key);
}
}
}
}
+127
View File
@@ -0,0 +1,127 @@
/* The Dashboard is the root object that contains all the other stuff in it. Some of that stuff is visible, some other is invisible. */
var canvas;
var markets;
var viewPort = newViewPort();
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.
const INITIAL_DEFAULT_MARKET = 2; // This is the market that will be shown when loading the site for the first time.
const WIDHTER_VOLUME_BAR_BASE_FACTOR = 2.5;
const LESS_WIDHTER_VOLUME_BAR_TOP_FACTOR = 1 / 4;
const ONE_DAY_IN_MILISECONDS = 24 * 60 * 60 * 1000;
const _12_HOURS_IN_MILISECONDS = 12 * 60 * 60 * 1000;
const _6_HOURS_IN_MILISECONDS = 6 * 60 * 60 * 1000;
const _3_HOURS_IN_MILISECONDS = 3 * 60 * 60 * 1000;
const _1_HOUR_IN_MILISECONDS = 1 * 60 * 60 * 1000;
const _30_MINUTES_IN_MILISECONDS = 30 * 60 * 1000;
const _10_MINUTES_IN_MILISECONDS = 10 * 60 * 1000;
const _5_MINUTES_IN_MILISECONDS = 5 * 60 * 1000;
const _1_MINUTE_IN_MILISECONDS = 1 * 60 * 1000;
const EARLIEST_DATE = new Date(2014, 0, 18, 4, 26, 8);
const FONT_ASPECT_RATIO = 0.60;
const CHART_ASPECT_RATIO = 1 / 10;
const INITIAL_TIME_PERIOD = _10_MINUTES_IN_MILISECONDS;
/* Here we list the valid Time Periods: */
const PERIOD_24_HS = "24-hs";
const PERIOD_12_HS = "12-hs";
const PERIOD_06_HS = "06-hs";
const PERIOD_03_HS = "03-hs";
const PERIOD_01_HS = "01-hs";
const PERIOD_30_MIN = "30-min";
const PERIOD_10_MIN = "10-min";
const PERIOD_05_MIN = "05-min";
const PERIOD_01_MIN = "01-min";
var newDate = new Date();
newDate.setMilliseconds(0);
newDate.setDate(newDate.getDate() - 90);
const INITIAL_DATE = newDate;
var maxDate = new Date();
maxDate.setMilliseconds(0);
maxDate.setDate(maxDate.getDate() + 10);
const MAX_PLOTABLE_DATE = maxDate;
var smallBalls = []; // Array of small circles for debugging purposes.
function dashboardStart() {
setTimeout(start, DEBUG_START_UP_DELAY);
}
function start() {
const ID_EXCHANGE_POLONIEX = 1;
var server = newFileServer();
server.initialize();
server.getMarkets(ID_EXCHANGE_POLONIEX, onResultSetReady);
function onResultSetReady(resultSet) {
markets = new Map();
var totalRows = resultSet.length;
for (var i = 0; i < totalRows; i++) {
var row = resultSet[i];
/* We move the information from the result set to an order object, and use that from now on. */
market = {
id: row[0],
assetA: row[1],
assetB: row[2]
};
markets.set(market.id, market);
}
canvas = newCanvas();
canvas.initialize();
}
}
function drawSmallBall() {
for (var i = 0; i < smallBalls.length; i++) {
x = smallBalls[i][0];
y = smallBalls[i][1];
radius = smallBalls[i][2];
fillStyle = smallBalls[i][3];
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(x, y);
browserCanvasContext.arc(x, y, radius, 0, Math.PI * 2, true);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = fillStyle;
browserCanvasContext.fill();
}
}
+81
View File
@@ -0,0 +1,81 @@
/*
We call displacement to the offset we can produce to the object which the displcement object is is a child from.
The displacement is a vector that displaces everything static drawn on on the context of the parent object.
*/
function newDisplacement() {
var displacement = {
containerName: "", // This is for debugging purposes only.
parentDisplacement: undefined, // Here we store the displacement object of the parent cointainer, if exists.
container: undefined,
x: 0, // This is the actual x displacement.
y: 0, // This is the actual y displacement.
displace: displace,
undisplaceThisPoint: undisplaceThisPoint,
displaceThisPoint: displaceThisPoint
};
return displacement;
function displace(amountX, amountY) {
/* First we check if by allowing this displacement we would produce the current frame to be beyond its limit. */
tempDisplacement = newDisplacement();
tempDisplacement.x = amountX;
tempDisplacement.y = amountY;
if (this.container.frame.canYouMoveHere(tempDisplacement)) {
/* Now we displace */
displacement.x = displacement.x + amountX;
displacement.y = displacement.y + amountY;
return true;
}
return false;
}
function displaceThisPoint(point) {
if (this.parentDisplacement !== undefined) {
point = this.parentDisplacement.displaceThisPoint(point);
}
point.x = point.x + displacement.x;
point.y = point.y + displacement.y;
return point;
}
function undisplaceThisPoint(point) {
if (this.parentDisplacement !== undefined) {
point = this.parentDisplacement.undisplaceThisPoint(point);
}
point.x = point.x - displacement.x;
point.y = point.y - displacement.y;
return point;
}
}
+46
View File
@@ -0,0 +1,46 @@
function newEventHandler() {
var eventHandler = {
containerName: "", // This is for debugging purposes only.
parentEventHandler: undefined, // Here we store the parent cointainer zoom object.
listenToEvent: listenToEvent,
raiseEvent: raiseEvent,
initialize: initialize
};
var eventHandlers = []; // Here we store all the functions we will call when an event is comming.
return eventHandler;
function initialize() {
}
function listenToEvent(eventType, handler, extraData) {
eventHandlers.push([eventType, handler, extraData]);
}
function raiseEvent(eventType, event) {
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];
handler(event, extraData);
}
}
}
}
+74
View File
@@ -0,0 +1,74 @@
/*
This module will acts as a dinamic file cache for each market. It works like this:
1. It is always listening to the DATETIME the user is browsing and dinamically adjusts the cache according to that, meaning that it loads more files or
unload files that at far in time and unlikely to be needed.
2. It is always listening to the PERIOD of candles and other visual objects to dinamically adjust the cache loading or unloading files according to that.
3. It is also listening to the Layers Panel to only keep in the cache the files of visible layers.
*/
function newFileCache() {
const FILE_TYPES = {
candles: {
layers: ["candles"],
periods: [PERIOD_24_HS, PERIOD_12_HS, PERIOD_06_HS, PERIOD_03_HS, PERIOD_01_HS]
},
volumes: {
layers: ["volumes"],
periods: [PERIOD_24_HS, PERIOD_12_HS, PERIOD_06_HS, PERIOD_03_HS, PERIOD_01_HS]
}
}
let fileCache = {
getFile: getFile,
initialize: initialize
}
let exchange;
let market;
let files = new Map;
return fileCache;
function initialize(pExchange, pMarket, callBackFunction) {
exchange = pExchange;
market = pMarket;
let server;
server = newFileServer();
server.initialize();
server.getMarketIndexCandles(exchangeId, marketId, onCandlesReady);
function onCandlesReady(data) {
dataCache.candles = data;
server.getMarketIndexVolumes(exchangeId, marketId, onVolumesReady);
function onVolumesReady(data) {
dataCache.volumes = data;
callBackFunction();
}
}
}
function getFile(pName, pPeriod, pDatetime) {
}
}
+391
View File
@@ -0,0 +1,391 @@
/*
This module gets the requested file from the appropiate cloud storage account.
*/
function newFileServer() {
const EXCHANGE_NAME = "Poloniex";
const CANDLES_FOLDER_NAME = "Candles";
const CANDLES_ONE_MIN = "One-Min";
const VOLUMES_FOLDER_NAME = "Volumes";
const VOLUMES_ONE_MIN = "One-Min";
var httpServer; // This is the object that allows as to make calls to the fileServer.
var fileServer = {
getOrderBook: getOrderBook,
getAggregattedOrderBook: getAggregattedOrderBook,
getMarkets: getMarkets,
getLastTrades: getLastTrades,
getTrades: getTrades,
getMarketIndexCandles: getMarketIndexCandles,
getMarketIndexVolumes: getMarketIndexVolumes,
getAllTimes: getAllTimes,
getDailyFile: getDailyFile,
initialize: initialize
};
const account = 'aadata';
const sas = '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D';
const fileUri = 'https://' + account + '.file.core.windows.net';
let fileService;
let charlyFileService;
let carolFileService;
let bruceFileService;
let oliviaFileService;
const genericBot = {
account: 'aadata',
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D',
fileUri: 'https://' + 'aadata' + '.file.core.windows.net'
};
const charlyBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=rc&se=2018-12-31T02:33:36Z&st=2018-02-01T18:33:36Z&spr=https&sig=xFTcopdKq0f60wl2iuukbtIpcLwxZVKzlw5BzpJfo5g%3D',
fileUri: 'https://' + 'aacharly' + '.file.core.windows.net'
};
const carolBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D',
fileUri: 'https://' + 'aadata' + '.file.core.windows.net'
};
const bruceBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-31T02:32:04Z&st=2018-02-01T18:32:04Z&spr=https&sig=SbZI6bvAE1MBxna2NOvfgMroPFZNjAyaHUsAPvh11hg%3D',
fileUri: 'https://' + 'aabruce' + '.file.core.windows.net'
};
const oliviaBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=rl&se=2018-12-31T02:34:32Z&st=2018-02-01T18:34:32Z&spr=https,http&sig=24UJjGDVpPrHjhBoZtt3iKj4sxgenfSV4VTJD2v0q1U%3D',
fileUri: 'https://' + 'aaolivia' + '.file.core.windows.net'
};
return fileServer;
function initialize() {
httpServer = new XMLHttpRequest();
fileService = AzureStorage.createFileServiceWithSas(fileUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
charlyFileService = AzureStorage.createFileServiceWithSas(charlyBot.fileUri, charlyBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
carolFileService = AzureStorage.createFileServiceWithSas(carolBot.fileUri, carolBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
bruceFileService = AzureStorage.createFileServiceWithSas(bruceBot.fileUri, bruceBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
oliviaFileService = AzureStorage.createFileServiceWithSas(oliviaBot.fileUri, oliviaBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
}
function getMarketIndexCandles(exchangeId, marketId, callBackFunction) {
//let fileName = '' + market.assetA + '_' + market.assetB + '.json';
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let filePath = EXCHANGE_NAME + "/Output/" + CANDLES_FOLDER_NAME + "/24-hs-Market";
oliviaFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getMarketIndexVolumes(exchangeId, marketId, callBackFunction) {
//let fileName = '' + market.assetA + '_' + market.assetB + '.json';
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let filePath = EXCHANGE_NAME + "/Output/" + VOLUMES_FOLDER_NAME + "/24-hs-Market";
oliviaFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getAllTimes(exchangeId, marketId, callBackFunction) {
let fileName = exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'all-times', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getDailyFile(exchangeId, marketId, date, callBackFunction) {
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let dateForPath = date.getUTCFullYear() + '/' + pad(date.getUTCMonth() + 1, 2) + '/' + pad(date.getUTCDate(), 2);
let filePath = EXCHANGE_NAME + "/Output/" + CANDLES_FOLDER_NAME + '/' + CANDLES_ONE_MIN + '/' + dateForPath;
bruceFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getMarkets(exchangeId, callBackFunction) {
let fileName = "Markets_" + exchangeId + "_USDT_BTC" + ".json";
fileService.getFileToText('data', 'other-files', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
var fileString = text;
let cleanString = fileString;
/* Dont know why but sometimes files comes with a first characater that is not supposed to be there and you can not see it at the file opened with notepad */
if (fileString[0] !== "[") {
cleanString = '';
for (let i = 1; i < fileString.length; i++) {
cleanString = cleanString + fileString[i];
}
}
let data = JSON.parse(cleanString);
callBackFunction(data);
}
}
}
function getAggregattedOrderBook(exchangeId, marketId, date, callBackFunction) {
let stringDate = date.getFullYear() + '/' + pad(date.getMonth() + 1, 2) + '/' + pad(date.getDate(), 2) + '/' + pad(date.getHours(), 2) + '/' + pad(date.getMinutes(), 2);
let fileName = stringDate + "/" + exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'aggregatted-order-books', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getOrderBook(exchangeId, marketId, date, callBackFunction) {
let stringDate = date.getFullYear() + '/' + pad(date.getMonth() + 1, 2) + '/' + pad(date.getDate(), 2) + '/' + pad(date.getHours(), 2) + '/' + pad(date.getMinutes(), 2);
let fileName = stringDate + "/" + exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'order-books', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getLastTrades(marketId, exchangeId, callBackFunction) {
requestTrades();
function requestTrades() {
httpServer = new XMLHttpRequest();
httpServer.open('GET', "lastTrades/" + marketId + "/" + exchangeId, true);
httpServer.send();
httpServer.onreadystatechange = onHttpServerResponded;
function onHttpServerResponded(err) {
checkResponse(callBackFunction);
}
}
}
function getTrades(idBegin, idEnd, marketId, exchangeId, callBackFunction) {
requestTrades();
function requestTrades() {
httpServer = new XMLHttpRequest();
httpServer.open('GET', "trades/" + marketId + "/" + exchangeId + "/" + idBegin + "/" + idEnd, true);
httpServer.send();
httpServer.onreadystatechange = onHttpServerResponded;
function onHttpServerResponded(err) {
checkResponse(callBackFunction);
}
}
}
function checkResponse(callBackFunction) {
if (httpServer.status === 404) {
let data = JSON.parse("[]");
callBackFunction(data);
}
if (httpServer.readyState === 4 && httpServer.status === 200) {
let data;
try {
data = JSON.parse(httpServer.responseText);
} catch (err) {
data = JSON.parse("[]");
}
callBackFunction(data);
}
}
}
+387
View File
@@ -0,0 +1,387 @@
function newFileServer() {
const EXCHANGE_NAME = "Poloniex";
const CANDLES_FOLDER_NAME = "Candles";
const CANDLES_ONE_MIN = "One-Min";
const VOLUMES_FOLDER_NAME = "Volumes";
const VOLUMES_ONE_MIN = "One-Min";
var httpServer; // This is the object that allows as to make calls to the fileServer.
var fileServer = {
getOrderBook: getOrderBook,
getAggregattedOrderBook: getAggregattedOrderBook,
getMarkets: getMarkets,
getLastTrades: getLastTrades,
getTrades: getTrades,
getMarketIndexCandles: getMarketIndexCandles,
getMarketIndexVolumes: getMarketIndexVolumes,
getAllTimes: getAllTimes,
getDailyFile: getDailyFile,
initialize: initialize
};
const account = 'aadata';
const sas = '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D';
const fileUri = 'https://' + account + '.file.core.windows.net';
let fileService;
let charlyFileService;
let carolFileService;
let bruceFileService;
let oliviaFileService;
const genericBot = {
account: 'aadata',
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D',
fileUri: 'https://' + 'aadata' + '.file.core.windows.net'
};
const charlyBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=rc&se=2018-12-31T02:33:36Z&st=2018-02-01T18:33:36Z&spr=https&sig=xFTcopdKq0f60wl2iuukbtIpcLwxZVKzlw5BzpJfo5g%3D',
fileUri: 'https://' + 'aacharly' + '.file.core.windows.net'
};
const carolBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-01T00:09:44Z&st=2017-12-01T13:09:44Z&spr=https,http&sig=J60UlQuUqh9Hd1Pm0PqIF6yari3D3TkGEz1fSNQJWks%3D',
fileUri: 'https://' + 'aadata' + '.file.core.windows.net'
};
const bruceBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=r&se=2018-12-31T02:32:04Z&st=2018-02-01T18:32:04Z&spr=https&sig=SbZI6bvAE1MBxna2NOvfgMroPFZNjAyaHUsAPvh11hg%3D',
fileUri: 'https://' + 'aabruce' + '.file.core.windows.net'
};
const oliviaBot = {
sas: '?sv=2017-04-17&ss=f&srt=sco&sp=rl&se=2018-12-31T02:34:32Z&st=2018-02-01T18:34:32Z&spr=https,http&sig=24UJjGDVpPrHjhBoZtt3iKj4sxgenfSV4VTJD2v0q1U%3D',
fileUri: 'https://' + 'aaolivia' + '.file.core.windows.net'
};
return fileServer;
function initialize() {
httpServer = new XMLHttpRequest();
fileService = AzureStorage.createFileServiceWithSas(fileUri, sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
charlyFileService = AzureStorage.createFileServiceWithSas(charlyBot.fileUri, charlyBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
carolFileService = AzureStorage.createFileServiceWithSas(carolBot.fileUri, carolBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
bruceFileService = AzureStorage.createFileServiceWithSas(bruceBot.fileUri, bruceBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
oliviaFileService = AzureStorage.createFileServiceWithSas(oliviaBot.fileUri, oliviaBot.sas).withFilter(new AzureStorage.ExponentialRetryPolicyFilter());
}
function getMarketIndexCandles(exchangeId, marketId, callBackFunction) {
//let fileName = '' + market.assetA + '_' + market.assetB + '.json';
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let filePath = EXCHANGE_NAME + "/Output/" + CANDLES_FOLDER_NAME + "/Multi-Period-Market/24-hs";
oliviaFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getMarketIndexVolumes(exchangeId, marketId, callBackFunction) {
//let fileName = '' + market.assetA + '_' + market.assetB + '.json';
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let filePath = EXCHANGE_NAME + "/Output/" + VOLUMES_FOLDER_NAME + "/Multi-Period-Market/24-hs";
oliviaFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getAllTimes(exchangeId, marketId, callBackFunction) {
let fileName = exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'all-times', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getDailyFile(exchangeId, marketId, date, callBackFunction) {
let fileName = '' + 'USDT' + '_' + 'BTC' + '.json';
let dateForPath = date.getUTCFullYear() + '/' + pad(date.getUTCMonth() + 1, 2) + '/' + pad(date.getUTCDate(), 2);
let filePath = EXCHANGE_NAME + "/Output/" + CANDLES_FOLDER_NAME + '/' + CANDLES_ONE_MIN + '/' + dateForPath;
bruceFileService.getFileToText('data', filePath, fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
let data;
if (err) {
data = JSON.parse("[]");
} else {
try {
data = JSON.parse(text);
} catch (err) {
data = JSON.parse("[]");
}
}
callBackFunction(data);
}
}
function getMarkets(exchangeId, callBackFunction) {
let fileName = "Markets_" + exchangeId + "_USDT_BTC" + ".json";
fileService.getFileToText('data', 'other-files', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
var fileString = text;
let cleanString = fileString;
/* Dont know why but sometimes files comes with a first characater that is not supposed to be there and you can not see it at the file opened with notepad */
if (fileString[0] !== "[") {
cleanString = '';
for (let i = 1; i < fileString.length; i++) {
cleanString = cleanString + fileString[i];
}
}
let data = JSON.parse(cleanString);
callBackFunction(data);
}
}
}
function getAggregattedOrderBook(exchangeId, marketId, date, callBackFunction) {
let stringDate = date.getFullYear() + '/' + pad(date.getMonth() + 1, 2) + '/' + pad(date.getDate(), 2) + '/' + pad(date.getHours(), 2) + '/' + pad(date.getMinutes(), 2);
let fileName = stringDate + "/" + exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'aggregatted-order-books', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getOrderBook(exchangeId, marketId, date, callBackFunction) {
let stringDate = date.getFullYear() + '/' + pad(date.getMonth() + 1, 2) + '/' + pad(date.getDate(), 2) + '/' + pad(date.getHours(), 2) + '/' + pad(date.getMinutes(), 2);
let fileName = stringDate + "/" + exchangeId + "_" + marketId + ".json";
fileService.getFileToText('data', 'order-books', fileName, undefined, onFileReceived);
function onFileReceived(err, text, response) {
if (err) {
let data = JSON.parse("[]");
callBackFunction(data);
} else {
let data = JSON.parse(text);
callBackFunction(data);
}
}
}
function getLastTrades(marketId, exchangeId, callBackFunction) {
requestTrades();
function requestTrades() {
httpServer = new XMLHttpRequest();
httpServer.open('GET', "lastTrades/" + marketId + "/" + exchangeId, true);
httpServer.send();
httpServer.onreadystatechange = onHttpServerResponded;
function onHttpServerResponded(err) {
checkResponse(callBackFunction);
}
}
}
function getTrades(idBegin, idEnd, marketId, exchangeId, callBackFunction) {
requestTrades();
function requestTrades() {
httpServer = new XMLHttpRequest();
httpServer.open('GET', "trades/" + marketId + "/" + exchangeId + "/" + idBegin + "/" + idEnd, true);
httpServer.send();
httpServer.onreadystatechange = onHttpServerResponded;
function onHttpServerResponded(err) {
checkResponse(callBackFunction);
}
}
}
function checkResponse(callBackFunction) {
if (httpServer.status === 404) {
let data = JSON.parse("[]");
callBackFunction(data);
}
if (httpServer.readyState === 4 && httpServer.status === 200) {
let data;
try {
data = JSON.parse(httpServer.responseText);
} catch (err) {
data = JSON.parse("[]");
}
callBackFunction(data);
}
}
}
+99
View File
@@ -0,0 +1,99 @@
/*
The Floating Space is the place where floating elements like balls, live and are rendered. This space has its own physics, preventing balls to overlap.
*/
var balls; // This is the array of balls being displayed
function newFloatingSpace() {
var floatingSpace = {
physicsLoop: physicsLoop,
balls: [],
initialize: initialize
};
return floatingSpace;
function initialize() {
balls = []; // We initialize this in order to start the calculations in a clean way.
}
function physicsLoop() {
/* This function makes all the calculations to apply phisycs on all objects in this space. */
for (var i = 0; i < balls.length; i++) {
var ball = balls[i];
/* Change position based on speed */
ball.currentPosition.x = ball.currentPosition.x + ball.currentSpeed.x;
ball.currentPosition.y = ball.currentPosition.y + ball.currentSpeed.y;
/* Apply some friction to desacelerate */
ball.currentSpeed.x = ball.currentSpeed.x * ball.friction; // Desaceleration factor.
ball.currentSpeed.y = ball.currentSpeed.y * ball.friction; // Desaceleration factor.
// Gives a minimun speed towards their taget.
if (ball.currentPosition.x < ball.targetPosition.x) {
ball.currentSpeed.x = ball.currentSpeed.x + .005;
} else {
ball.currentSpeed.x = ball.currentSpeed.x - .005;
}
if (ball.currentPosition.y < ball.targetPosition.y) {
ball.currentSpeed.y = ball.currentSpeed.y + .005;
} else {
ball.currentSpeed.y = ball.currentSpeed.y - .005;
}
// The radius also have a target.
if (ball.currentRadius < ball.targetRadius) {
ball.currentRadius = ball.currentRadius + .5;
} else {
ball.currentRadius = ball.currentRadius - .5;
}
/* Collision Control */
for (var k = i + 1; k < balls.length; k++) {
if (colliding(balls[i], balls[k])) {
resolveCollision(balls[k], balls[i]);
}
}
/* Calculate repulsion force produced by all other balls */
repulsionForce(i);
gravityForce(ball);
}
for (var i = 0; i < balls.length; i++) {
var ball = balls[i];
ball.drawBackground();
}
for (var i = 0; i < balls.length; i++) {
var ball = balls[balls.length - i - 1];
//var ball = balls[i];
ball.drawForeground();
}
}
}
+598
View File
@@ -0,0 +1,598 @@
function newFrame() {
const PANEL_CORNERS_RADIOUS = 10;
const TITLE_BAR_HEIGHT = 14; // this must be grater than radius
var frame = {
containerName: "", // This is for debugging purposes only.
parentFrame: undefined, // Here we store the parent cointainer zoom object.
width: browserCanvas.width,
height: browserCanvas.height,
position: undefined,
getBodyHeight: getBodyHeight,
draw: draw,
container: undefined,
frameThisPoint: frameThisPoint, // This function changes the actual frame coordinate system to the screen coordinate system.
unframeThisPoint: unframeThisPoint,
fitIntoFrame: fitIntoFrame,
isThisPointHere: isThisPointHere, // This function return true is the point received as parameter lives within this frame.
isInViewPort: isInViewPort,
canYouMoveHere: canYouMoveHere,
canYouZoomHere: canYouZoomHere,
initialize: initialize
};
return frame;
function initialize() {
var position = {
x: 0,
y: 0
};
this.position = position;
}
function getBodyHeight() {
return frame.height - TITLE_BAR_HEIGHT;
}
function isInViewPort() {
point1 = {
x: 0,
y: 0
};
point3 = {
x: frame.width,
y: frame.height
};
/* Now the transformations. */
point1 = transformThisPoint(point1, frame.container);
point3 = transformThisPoint(point3, frame.container);
if (point1.x < viewPort.visibleArea.topRight.x && point1.y < viewPort.visibleArea.bottomRight.y && point3.x > viewPort.visibleArea.bottomLeft.x && point3.y > viewPort.visibleArea.topLeft.y ) {
return true;
} else {
return false;
}
}
function fitIntoFrame(point) {
/* Here we check the boundaries of the resulting points, so they dont go out of the visible area. */
if (point.x > frame.width) {
point.x = frame.width;
}
if (point.x < 0) {
point.x = 0;
}
if (point.y > frame.height) {
point.y = frame.height;
}
if (point.y < 0) {
point.y = 0;
}
return point;
}
function frameThisPoint(point) {
if (this.parentFrame !== undefined) {
point = this.parentFrame.frameThisPoint(point);
}
point.x = point.x + frame.position.x;
point.y = point.y + frame.position.y;
return point;
}
function unframeThisPoint(point) {
if (this.parentFrame !== undefined) {
point = this.parentFrame.unframeThisPoint(point);
}
point.x = point.x - this.position.x;
point.y = point.y - this.position.y;
return point;
}
function canYouMoveHere(tempDisplacement) {
/*
The current frame has a position and a displacement. We need to check that none of the boundaries points of the frame fall outside of its container frame.
First we apply the theoreticall displacement.
*/
point1 = {
x: this.position.x,
y: this.position.y
};
point2 = {
x: this.position.x + this.width,
y: this.position.y
};
point3 = {
x: this.position.x + this.width,
y: this.position.y + this.height
};
point4 = {
x: this.position.x,
y: this.position.y + this.height
};
/* Now the transformations. */
if (this.parentFrame !== undefined) { // If there is not a parent then there is no point to check bounderies.
point1 = this.parentFrame.frameThisPoint(point1);
point2 = this.parentFrame.frameThisPoint(point2);
point3 = this.parentFrame.frameThisPoint(point3);
point4 = this.parentFrame.frameThisPoint(point4);
/* We apply the temporary displacement. */
point1 = tempDisplacement.displaceThisPoint(point1);
point2 = tempDisplacement.displaceThisPoint(point2);
point3 = tempDisplacement.displaceThisPoint(point3);
point4 = tempDisplacement.displaceThisPoint(point4);
/* We add the actual displacement. */
point1 = this.container.displacement.displaceThisPoint(point1);
point2 = this.container.displacement.displaceThisPoint(point2);
point3 = this.container.displacement.displaceThisPoint(point3);
point4 = this.container.displacement.displaceThisPoint(point4);
/* We add the actual zoom. */
point1 = this.container.zoom.zoomThisPoint(point1);
point2 = this.container.zoom.zoomThisPoint(point2);
point3 = this.container.zoom.zoomThisPoint(point3);
point4 = this.container.zoom.zoomThisPoint(point4);
if (this.parentFrame.isThisPointHere(point1) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point2) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point3) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point4) === false) {
return false;
}
}
return true;
}
function canYouZoomHere(tempZoom) {
point1 = {
x: this.position.x,
y: this.position.y
};
point2 = {
x: this.position.x + this.width,
y: this.position.y
};
point3 = {
x: this.position.x + this.width,
y: this.position.y + this.height
};
point4 = {
x: this.position.x,
y: this.position.y + this.height
};
/* Now the transformations. */
if (this.parentFrame !== undefined) { // If there is not a parent then there is no point to check bounderies.
point1 = this.parentFrame.frameThisPoint(point1);
point2 = this.parentFrame.frameThisPoint(point2);
point3 = this.parentFrame.frameThisPoint(point3);
point4 = this.parentFrame.frameThisPoint(point4);
/* We add the actual displacement. */
point1 = this.container.displacement.displaceThisPoint(point1);
point2 = this.container.displacement.displaceThisPoint(point2);
point3 = this.container.displacement.displaceThisPoint(point3);
point4 = this.container.displacement.displaceThisPoint(point4);
/* We temp zoom. */
point1 = tempZoom.zoomThisPoint(point1);
point2 = tempZoom.zoomThisPoint(point2);
point3 = tempZoom.zoomThisPoint(point3);
point4 = tempZoom.zoomThisPoint(point4);
if (this.parentFrame.isThisPointHere(point1) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point2) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point3) === false) {
return false;
}
if (this.parentFrame.isThisPointHere(point4) === false) {
return false;
}
}
return true;
}
function isThisPointHere(point, outsideViewPort) { // The second parameter is usefull when you want to check a point that you already know is outside the viewport.
/* We need not to modify the point received, so me make a copy of it. */
var checkPoint = {
x: point.x,
y: point.y
};
/* The point received is on the screen coordinates system, which already has zoom and displacement applied. We need to remove the zoom and displacement
in order to have the point on the containers coordinate system and be able to compare it with its dimmensions. */
if (outsideViewPort === true) {
checkPoint = this.container.zoom.unzoomThisPoint(checkPoint);
checkPoint = this.container.displacement.undisplaceThisPoint(checkPoint);
checkPoint = this.container.frame.unframeThisPoint(checkPoint);
} else {
checkPoint = unTransformThisPoint(checkPoint, frame.container);
}
/* Now we check if the resulting point is whin the current Frame. */
if (checkPoint.x < 0 || checkPoint.y < 0 || checkPoint.x > frame.width || checkPoint.y > frame.height) {
/* The point received is not in this frame */
return false;
} else {
/* The point is within this frame. */
return true;
}
}
function draw(drawGrid, drawBorders, drawBackground) {
if (drawBorders === true) {
borders();
}
if (drawGrid === true) {
grid();
}
if (drawBackground === true) {
background();
}
}
function background() {
borderPoint1 = {
x: PANEL_CORNERS_RADIOUS,
y: PANEL_CORNERS_RADIOUS
};
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
};
titleBarPoint1 = {
x: 0,
y: TITLE_BAR_HEIGHT
};
titleBarPoint2 = {
x: frame.width,
y: TITLE_BAR_HEIGHT
};
/* 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(255, 255, 255, 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(54, 54, 54, 0.75)';
browserCanvasContext.stroke();
/* We paint the title bar now */
browserCanvasContext.fillStyle = 'rgba(37, 107, 219, 0.75)';
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(titleBarPoint1.x, titleBarPoint1.y);
browserCanvasContext.lineTo(borderPoint1.x - PANEL_CORNERS_RADIOUS, borderPoint1.y);
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(titleBarPoint2.x, titleBarPoint2.y);
browserCanvasContext.closePath();
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 0.1;
browserCanvasContext.strokeStyle = 'rgba(12, 64, 148, 0.75)';
browserCanvasContext.stroke();
/* print the title */
let labelPoint;
let fontSize = 10;
browserCanvasContext.font = fontSize + 'px Courier New';
let label = frame.containerName;
let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO;
let yOffset = (TITLE_BAR_HEIGHT - fontSize) / 2 + 2;
labelPoint = {
x: frame.width / 2 - xOffset,
y: TITLE_BAR_HEIGHT - yOffset
};
labelPoint = frame.frameThisPoint(labelPoint);
browserCanvasContext.fillStyle = 'rgba(240, 240, 240, 1)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
function borders() {
/* Lest get the important points of the drawing so as to apply the needed transformations. */
point1 = {
x: 0,
y: 0
};
point2 = {
x: frame.width,
y: 0
};
point3 = {
x: frame.width,
y: frame.height
};
point4 = {
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);
/* Lets start the drawing. */
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();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
function grid(smallLines) {
if (smallLines === true) {
/* Small Lines */
var step = frame.width / 100;
browserCanvasContext.beginPath();
for (var i = 0; i < frame.width; i = i + step) {
for (var j = 0; j < frame.height; j = j + step) {
let point1 = {
x: 0,
y: j
};
let point2 = {
x: frame.width,
y: j
};
point1 = transformThisPoint(point1, frame.container);
point2 = transformThisPoint(point2, frame.container);
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
}
let point3 = {
x: frame.width,
y: frame.height
};
let point4 = {
x: 0,
y: frame.height
};
point3 = transformThisPoint(point3, frame.container);
point4 = transformThisPoint(point4, frame.container);
browserCanvasContext.moveTo(point3.x, point3.y);
browserCanvasContext.lineTo(point4.x, point4.y);
}
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 0.1)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
/* Main Lines */
var step = frame.width / 20;
browserCanvasContext.beginPath();
for (var i = 0; i < frame.width; i = i + step) {
for (var j = 0; j < frame.height; j = j + step) {
let point1 = {
x: 0,
y: j
};
let point2 = {
x: frame.width,
y: j
};
point1 = transformThisPoint(point1, frame.container);
point2 = transformThisPoint(point2, frame.container);
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
}
let point3 = {
x: i,
y: 0
};
let point4 = {
x: i,
y: frame.height
};
point3 = transformThisPoint(point3, frame.container);
point4 = transformThisPoint(point4, frame.container);
browserCanvasContext.moveTo(point3.x, point3.y);
browserCanvasContext.lineTo(point4.x, point4.y);
}
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(100, 100, 100, 0.2)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
+110
View File
@@ -0,0 +1,110 @@
/*
* Linear regression curve. SRC: Gekko
*/
//var log = require('../../core/log');
var LRCIndicator = function(settings) {
this.input = 'price';
this.depth = settings;
this.result = false;
this.age = 0;
this.history = [];
this.x = [];
/*
* Do not use array(depth) as it might not be implemented
*/
for (var i = 0; i < this.depth; i++) {
this.history.push(0.0);
this.x.push(i);
}
// log.debug("Created LRC indicator with h: ", this.depth);
}
LRCIndicator.prototype.update = function(price) {
// We need sufficient history to get the right result.
if(this.result === false && this.age < this.depth) {
this.history[this.age] = price;
this.age++;
this.result = false;
// log.debug("Waiting for sufficient age: ", this.age, " out of ", this.depth);
return;
}
this.age++;
// shift history
for (var i = 0; i < (this.depth - 1); i++) {
this.history[i] = this.history[i+1];
}
this.history[this.depth-1] = price;
this.calculate(price);
// log.debug("Checking LRC: ", this.result.toFixed(8), "\tH: ", this.age);
return;
}
/*
* Least squares linear regression fitting.
*/
function linreg(values_x, values_y) {
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var count = 0;
/*
* We'll use those variables for faster read/write access.
*/
var x = 0;
var y = 0;
var values_length = values_x.length;
if (values_length != values_y.length) {
throw new Error('The parameters values_x and values_y need to have same size!');
}
/*
* Nothing to do.
*/
if (values_length === 0) {
return [ [], [] ];
}
/*
* Calculate the sum for each of the parts necessary.
*/
for (var v = 0; v < values_length; v++) {
x = values_x[v];
y = values_y[v];
sum_x += x;
sum_y += y;
sum_xx += x*x;
sum_xy += x*y;
count++;
}
/*
* Calculate m and b for the formula: y = x * m + b
*
*/
var m = (count*sum_xy - sum_x*sum_y) / (count*sum_xx - sum_x*sum_x);
var b = (sum_y/count) - (m*sum_x)/count;
return [m, b];
}
/*
* Handle calculations
*/
LRCIndicator.prototype.calculate = function(price) {
// get the reg
var reg = linreg(this.x, this.history);
// y = a * x + b
this.result = ((this.depth-1) * reg[0]) + reg[1];
}
+79
View File
@@ -0,0 +1,79 @@
function newMarketIndex() {
let marketIndex = {
candles: undefined,
volumes: undefined,
maxRate: maxRate,
maxVolume: maxVolume,
initialize: initialize
}
let marketId;
let exchangeId;
return marketIndex;
function initialize(exchange, market, callBackFunction) {
marketId = market;
exchangeId = exchange;
let server;
server = newFileServer();
server.initialize();
server.getMarketIndexCandles(exchangeId, marketId, onCandlesReady);
function onCandlesReady(data) {
marketIndex.candles = data;
server.getMarketIndexVolumes(exchangeId, marketId, onVolumesReady);
function onVolumesReady(data) {
marketIndex.volumes = data;
callBackFunction();
}
}
}
function maxRate() {
let maxValue = 0;
for (var i = 0; i < marketIndex.candles.length; i++) {
let currentMax = marketIndex.candles[i][1];
if (maxValue < currentMax) {
maxValue = currentMax;
}
}
return maxValue;
}
function maxVolume() {
let maxValue = 0;
for (var i = 0; i < marketIndex.volumes.length; i++) {
let currentMax = marketIndex.volumes[i][0] + marketIndex.volumes[i][1];
if (maxValue < currentMax) {
maxValue = currentMax;
}
}
return maxValue;
}
}
+366
View File
@@ -0,0 +1,366 @@
function newMarketTrades() {
/*
The object mantains the information of the trades of a certain market.
It is initially empty until it receives a request for trades from any of its clients. It tries to serve the request with already existing trades,
in case that request was done before, and if it wasnt, then it makes the request to a Server object and store the trades received.
*/
var trades = new Map(); // Here we store all the trades that we received from the server.
var marketId;
var exchangeId;
var server;
let minId = 100000000000000;
let maxId = 0;
let absoluteMinId;
let absoluteMaxId;
var marketTrades = {
getTradesByDateRange: getTradesByDateRange,
getTradesById: getTradesById,
initialize: initialize
};
let processingRequest = false;
const MAX_TRADES_PER_SERVER_REQUEST = 100000;
let targetBeginId;
let targetEndId;
let currentRecursion = 0;
const MAX_RECURSIVE_CALLS = 6;
let leftOrRight = "left";
//tradesSegments = []; // We will devide the whole history of this market in segments of 100K records, so as to fetch from the server no more than 100K a the time.
return marketTrades;
function initialize(exchange, market, callBackFunction) {
exchangeId = exchange;
marketId = market;
/* First we initialize the server that will allow us to retrieve data. */
server = newFileServer();
server.initialize();
trades = new Map();
server.getLastTrades(marketId, exchangeId, onLastTradesReady);
function onLastTradesReady(resultSet) {
addTrades(resultSet);
callBackFunction();
}
}
function getTradesById(initialId, finalId, callBackFunction) {
/*
if (processingRequest === true) {
return;
} else {
processingRequest = true;
}
*/
currentRecursion = 0;
processRequest(initialId, finalId, callBackFunction);
}
async function processRequest(initialId, finalId, callBackFunction) {
if (absoluteMinId !== undefined && initialId < absoluteMinId) {
initialId = absoluteMinId; // We can not deal with ids before the absolute minimun in existence.
}
if (absoluteMaxId !== undefined && finalId > absoluteMaxId) {
finalId = absoluteMaxId; // We can not deal with ids after the absolute maximun in existence.
}
/*
At this point we already have a collection of trades, and we know the min and max id of the collection.
We need to see if the requested range is within the collection or we need to ask for more trades to the Server.
*/
/* First scenario is that the range requested is fully inside of the set of trades we already have */
if (initialId >= minId && finalId <= maxId) {
respondWithTradesById(); // We already have the trades needed.
return;
}
/*
Second scenario is that there is a gap between the range requested and the set of trades we already have.
In this case the current set is obsolete and must be replaced by a new one.
*/
if (finalId < minId || initialId > maxId) {
trades = new Map();
minId = 100000000000000;
maxId = 0;
targetBeginId = undefined;
targetEndId = undefined;
if (finalId - initialId > MAX_TRADES_PER_SERVER_REQUEST) {
targetBeginId = initialId;
targetEndId = finalId;
initialId = initialId + Math.trunc((finalId - initialId) / 2 - MAX_TRADES_PER_SERVER_REQUEST / 2);
finalId = initialId + MAX_TRADES_PER_SERVER_REQUEST;
}
server.getTrades(initialId, finalId, marketId, exchangeId, onServerSecondResponse);
return;
}
/* The third and last scenario is when there is no gap, and the range requested expands the current set. */
checkBeforeTheCurrentRange();
function checkBeforeTheCurrentRange() {
if (initialId < minId) {
if (minId - initialId > MAX_TRADES_PER_SERVER_REQUEST) {
targetBeginId = initialId;
initialId = minId - MAX_TRADES_PER_SERVER_REQUEST;
}
server.getTrades(initialId, minId - 1, marketId, exchangeId, onServerFirstResponse);
} else {
checkAfterTheCurrentRange();
}
}
function onServerFirstResponse(resultSet) {
if (resultSet.length > 0) {
let firstTradeId = resultSet[0][0][1];
if (initialId < firstTradeId) {
/* This means that there are no more records before the Id received, which transform this id in the absolute minimum. */
absoluteMinId = firstTradeId;
}
addTrades(resultSet);
} else {
absoluteMinId = minId;
}
checkAfterTheCurrentRange();
}
function checkAfterTheCurrentRange() {
if (finalId > maxId) {
if (finalId - maxId > MAX_TRADES_PER_SERVER_REQUEST) {
targetFinalId = finalId;
finalId = maxId + MAX_TRADES_PER_SERVER_REQUEST;
}
server.getTrades(maxId + 1, finalId, marketId, exchangeId, onServerSecondResponse);
} else {
respondWithTradesById();
}
}
function onServerSecondResponse(resultSet) {
if (resultSet.length > 0) {
let lastTradeId = resultSet[resultSet.length - 1][0][1];
if (finalId > lastTradeId) {
/* This means that there are no more records after the Id received, which transform this id in the absolute maximun. */
absoluteMaxId = lastTradeId;
}
addTrades(resultSet);
} else {
absoluteMaxId = maxId;
}
respondWithTradesById();
}
function respondWithTradesById() {
let tradesToReturn = [];
/* We are ready to create an array of the trades for the id range requested. For this we need to scan the whole Trades Map. */
for (let i = initialId; i <= finalId; i++) {
let trade = trades.get(i);
if (trade !== undefined) {
tradesToReturn.push(trade);
}
}
callBackFunction(tradesToReturn);
processingRequest = false;
if (currentRecursion !== MAX_RECURSIVE_CALLS) {
if (leftOrRight === "left") {
leftOrRight = "right";
if (minId > targetBeginId) {
processRequest(targetBeginId, finalId, callBackFunction);
currentRecursion++;
}
if (maxId < targetEndId) {
processRequest(initialId, targetEndId, callBackFunction);
currentRecursion++;
}
} else {
leftOrRight = "left";
if (maxId < targetEndId) {
processRequest(initialId, targetEndId, callBackFunction);
currentRecursion++;
}
if (minId > targetBeginId) {
processRequest(targetBeginId, finalId, callBackFunction);
currentRecursion++;
}
}
}
else {
currentRecursion = 0;
}
}
}
function getTradesByDateRange(datetimeRange, callBackFunction) {
/* So far, we only accept dates range against the current collection of trades we hold here. */
respondToCallerByDateRange();
function respondToCallerByDateRange() {
let tradesToReturn = [];
let begin = datetimeRange.begin.valueOf();
let end = datetimeRange.end.valueOf();
/* We are ready to create an array of the trades for the date requested. For this we need to scan the whole Trades Map. */
for (let i = minId; i <= maxId; i++) {
let trade = trades.get(i);
if (trade !== undefined) {
let now = trade.datetime.valueOf();
if (begin <= now && now < end) {
tradesToReturn.push(trade);
}
}
}
callBackFunction(tradesToReturn);
}
}
function addTrades(resultSet) {
/* Last Trades are asked in reversed order, so we put it here in the correct order as it is going to be consumed */
for (let i = 0; i < resultSet.length; i++) {
let row = resultSet[i];
var trade = newTrade(row[0][1], row[1][1], row[2][1], row[3][1], row[4][1], new Date(row[5][1]));
trades.set(trade.id, trade); // Because it is a map, I don-t need to worry about duplicate records.
if (trade.id < minId) {
minId = trade.id;
}
if (trade.id > maxId) {
maxId = trade.id;
}
}
}
}
+164
View File
@@ -0,0 +1,164 @@
/* This business logic module is responsible for Markets and Assets. */
const MODULE_NAME = "Markets";
var DATA_LAYER_MODULE = require('./Data Layer');
exports.newMarkets = function newMarkets() {
markets = {
getMarketsByExchange: getMarketsByExchange,
getExistingOrNewMarketId: getExistingOrNewMarketId,
createNewAsset: createNewAsset,
createNewMarket: createNewMarket,
initialize: initialize
};
var dataLayer;
return markets;
function initialize() {
dataLayer = DATA_LAYER_MODULE.newDataLayer();
}
function getMarketsByExchange(exchangeId, callBackFunction) {
dataLayer.getMarketsByExchange(exchangeId, onResultSetReady);
function onResultSetReady(resultSet) {
callBackFunction(resultSet);
}
}
function getExistingOrNewMarketId(marketName, market, exchangeId, callBackFunction) {
var assets = marketName.split("_");
var assetCodeA = assets[0];
var assetCodeB = assets[1];
var idAssetA;
var idAssetB;
var marketId;
getIdAssetA();
function getIdAssetA() {
dataLayer.getAssetIdByCodeName(assetCodeA, onIdReady);
function onIdReady(resultSet) {
idAssetA = resultSet.getValue(1, "Id");
if (idAssetA === undefined) {
createNewAsset(assetCodeA, onAssetCreated);
function onAssetCreated(resultSet) {
idAssetA = resultSet.getValue(1, "Id");
getIdAssetB();
}
} else {
getIdAssetB();
}
}
}
function getIdAssetB() {
dataLayer.getAssetIdByCodeName(assetCodeB, onIdReady);
function onIdReady(resultSet) {
idAssetB = resultSet.getValue(1, "Id");
if (idAssetB === undefined) {
createNewAsset(assetCodeB, onAssetCreated);
function onAssetCreated(resultSet) {
idAssetB = resultSet.getValue(1, "Id");
getMarketId();
}
} else {
getMarketId();
}
}
}
function getMarketId() {
dataLayer.getMarketId(idAssetA, idAssetB, exchangeId, onIdReady);
function onIdReady(resultSet) {
marketId = resultSet.getValue(1, "Id");
if (marketId === undefined) {
createNewMarket(exchangeId, idAssetA, idAssetB, onMarketCreated);
function onMarketCreated(resultSet) {
marketId = resultSet.getValue(1, "Id");
respond();
}
} else {
respond();
}
}
}
function respond() {
callBackFunction(marketName, market, marketId);
}
}
function createNewAsset(assetCode, callBackFunction) {
dataLayer.newAsset(assetCode, onIdReady);
function onIdReady(resultSet) {
callBackFunction(resultSet);
}
}
function createNewMarket(exchangeId, idAssetA, idAssetB, callBackFunction) {
dataLayer.newMarket(exchangeId, idAssetA, idAssetB, onIdReady);
function onIdReady(resultSet) {
callBackFunction(resultSet);
}
}
};
+18
View File
@@ -0,0 +1,18 @@
function newOrder(id, type, rate, amountA, amountB, datetimeIn, datetimeOut) {
var order = {
id: id,
rate: rate,
amountA: amountA,
amountB: amountB,
type: type,
datetimeIn: datetimeIn,
datetimeOut: datetimeOut
};
return order;
}
+135
View File
@@ -0,0 +1,135 @@
function newOrderBook() {
/*
The order book object mantains the information of an order book of a certain market.
It is initially empty until it receives a request for orders from any of its clients. It tries to serve the request with already existing orders,
in case that request was done before, and if it wasnt, then it makes the request to a Server object and store the orders received.
*/
var orders = new Map(); // Here we store all the orders that we received from the server.
var marketId;
var server;
var datetimeRange;
var lastRangeLoaded;
var orderBook = {
setDatetimeRange: setDatetimeRange,
getOrdersOf: getOrdersOf,
initialize: initialize
};
return orderBook;
function initialize(market) {
marketId = market;
/* First we initialize the server that will allow us to retrieve data. */
server = newFileServer();
server.initialize();
}
function setDatetimeRange(newDatetimeRange) {
datetimeRange = newDatetimeRange;
lastRangeLoaded = false;
orders = new Map();
}
function getOrdersOf(datetime, callBackFunction) {
/*
Someone is requesting the order book to get updated with information of the datime provided. We request here the new
information the server knows about this datetime, but only if this information we dont have it already.
*/
if (lastRangeLoaded !== true) {
server.getOrderBook(datetimeRange.begin, datetimeRange.end, marketId, onServerResponded);
} else {
respondToCaller();
}
function onServerResponded(resultSet) {
lastRangeLoaded = true;
/*
Fresh data about the order book has just arrived from the server. We need to take it an put it in the right way.
*/
addOrders(resultSet);
respondToCaller();
}
function addOrders(resultSet) {
var totalRows = Object.keys(resultSet).length;
for (var i = 1; i <= totalRows; i++) {
var row = resultSet["row " + i];
/* We move the information from the result set to an order object, and use that from now on. */
var order = newOrder(row.Id, row.Type, row.Rate, row.AmountA, row.AmountB, new Date(row.DatetimeIn), new Date(row.DatetimeOut));
orders.set(order.id, order);
}
}
function respondToCaller() {
var ordersForDatetime = [];
/* We are ready to create an array of the orders for the date requested. For this we need to scan the whole Order Book. */
for (var order of orders.values()) {
var valueOfDatetimeIn = order.datetimeIn.valueOf();
var valueOfDatetimeOut = order.datetimeOut.valueOf();
var valueOfDatetime = datetime.valueOf();
if (valueOfDatetimeIn <= valueOfDatetime && valueOfDatetimeOut > valueOfDatetime) {
ordersForDatetime.push(order);
}
}
callBackFunction(ordersForDatetime);
}
}
}
+113
View File
@@ -0,0 +1,113 @@
function newOrderBookChart() {
/*
This object is responsible for putting all the pieces together that forms an order book chart. These pieces so far are:
1. A snapshot object, with the orders valid for a certain Datetime.
2. A Depht chart object, that is the one that actually plots the chart.
3. The container that allows this object to be dragged around and zoomed in or out.
*/
var datetime;
var datetimeRange;
var orderBookChart = {
setDatetime: setDatetime,
setDatetimeRange: setDatetimeRange,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
orderBookChart.container = container;
container.displacement.containerName = "Order Book Chart";
container.zoom.containerName = "Order Book Chart";
container.frame.containerName = "Order Book Chart";
var orderBookDephChart = newOrderBookDephChart();
var orderBookSnapShot = newOrderBookSnapShot();
var marketId;
return orderBookChart;
function initialize(market) {
marketId = market;
/* We initialize first the Book Depth object. */
orderBookDephChart.container.frame.width = this.container.frame.width * 0.90;
orderBookDephChart.container.frame.height = this.container.frame.height * 0.90;
orderBookDephChart.container.frame.position.x = this.container.frame.width * 0.05;
orderBookDephChart.container.frame.position.y = this.container.frame.height * 0.05;
orderBookDephChart.container.displacement.parentDisplacement = this.container.displacement;
orderBookDephChart.container.zoom.parentZoom = this.container.zoom;
orderBookDephChart.container.frame.parentFrame = this.container.frame;
orderBookDephChart.container.parentContainer = this.container;
orderBookDephChart.initialize(marketId);
/* Then we initialize the Snap Shot object. */
orderBookSnapShot.initialize(marketId);
orderBookSnapShot.eventHandler.listenToEvent('Order Added', orderBookDephChart.addOrder, undefined);
orderBookSnapShot.eventHandler.listenToEvent('Order Removed', orderBookDephChart.removeOrder, undefined);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function setDatetime(newDatetime) {
datetime = newDatetime;
orderBookSnapShot.setDatetime(datetime);
}
function setDatetimeRange(newDatetimeRange) {
datetimeRange = newDatetimeRange;
orderBookSnapShot.setDatetimeRange(datetimeRange);
}
function draw() {
this.container.frame.draw();
orderBookDephChart.draw();
}
}
+466
View File
@@ -0,0 +1,466 @@
function newOrderBookDephChart() {
/*
This object represents the Depth chart and is able to mainain the information needed to plot it and to draw it on the canvas.
*/
var plotArea = newPlotArea();
var orderBookDephChart = {
addOrder: addOrder,
removeOrder: removeOrder,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var aggBidOrders = newAggregatedOrdersArray();
var aggAskOrders = newAggregatedOrdersArray();
var container = newContainer();
container.initialize();
orderBookDephChart.container = container;
container.displacement.containerName = "Order Book Depth Chart";
container.zoom.containerName = "Order Book Depth Chart";
container.frame.containerName = "Order Book Depth Chart";
var bidPoints = [];
var askPoints = [];
var marketId;
return orderBookDephChart;
function initialize(market) {
marketId = market;
aggBidOrders.initialize();
aggAskOrders.initialize();
aggBidOrders.setSortOrder('descending');
aggAskOrders.setSortOrder('ascending');
aggBidOrders.eventHandler.listenToEvent('Array Changed', onBidArrayChanged, undefined);
aggAskOrders.eventHandler.listenToEvent('Array Changed', onAskArrayChanged, undefined);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function addOrder(order) {
if (order.type === 'Bid') {
aggBidOrders.addOrder(order);
} else {
aggAskOrders.addOrder(order);
}
}
function removeOrder(order) {
if (order.type === 'Bid') {
aggBidOrders.removeOrder(order);
} else {
aggAskOrders.removeOrder(order);
}
}
function onBidArrayChanged(array) {
/* In order to avoid glinches while plotting the information of the array, we use a copy of the original that is constantly manipulated. */
newArray = array.slice();
bidPoints = newArray;
recalculateScale();
}
function onAskArrayChanged(array) {
/* In order to avoid glinches while plotting the information of the array, we use a copy of the original that is constantly manipulated. */
newArray = array.slice();
askPoints = newArray;
recalculateScale();
}
function draw() {
if (bidPoints.length > 0 || askPoints.length > 0) {
drawAxis();
drawBackground();
plotChart();
}
}
function drawBackground() {
var market = markets.get(marketId);
var label = market.assetA + " " + market.assetB;
var fontSize = 50;//+ orderBookDephChart.container.zoom.level();
browserCanvasContext.font = fontSize + 'px verdana';
/* Now we transform x on the actual coordinate on the canvas. */
var point = {
x: orderBookDephChart.container.frame.width / 2 - (label.length / 2) * fontSize / 2,
y: orderBookDephChart.container.frame.height * 3 / 8
};
point = transformThisPoint(point, orderBookDephChart.container);
browserCanvasContext.fillStyle = 'rgba(190, 190, 190, 0.25)';
browserCanvasContext.fillText(label, point.x, point.y);
}
function plotChart() {
/*
This function is responsible for plotting the chart onto the browser canvas.
*/
/* The first part of this function will plot BIDs, the second one will plot the ASKs. */
if (bidPoints.length > 0) {
/* We calculate the first points of the chart. These are not points representing orders, but the lower part of the hill plotted. */
var maxBasePoint = {
x: 0 ,
y: orderBookDephChart.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (bidPoints[0].rate - plotArea.min.x) * plotArea.scale.x, // We take the first Order Rate on the array for this.
y: orderBookDephChart.container.frame.height * 5 / 7
};
maxBasePoint = transformThisPoint(maxBasePoint, orderBookDephChart.container);
minBasePoint = transformThisPoint(minBasePoint, orderBookDephChart.container);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var progressiveSum = 0;
var point = minBasePoint;
for (var i = 0; i < bidPoints.length; i++) {
if (bidPoints[i].rate >= plotArea.min.x && bidPoints[i].rate <= plotArea.max.x) {
progressiveSum = progressiveSum + bidPoints[i].amountSum;
point = {
x: (bidPoints[i].rate - plotArea.min.x) * plotArea.scale.x,
y: orderBookDephChart.container.frame.height * 5 / 7 - progressiveSum * plotArea.scale.y
};
var rawPosition = {
x: point.x,
y: point.y
};
point = transformThisPoint(point, orderBookDephChart.container);
browserCanvasContext.lineTo(point.x, point.y);
}
}
browserCanvasContext.lineTo(maxBasePoint.x, point.y);
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(130, 180, 30, 0.50)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(50, 130, 30, 0.50)';
browserCanvasContext.lineWidth = 2;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
/* Ok, Now it is the turn of the ASKs, following is the code that plots them on the chart. */
if (askPoints.length > 0) {
/* We calculate the first point of the chart */
var maxBasePoint = {
x: (plotArea.max.x - plotArea.min.x) * plotArea.scale.x,
y: orderBookDephChart.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (askPoints[0].rate - plotArea.min.x) * plotArea.scale.x, // We take the first Order Rate on the array for this.
y: orderBookDephChart.container.frame.height * 5 / 7
};
maxBasePoint = transformThisPoint(maxBasePoint, orderBookDephChart.container);
minBasePoint = transformThisPoint(minBasePoint, orderBookDephChart.container);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var progressiveSum = 0;
var point = minBasePoint;
for (var i = 0; i < askPoints.length; i++) {
if (askPoints[i].rate >= plotArea.min.x && askPoints[i].rate <= plotArea.max.x) {
progressiveSum = progressiveSum + askPoints[i].amountSum;
point = {
x: (askPoints[i].rate - plotArea.min.x) * plotArea.scale.x,
y: orderBookDephChart.container.frame.height * 5 / 7 - progressiveSum * plotArea.scale.y
};
point = transformThisPoint(point, orderBookDephChart.container);
browserCanvasContext.lineTo(point.x, point.y);
}
}
browserCanvasContext.lineTo(maxBasePoint.x, point.y);
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(180, 130, 30, 0.50)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(130, 50, 30, 0.50)';
browserCanvasContext.lineWidth = 2;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
}
function drawAxis() {
var step = (plotArea.max.x - plotArea.min.x) / 10;
var decimals;
/* Lets identify how many decimals are needed to be displayed. To do that we will chekck when is the first time that two consecutives points in the plotArea are different. */
for (var j = 0; j < 10; j++) {
var diff = (plotArea.min.x + step * 2).toFixed(j) - (plotArea.min.x + step * 1).toFixed(j);
if (diff !== 0 && decimals === undefined) {
decimals = j;
}
}
for (var i = 1; i < 10 ; i++) {
var point = {
x: plotArea.min.x + step * i,
y: orderBookDephChart.container.frame.height * 6 / 7
};
browserCanvasContext.fillStyle = 'rgba(10, 10, 10, 1)';
fontSize = 8;
browserCanvasContext.font = fontSize + 'px verdana';
/* Se the label */
var label = point.x.toFixed(decimals);
/* Now we transform x on the actual coordinate on the canvas. */
point.x = (point.x - plotArea.min.x) * plotArea.scale.x; // Now x represent a coordinate on the canvas.
point = orderBookDephChart.container.frame.frameThisPoint(point);
point = orderBookDephChart.container.displacement.displaceThisPoint(point);
point = orderBookDephChart.container.zoom.zoomThisPoint(point);
browserCanvasContext.fillText(label, point.x, point.y);
}
}
function recalculateScale() {
/* Since the range of the data might change, we must calculate the plotArea everytime new data arrives. */
var minBidRate = bidPoints[bidPoints.length - 1];
var maxBidRate = bidPoints[0];
var minValue = {
x: 1,
y: 1
};
var maxValue = {
x: 1,
y: 1
};
if (bidPoints.length > 0) {
/* X AXIS:
We calculate the min value on x on the plot in this way:
1. We calculate the sum of all orders.
2. Then we find which orders are included in the 75% of the total sum.
3. The last order included will contain the minimun rate we need for the chart.
Regarding the maximun, we just take ask orders that mirrors the bids orders only.
*/
var sum = 0;
for (var i = 0; i < bidPoints.length; i++) {
sum = sum + bidPoints[i].amountSum;
}
target = sum * 0.75;
sum = 0;
lastOrder = bidPoints[0];
for (var i = 0; i < bidPoints.length; i++) {
sum = sum + bidPoints[i].amountSum;
if (sum < target) {
lastOrder = bidPoints[i];
}
}
var minBidRate = lastOrder.rate;
var maxBidRate = bidPoints[0].rate;
minValue.x = minBidRate;
maxValue.x = maxBidRate + (maxBidRate - minBidRate);
/* Y AXIS:
Now that we know which orders are included on the plot, we must see which is the highest value of
all of them. The highest value can be either at an ask, or at a bid order side of the chart.
*/
var selectedItem = bidPoints[0];
var currentMax = 0;
var sum = 0;
for (var i = 0; i < bidPoints.length; i++) {
if (bidPoints[i].rate >= minValue.x && bidPoints[i].rate <= maxValue.x) {
sum = sum + bidPoints[i].amountSum;
}
}
currentMax = sum;
var sum = 0;
for (var i = 0; i < askPoints.length; i++) {
if (askPoints[i].rate >= minValue.x && askPoints[i].rate <= maxValue.x) {
sum = sum + askPoints[i].amountSum;
}
}
if (currentMax < sum) {
currentMax = sum;
}
minValue.y = 0;
maxValue.y = currentMax;
}
plotArea.initialize(
minValue,
maxValue,
orderBookDephChart.container.frame.width,
orderBookDephChart.container.frame.height - orderBookDephChart.container.frame.height * 5 / 7
);
}
}
+140
View File
@@ -0,0 +1,140 @@
function newOrderBookFilesCursor() {
const CURSOR_SIZE = 1440 * 2;
let orderBookFiles = new Map;
let cursorDate = new Date(INITIAL_DATE);
let orderBookFilesCursor = {
setDatetime: setDatetime,
orderBookFiles: undefined,
initialize: initialize
}
orderBookFilesCursor.orderBookFiles = orderBookFiles;
let marketId;
let exchangeId;
let server = newFileServer();
let working = false;
return orderBookFilesCursor;
function initialize(exchange, market) {
marketId = market;
exchangeId = exchange;
server.initialize();
}
function setDatetime(datetime) {
cursorDate = datetime;
//if (working === false) {
getFiles();
working = true
collectGarbage();
//}
}
function getFiles(callBackFunction) {
let i = 0;
let j = 0;
let dateString;
getNextFile();
function getNextFile() {
let targetDate = new Date(cursorDate);
targetDate.setMinutes(targetDate.getMinutes() + j);
if (j === 0) { j++; }
else {
if (j < 0) {
j = -j;
j++;
}
else {
j = -j;
}
}
dateString = targetDate.getFullYear() + '-' + pad(targetDate.getMonth() + 1, 2) + '-' + pad(targetDate.getDate(), 2) + '-' + pad(targetDate.getHours(), 2) + '-' + pad(targetDate.getMinutes(), 2);
if (orderBookFilesCursor.orderBookFiles.get(dateString) === undefined) {
server.getAggregattedOrderBook(exchangeId, marketId, targetDate, newOrderBookFilesReady)
} else {
controlLoop();
}
}
function newOrderBookFilesReady(dailyFileReceived) {
orderBookFilesCursor.orderBookFiles.set(dateString, dailyFileReceived);
controlLoop();
}
function controlLoop() {
i++;
if (i < CURSOR_SIZE) {
getNextFile();
}
else {
if (callBackFunction !== undefined) {
callBackFunction();
}
working = false;
}
}
}
function collectGarbage() {
date = removeTime(cursorDate);
let minDate = date.valueOf() - CURSOR_SIZE / 2 * 60 * 1000;
let maxDate = date.valueOf() + CURSOR_SIZE / 2 * 60 * 1000;
for (let key of orderBookFilesCursor.orderBookFiles.keys()) {
let keyDate = new Date(key + ':00');
if (keyDate.valueOf() < minDate || keyDate.valueOf() > maxDate) {
orderBookFilesCursor.orderBookFiles.delete(key);
}
}
}
}
+107
View File
@@ -0,0 +1,107 @@
function newOrderBookSnapShot() {
/*
This object contains an mantains a snapshot of an order book, which is defined as a collection of all orders valid at a certain moment in time.
Everytime someone sets a new datetime, it goes to an OrderBook object and request new orders for this datetime. At the same time it removes all
orders that are not valid in that new datetime.
For each new order that adds or removes from the snapshot, it raises an event that can be consumed by subscribers.
*/
var orderBook = newOrderBook(); // This is the order book object that is going to provide us with the orders when we shall need them.
var snapshotOrders = new Map(); // These are the orders that are only valid for the time the chart is plotting right now.
var datetime;
var datetimeRange;
var marketId;
var orderBookSnapShot = {
eventHandler: undefined,
getDatetime: getDatetime,
setDatetime: setDatetime,
setDatetimeRange: setDatetimeRange,
initialize: initialize
};
orderBookSnapShot.eventHandler = newEventHandler();
return orderBookSnapShot;
function initialize(market) {
marketId = market;
this.eventHandler.initialize();
orderBook.initialize(marketId);
}
function getDatetime() {
return datetime;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
/* We need to check that all orders that do not belong to this time period must be removed from the snapshot. */
removeOutOfTimeOrders();
/* We also have to get the orders from the order book that belongs to this period and we dont have.*/
orderBook.getOrdersOf(newDatetime, addNewOrders);
}
function setDatetimeRange(newDatetimeRange) {
datetimeRange = newDatetimeRange;
orderBook.setDatetimeRange(datetimeRange);
}
function addNewOrders(ordersToAdd) {
for (var i = 0; i < ordersToAdd.length; i++) {
order = ordersToAdd[i];
var existingOrder = snapshotOrders.get(order.id);
if (existingOrder === undefined) {
snapshotOrders.set(order.id, order);
orderBookSnapShot.eventHandler.raiseEvent('Order Added', order);
}
}
}
function removeOutOfTimeOrders() {
for (var [id, order] of snapshotOrders) {
if (order.datetimeIn.valueOf() > datetime.valueOf() || order.datetimeOut.valueOf() <= datetime.valueOf()) {
snapshotOrders.delete(id);
orderBookSnapShot.eventHandler.raiseEvent('Order Removed', order);
}
}
}
}
+609
View File
@@ -0,0 +1,609 @@
function newBotsLayersPanel() {
const ECOSYSTEM = {
consortium: {
organization: {
name: "AAConsortium",
type: "Non-For-Profit",
displayName: "Advanced Algos Consortium",
location: "Switzerland",
leader: "Luis Molina",
logo: "AAConsortium.jpg"
},
web: "www.AdvancedAlgos.org",
github: {
org: "Advanced Algos",
repos: {
repo: {
name: "AABrowser",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
},
members: {
member: {
organizationName: "AAMasters",
type: "devTeam",
delegate: "Luis Molina",
votes: 1
},
member: {
organizationName: "AAOrion LLC",
type: "cloudHosting",
delegate: "Luis Molina",
votes: 5
},
member: {
organizationName: "AAExchange Masters",
type: "exchangeWrapper",
delegate: "Luis Molina",
votes: 1
}
}
},
devTeams: {
team: {
organization: {
name: "AAMasters",
type: "Open Source Community",
displayName: "AA Masters",
location: "Global",
leader: "Luis Molina",
logo: "AAMasters.jpg"
},
teamMembers: {
member: {
displayName: "Luis Molina",
githubUsername: "Luis-Fernando-Molina",
profilePicture: "Luis.jpg",
tokens: {
percentDistribution: 100,
totalCollected: 121.45
}
}
},
bots: {
bot: {
codeName : "AACharly",
displayName: "Charly",
type: "Extract",
version: {
number: "1.0.0",
status: "Mantained", // Discontinued
},
oputput: {
name: "Trades",
description: "Each file contains trades records of one market at one exchange in a period of time of one minute.",
storageAccount: "aacharly",
filePath: "@Exchange/Output/Trades/@Year/@Month/@Date/@Hour/@Minute",
fileName: "@AssetA_@AssetB.json",
datetimeRange: {
minDatetime: "2015-02-19 19:15:00.000 GMT+0000",
maxDatetime: "2018-02-13 10:10:00.000 GMT+0000"
}
},
processes: {
process: {
name: "Poloniex-Live-Trades",
description: "Retrieves the trades done at the current minute and the previous minute and saves them at the storage account."
},
process: {
name: "Poloniex-Historic-Trades",
description: "Retrieves and saves the historical trades in batches going backwards from the current time until reaching the begining of the market."
},
process: {
name: "Poloniex-Hole-Fixing",
description: "Scans the trades saved by the Live Trades and Historic Trades processes searching for missing records. Once a hole is found on the data set, it patches it by retrieving the missing records from the exchange."
}
},
layers: {
layer: {
displayName: "Trades",
exchangeList: ["Poloniex"],
validPeriods: ["01-min"],
renderer: {
devTeam: "AAMasters",
bot: "AACharly",
moduleName: "TradeList",
target: "Timeline"
}
}
},
directDependencies: {},
directDependents: {
bot: {
devTeam: "AAMasters",
codeName: "AABruce"
},
bot: {
devTeam: "AAMasters",
codeName: "AAOlivia"
}
},
collaboratorsList: [],
github: {
org: "AAMasters",
repos: {
repo: {
name: "AACharly",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
}
},
bot: {
codeName: "AACarol",
displayName: "Carol",
type: "Extract",
version: {
number: "1.0.0",
status: "Mantained", // Discontinued
},
oputput: {
name: "Order Books",
description: "Each file contains the bids and asks positions at each market at a certain moment in time.",
storageAccount: "aacarol",
filePath: "@Exchange/Output/Order-Books/@Year/@Month/@Date/@Hour/@Minute",
fileName: "@AssetA_@AssetB.json",
datetimeRange: {
minDatetime: "2017-02-19 19:15:00.000 GMT+0000",
maxDatetime: "2018-02-13 10:10:00.000 GMT+0000"
}
},
processes: {
process: {
name: "Poloniex-Order-Books",
description: "Retrieves the order books at the current minute and saves them at the storage account."
},
process: {
name: "Aggregated-Order-Books",
description: "Aggregates the order books information to be viewed at different time periods."
},
},
layers: {
layer: {
displayName: "Order Books",
exchangeList: ["Poloniex"],
validPeriods: ["06-hs", "03-hs", "01-hs", "30-min", "10-min", "05-min", "01-min"],
renderer: {
devTeam: "AAMasters",
bot: "AACarol",
moduleName: "OrderBooks",
target: "Timeline"
}
},
layer: {
displayName: "Order Book",
exchangeList: ["Poloniex"],
validPeriods: ["06-hs", "03-hs", "01-hs", "30-min", "10-min", "05-min", "01-min"],
renderer: {
devTeam: "AAMasters",
bot: "AACarol",
moduleName: "OrderBook",
target: "Panel"
}
}
},
directDependencies: {},
directDependents: {},
collaboratorsList: [],
github: {
org: "AAMasters",
repos: {
repo: {
name: "AACarol",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
}
}
}
}
},
clouds: {
cloudHosting: {
codeName: "AAOrion",
organization: {
name: "AAOrion LLC",
type: "Company",
displayName: "Orion",
location: "USA",
leader: "Luis Molina",
logo: "AAOrion.jpg"
},
github: {
org: "AAOrion",
repos: {
repo: {
name: "AzureAAHosting",
description: "AA Azure Hosting Web Site",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
},
underlayingCloud: "Azure",
botsRunning: {
bot: {
devTeam: "AAMasters",
codeName: "AACharly",
version: "1.0.0",
status: "Alive",
stats: {
tokens: {
totalCollected: 532.2442,
totalSpent: 323.455,
currentBalance: 142,
expensesPerHour: 1.44,
maxBalance: 177,
minBalance: 22.44
},
life: {
born: "2015-02-19 19:15:00.000 GMT+0000",
died: undefined,
expectedToRetire: "2019-02-19 19:15:00.000 GMT+0000",
expectedToDie: "2019-03-19 19:15:00.000 GMT+0000"
}
}
},
bot: {
devTeam: "AAMasters",
codeName: "AACarol",
version: "1.0.0",
status: "Alive",
stats: {
tokens: {
totalCollected: 532.2442,
totalSpent: 323.455,
currentBalance: 142,
expensesPerHour: 1.44,
maxBalance: 177,
minBalance: 22.44
},
life: {
born: "2015-02-19 19:15:00.000 GMT+0000",
died: undefined,
expectedToRetire: "2019-02-19 19:15:00.000 GMT+0000",
expectedToDie: "2019-03-19 19:15:00.000 GMT+0000"
}
}
}
},
stats: {
extractionBots: 2,
indicatorsBots: 24,
tradingBots: 12,
suscribers: 230,
apps: 1
}
}
},
exchanges: {
exchangeWrapper: {
codeName: "AAExchange-Masters",
organization: {
name: "AAExchange Masters",
type: "Open Source Project",
displayName: "Exchange Masters",
location: "Global",
leader: "Luis Molina",
logo: "AAExchange-Masters.jpg"
},
exchangesServed: {
exchange: {
name: "Poloniex",
github: {
org: "AAExchange Masters",
repo: {
name: "AAPoloniexWrapper",
description: "Wrapps Poloniex Exchange to be acceced from within the Advanced Algos Ecosystem.",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
},
exchange: {
name: "Binance",
github: {
org: "AAExchange Masters",
repo: {
name: "AABinanceWrapper",
description: "Wrapps Binance Exchange to be acceced from within the Advanced Algos Ecosystem.",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
}
}
}
}
},
apps: {
app: {
organization: {
name: "AAApps Masters",
type: "Open Source Project",
displayName: "Global Ranking",
location: "Global",
leader: "Luis Molina",
logo: "AAApps-Masters.jpg"
},
github: {
org: "AAApps Masters",
repo: {
name: "AAGlobalRanking",
description: "Global Ranking Web Site",
openIssues: 0,
openPullRequests: 0,
contributors: 1
}
},
web: "www.AAGlobalRanking.org",
tradingBots: {
bot: {
devTeam: "AAMasters",
codeName: "AAMichael",
version: "1.0.0",
cloudHosting: "AAOrion",
suscribers: {
subscriber: {
userName: "Trader 007",
subscription: {
type: "Trade-For-Me",
tokensPaid: 20,
expirationDatetime: "2019-03-19 19:15:00.000 GMT+0000"
}
},
subscriber: {
userName: "EliasYofre1",
subscription: {
type: "Buy-Sell-Signals",
tokensPaid: 1,
expirationDatetime: "2019-03-19 19:15:00.000 GMT+0000"
}
}
}
}
}
}
}
};
const BUTTONS_STATES = {
ON: 'on',
INVISIBLE: 'invisible',
OFF: 'off'
};
const LAYER_NAMES = {
CANDLESTICKS: 'Candlesticks',
VOLUME: 'Volume',
ATH: 'All-time Highs and Lows',
HIGH_LOWS: 'High and Lows',
FORECAST: 'Forecast',
ORDER_BOOKS: 'Order Books',
CANDLE_STAIRS: 'Candle Stairs',
VOLUME_STAIRS: 'Volume Stairs',
BUY_SELL_BALANCE: 'Buy Sell Balance',
LINEAR_REGRESION_CURVE: 'Linear Regression Curve'
};
var botsLayersPanel = {
container: undefined,
buttons: undefined,
getLayerStatus: getLayerStatus,
layerNames: LAYER_NAMES,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
container.isDraggeable = true;
container.isZoomeable = false;
botsLayersPanel.container = container;
botsLayersPanel.container.frame.containerName = "Bots Layers Panel";
let isInitialized = false;
let buttons;
return botsLayersPanel;
function initialize() {
this.container.frame.width = 200;
this.container.frame.height = 270;
var position = {
x: viewPort.visibleArea.topLeft.x,
y: viewPort.visibleArea.bottomRight.y - this.container.frame.height
};
this.container.frame.position = position;
var buttonPosition;
var buttonNames = [LAYER_NAMES.CANDLESTICKS, LAYER_NAMES.VOLUME, LAYER_NAMES.ATH, LAYER_NAMES.HIGH_LOWS, LAYER_NAMES.FORECAST, LAYER_NAMES.ORDER_BOOKS, LAYER_NAMES.CANDLE_STAIRS, LAYER_NAMES.VOLUME_STAIRS, LAYER_NAMES.BUY_SELL_BALANCE, LAYER_NAMES.LINEAR_REGRESION_CURVE];
var lastY = 5;
buttons = [];
for (var i = 0; i < buttonNames.length; i++) {
/* Buttons are going to be one at the right of the other. */
var textButton = newTextButton();
textButton.type = buttonNames[i];
textButton.container.displacement.parentDisplacement = this.container.displacement;
textButton.container.zoom.parentZoom = this.container.zoom;
textButton.container.frame.parentFrame = this.container.frame;
textButton.container.parentContainer = this.container;
textButton.initialize();
buttonPosition = { // The first textButton
x: 10,
y: botsLayersPanel.container.frame.height - botsLayersPanel.container.frame.getBodyHeight()
};
textButton.container.frame.position.x = buttonPosition.x;
textButton.container.frame.position.y = buttonPosition.y + lastY;
lastY = lastY + textButton.container.frame.height;
/* We start listening to the buttons click event, so as to know when one was pressed. */
textButton.container.eventHandler.listenToEvent('onMouseClick', buttonPressed, i);
let storedValue = window.localStorage.getItem(textButton.type);
if (storedValue !== null) {
textButton.status = storedValue;
} else {
textButton.status = BUTTONS_STATES.ON;
}
buttons.push(textButton);
let eventData = {
layer: textButton.type,
status: textButton.status
}
botsLayersPanel.container.eventHandler.raiseEvent('Layer Status Changed', eventData);
}
botsLayersPanel.buttons = buttons;
isInitialized = true;
}
function getLayerStatus(layerName) {
for (let i = 0; i < buttons.length; i++) {
let button = buttons[i];
if (button.type === layerName) {
return button.status;
}
}
return BUTTONS_STATES.OFF;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
/* Now we see which is the inner most container that has it */
for (var i = 0; i < this.buttons.length; i++) {
container = this.buttons[i].getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
}
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function buttonPressed(event, buttonPressedIndex) {
switch (botsLayersPanel.buttons[buttonPressedIndex].status) {
case BUTTONS_STATES.ON:
botsLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.INVISIBLE;
break;
case BUTTONS_STATES.INVISIBLE:
botsLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.OFF;
break;
case BUTTONS_STATES.OFF:
botsLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.ON;
break;
}
let eventData = {
layer: botsLayersPanel.buttons[buttonPressedIndex].type,
status: botsLayersPanel.buttons[buttonPressedIndex].status
}
botsLayersPanel.container.eventHandler.raiseEvent('Layer Status Changed', eventData);
window.localStorage.setItem(botsLayersPanel.buttons[buttonPressedIndex].type, botsLayersPanel.buttons[buttonPressedIndex].status);
}
function draw() {
if (isInitialized === false) { return; }
botsLayersPanel.container.frame.draw(false, false, true);
for (var i = 0; i < botsLayersPanel.buttons.length; i++) {
botsLayersPanel.buttons[i].draw();
}
}
}
+232
View File
@@ -0,0 +1,232 @@
function newChartLayersPanel() {
const BUTTONS_STATES = {
ON: 'on',
INVISIBLE: 'invisible',
OFF: 'off'
};
const LAYER_NAMES = {
CANDLESTICKS: 'Candlesticks',
VOLUME: 'Volume',
ATH: 'All-time Highs and Lows',
HIGH_LOWS: 'High and Lows',
FORECAST: 'Forecast',
ORDER_BOOKS: 'Order Books',
CANDLE_STAIRS: 'Candle Stairs',
VOLUME_STAIRS: 'Volume Stairs',
BUY_SELL_BALANCE: 'Buy Sell Balance',
LINEAR_REGRESION_CURVE: 'Linear Regression Curve'
};
var chartLayersPanel = {
container: undefined,
buttons: undefined,
getLayerStatus: getLayerStatus,
layerNames: LAYER_NAMES,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
container.isDraggeable = true;
container.isZoomeable = false;
chartLayersPanel.container = container;
chartLayersPanel.container.frame.containerName = "Chart Layers Panel";
let isInitialized = false;
let buttons;
return chartLayersPanel;
function initialize() {
this.container.frame.width = 200;
this.container.frame.height = 170;
var position = {
x: viewPort.visibleArea.topRight.x - this.container.frame.width,
y: viewPort.visibleArea.bottomRight.y - this.container.frame.height
};
this.container.frame.position = position;
var buttonPosition;
var buttonNames = [LAYER_NAMES.CANDLESTICKS, LAYER_NAMES.VOLUME, LAYER_NAMES.ATH, LAYER_NAMES.HIGH_LOWS, LAYER_NAMES.FORECAST, LAYER_NAMES.ORDER_BOOKS, LAYER_NAMES.CANDLE_STAIRS, LAYER_NAMES.VOLUME_STAIRS, LAYER_NAMES.BUY_SELL_BALANCE, LAYER_NAMES.LINEAR_REGRESION_CURVE];
var lastY = 5;
buttons = [];
for (var i = 0; i < buttonNames.length; i++) {
/* Buttons are going to be one at the right of the other. */
var textButton = newTextButton();
textButton.type = buttonNames[i];
textButton.container.displacement.parentDisplacement = this.container.displacement;
textButton.container.zoom.parentZoom = this.container.zoom;
textButton.container.frame.parentFrame = this.container.frame;
textButton.container.parentContainer = this.container;
textButton.initialize();
buttonPosition = { // The first textButton
x: 10,
y: chartLayersPanel.container.frame.height - chartLayersPanel.container.frame.getBodyHeight()
};
textButton.container.frame.position.x = buttonPosition.x;
textButton.container.frame.position.y = buttonPosition.y + lastY;
lastY = lastY + textButton.container.frame.height;
/* We start listening to the buttons click event, so as to know when one was pressed. */
textButton.container.eventHandler.listenToEvent('onMouseClick', buttonPressed, i);
let storedValue = window.localStorage.getItem(textButton.type);
if (storedValue !== null) {
textButton.status = storedValue;
} else {
textButton.status = BUTTONS_STATES.ON;
}
buttons.push(textButton);
let eventData = {
layer: textButton.type,
status: textButton.status
}
chartLayersPanel.container.eventHandler.raiseEvent('Layer Status Changed', eventData);
}
chartLayersPanel.buttons = buttons;
isInitialized = true;
}
function getLayerStatus(layerName) {
for (let i = 0; i < buttons.length; i++) {
let button = buttons[i];
if (button.type === layerName) {
return button.status;
}
}
return BUTTONS_STATES.OFF;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
/* Now we see which is the inner most container that has it */
for (var i = 0; i < this.buttons.length; i++) {
container = this.buttons[i].getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
}
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function buttonPressed(event, buttonPressedIndex) {
switch (chartLayersPanel.buttons[buttonPressedIndex].status) {
case BUTTONS_STATES.ON:
chartLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.INVISIBLE;
break;
case BUTTONS_STATES.INVISIBLE:
chartLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.OFF;
break;
case BUTTONS_STATES.OFF:
chartLayersPanel.buttons[buttonPressedIndex].status = BUTTONS_STATES.ON;
break;
}
let eventData = {
layer: chartLayersPanel.buttons[buttonPressedIndex].type,
status: chartLayersPanel.buttons[buttonPressedIndex].status
}
chartLayersPanel.container.eventHandler.raiseEvent('Layer Status Changed', eventData);
window.localStorage.setItem(chartLayersPanel.buttons[buttonPressedIndex].type, chartLayersPanel.buttons[buttonPressedIndex].status);
}
function draw() {
if (isInitialized === false) {return;}
chartLayersPanel.container.frame.draw(false, false, true);
for (var i = 0; i < chartLayersPanel.buttons.length; i++) {
chartLayersPanel.buttons[i].draw();
}
}
}
+344
View File
@@ -0,0 +1,344 @@
function newControlPanel() {
let PLAY_STEP = 0;
var controlPanel = {
container: undefined,
buttons: undefined,
setDatetime: setDatetime,
datetimeDisplay: undefined,
stepDisplay: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
container.isDraggeable = true;
container.isZoomeable = false;
controlPanel.container = container;
controlPanel.container.frame.containerName = "Time Control Panel";
var playingLoop; // Controls the generation of events that allows to play continuosly the market.
return controlPanel;
function initialize() {
this.container.frame.width = 200;
this.container.frame.height = 65;
var position = {
x: (viewPort.visibleArea.topRight.x - viewPort.visibleArea.topLeft.x) / 2 - this.container.frame.width / 2,
y: browserCanvas.height * 0.30
};
this.container.frame.position = position;
var buttonPosition;
var buttonNames = ['Fast Backwards', 'Play Backwards', 'Step Backwards', 'Pause', 'Step Forward', 'Play Forward', 'Fast Forward'];
var lastX = 0;
var buttons = [];
for (var i = 0; i < buttonNames.length; i++) {
/* Buttons are going to be one at the right of the other. */
var button = newButton();
button.type = buttonNames[i];
button.container.displacement.parentDisplacement = this.container.displacement;
button.container.zoom.parentZoom = this.container.zoom;
button.container.frame.parentFrame = this.container.frame;
button.container.parentContainer = this.container;
button.initialize();
buttonPosition = { // The first button
x: controlPanel.container.frame.width / 2 - (buttonNames.length * button.container.frame.width) / 2,
y: controlPanel.container.frame.height * 7 / 10
};
button.container.frame.position.x = buttonPosition.x + lastX;
button.container.frame.position.y = buttonPosition.y;
lastX = lastX + button.container.frame.width;
/* We start listening to the buttons click event, so as to know when one was pressed. */
button.container.eventHandler.listenToEvent('onMouseClick', buttonPressed, i);
if (buttonNames[i] === 'Pause') {
button.status = 'on'; // We turn on by default the PAUSE button.
}
buttons.push(button);
}
controlPanel.buttons = buttons;
var datetime = INITIAL_DATE;
var datetimeDisplay = {
currentDatetime: datetime,
addTime: addTime,
draw: drawTimeDisplay
};
controlPanel.buttons = buttons;
controlPanel.datetimeDisplay = datetimeDisplay;
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
PLAY_STEP = recalculatePeriod(viewPort.zoomLevel);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
/* Now we see which is the inner most container that has it */
for (var i = 0; i < this.buttons.length; i++) {
container = this.buttons[i].getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
}
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onZoomChanged(event) {
PLAY_STEP = recalculatePeriod(event.newLevel);
}
function setDatetime(newDatetime) {
controlPanel.datetimeDisplay.currentDatetime = newDatetime;
}
function addTime(seconds) {
var newDate = controlPanel.datetimeDisplay.currentDatetime;
newDate.setSeconds(newDate.getSeconds() + seconds);
controlPanel.datetimeDisplay.currentDatetime = newDate;
}
function buttonPressed(event, buttonPressedIndex) {
clearInterval(playingLoop);
/* When any of the buttons are pressed, the control panel must turn off the resto of the buttons. */
for (var i = 0; i < controlPanel.buttons.length; i++) {
if (i !== buttonPressedIndex) {
var button = controlPanel.buttons[i];
button.status = 'off';
}
}
/* Now we actualy do something depending on which button was pressed. */
switch (controlPanel.buttons[buttonPressedIndex].type) {
case "Fast Backwards":
pressFastBackwards();
break;
case "Play Backwards":
pressPlayBackwards();
break;
case "Step Backwards":
pressStepBackwards();
break;
case "Pause":
pressPause();
break;
case "Step Forward":
pressStepForward();
break;
case "Play Forward":
pressPlayForward();
break;
case "Fast Forward":
pressFastForward();
break;
default:
}
}
function pressFastBackwards() {
clearInterval(playingLoop);
playingLoop = setInterval(pressStepBackwards, 100);
}
function pressPlayBackwards() {
clearInterval(playingLoop);
playingLoop = setInterval(pressStepBackwards, 1000);
}
function pressStepBackwards() {
controlPanel.datetimeDisplay.addTime(-1 * PLAY_STEP / 1000);
var newDatetime = controlPanel.datetimeDisplay.currentDatetime;
controlPanel.container.eventHandler.raiseEvent('Datetime Changed', newDatetime);
}
function pressPause() {
clearInterval(playingLoop);
}
function pressStepForward() {
controlPanel.datetimeDisplay.addTime(PLAY_STEP / 1000);
var newDatetime = controlPanel.datetimeDisplay.currentDatetime;
controlPanel.container.eventHandler.raiseEvent('Datetime Changed', newDatetime);
}
function pressPlayForward() {
clearInterval(playingLoop);
playingLoop = setInterval(pressStepForward, 1000);
}
function pressFastForward() {
playingLoop = setInterval(pressStepForward, 100);
}
function draw() {
controlPanel.container.frame.draw(false, false, true);
for (var i = 0; i < controlPanel.buttons.length; i++) {
controlPanel.buttons[i].draw();
}
this.datetimeDisplay.draw();
}
function drawTimeDisplay() {
let fontSize = 10;
var label = controlPanel.datetimeDisplay.currentDatetime.toDateString() + ' ' + controlPanel.datetimeDisplay.currentDatetime.toLocaleTimeString();
/* Now we transform x on the actual coordinate on the canvas. */
let labelPoint = {
x: controlPanel.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO,
y: controlPanel.container.frame.height * 4.5 / 10
};
labelPoint = controlPanel.container.frame.frameThisPoint(labelPoint);
browserCanvasContext.font = fontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
label = PLAY_STEP / _1_MINUTE_IN_MILISECONDS + ' min';
/* Now we transform x on the actual coordinate on the canvas. */
labelPoint = {
x: controlPanel.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO,
y: controlPanel.container.frame.height * 6.5 / 10
};
labelPoint = controlPanel.container.frame.frameThisPoint(labelPoint);
browserCanvasContext.font = fontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
}
+303
View File
@@ -0,0 +1,303 @@
function newCurrentCandlePanel() {
var currentCandlePanel = {
onCurrentCandleChanged: onCurrentCandleChanged,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
currentCandlePanel.container = container;
container.displacement.containerName = "Current Candle Panel";
container.zoom.containerName = "Current Candle Panel";
container.frame.containerName = "Current Candle Panel";
let currentCandle;
return currentCandlePanel;
function initialize() {
currentCandlePanel.container.frame.width = 250;
currentCandlePanel.container.frame.height = 300;
currentCandlePanel.container.frame.position.x = 0;
currentCandlePanel.container.frame.position.y = viewPort.visibleArea.topLeft.y;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onCurrentCandleChanged(lastCurrentCandle) {
currentCandle = lastCurrentCandle;
}
function draw() {
this.container.frame.draw(false, false, true);
plotCurrentCandleInfo();
}
function plotCurrentCandleInfo() {
if (currentCandle === undefined) { return; }
if (currentCandle.innerCandle === undefined) { return; }
const frameBodyHeight = currentCandlePanel.container.frame.getBodyHeight();
const frameTitleHeight = currentCandlePanel.container.frame.height - frameBodyHeight;
const X_AXIS = currentCandlePanel.container.frame.width / 2;
const Y_AXIS = frameTitleHeight + frameBodyHeight / 2;
var candlePoint1 = {
x: X_AXIS - currentCandle.bodyWidth / 2,
y: Y_AXIS - currentCandle.bodyHeight / 2
};
var candlePoint2 = {
x: X_AXIS + currentCandle.bodyWidth / 2,
y: Y_AXIS - currentCandle.bodyHeight / 2
};
var candlePoint3 = {
x: X_AXIS + currentCandle.bodyWidth / 2,
y: Y_AXIS + currentCandle.bodyHeight / 2
};
var candlePoint4 = {
x: X_AXIS - currentCandle.bodyWidth / 2,
y: Y_AXIS + currentCandle.bodyHeight / 2
};
var stickPoint1 = {
x: X_AXIS - currentCandle.stickWidth / 2,
y: candlePoint1.y - currentCandle.stickStart
};
var stickPoint2 = {
x: X_AXIS + currentCandle.stickWidth / 2,
y: candlePoint1.y - currentCandle.stickStart
};
var stickPoint3 = {
x: X_AXIS + currentCandle.stickWidth / 2,
y: candlePoint1.y - currentCandle.stickStart + currentCandle.stickHeight
};
var stickPoint4 = {
x: X_AXIS - currentCandle.stickWidth / 2,
y: candlePoint1.y - currentCandle.stickStart + currentCandle.stickHeight
};
/* Extra bounderies due to constrained space */
const upperLimit = frameTitleHeight + frameBodyHeight * 0.15;
const downLimit = frameTitleHeight + frameBodyHeight * 0.85;
if (candlePoint1.y < upperLimit) {
candlePoint1.y = upperLimit;
candlePoint2.y = upperLimit;
}
if (stickPoint1.y < upperLimit) {
stickPoint1.y = upperLimit;
stickPoint2.y = upperLimit;
}
if (candlePoint3.y < upperLimit) {
candlePoint3.y = upperLimit;
candlePoint4.y = upperLimit;
}
if (stickPoint3.y < upperLimit) {
stickPoint3.y = upperLimit;
stickPoint4.y = upperLimit;
}
if (candlePoint1.y > downLimit) {
candlePoint1.y = downLimit;
candlePoint2.y = downLimit;
}
if (stickPoint1.y > downLimit) {
stickPoint1.y = downLimit;
stickPoint2.y = downLimit;
}
if (candlePoint3.y > downLimit) {
candlePoint3.y = downLimit;
candlePoint4.y = downLimit;
}
if (stickPoint3.y > downLimit) {
stickPoint3.y = downLimit;
stickPoint4.y = downLimit;
}
candlePoint1 = currentCandlePanel.container.frame.frameThisPoint(candlePoint1);
candlePoint2 = currentCandlePanel.container.frame.frameThisPoint(candlePoint2);
candlePoint3 = currentCandlePanel.container.frame.frameThisPoint(candlePoint3);
candlePoint4 = currentCandlePanel.container.frame.frameThisPoint(candlePoint4);
stickPoint1 = currentCandlePanel.container.frame.frameThisPoint(stickPoint1);
stickPoint2 = currentCandlePanel.container.frame.frameThisPoint(stickPoint2);
stickPoint3 = currentCandlePanel.container.frame.frameThisPoint(stickPoint3);
stickPoint4 = currentCandlePanel.container.frame.frameThisPoint(stickPoint4);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(stickPoint1.x, stickPoint1.y);
browserCanvasContext.lineTo(stickPoint2.x, stickPoint2.y);
browserCanvasContext.lineTo(stickPoint3.x, stickPoint3.y);
browserCanvasContext.lineTo(stickPoint4.x, stickPoint4.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(54, 54, 54, 1)';
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(candlePoint1.x, candlePoint1.y);
browserCanvasContext.lineTo(candlePoint2.x, candlePoint2.y);
browserCanvasContext.lineTo(candlePoint3.x, candlePoint3.y);
browserCanvasContext.lineTo(candlePoint4.x, candlePoint4.y);
browserCanvasContext.closePath();
const OPACITY = '1';
if (currentCandle.innerCandle.direction === 'up') { browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + OPACITY + ')'; }
if (currentCandle.innerCandle.direction === 'down') { browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + OPACITY + ')'; }
if (currentCandle.innerCandle.direction === 'side') { browserCanvasContext.strokeStyle = 'rgba(27, 7, 105, ' + OPACITY + ')'; }
if (currentCandle.innerCandle.direction === 'up') { browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + OPACITY + ')'; }
if (currentCandle.innerCandle.direction === 'down') { browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + OPACITY + ')'; }
if (currentCandle.innerCandle.direction === 'side') { browserCanvasContext.fillStyle = 'rgba(64, 26, 217, ' + OPACITY + ')'; }
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
/* put the labels with the candles values */
let y;
printLabel('High', X_AXIS, frameTitleHeight + frameBodyHeight * 0.05, '1');
printLabel(currentCandle.innerCandle.max, X_AXIS, frameTitleHeight + frameBodyHeight * 0.10, '0.50');
printLabel('Low', X_AXIS, frameTitleHeight + frameBodyHeight * 0.95, '1');
printLabel(currentCandle.innerCandle.min, X_AXIS, frameTitleHeight + frameBodyHeight * 0.90, '0.50');
y = Y_AXIS - currentCandle.bodyHeight / 2;
if (y < frameTitleHeight + frameBodyHeight * 0.15) { y = frameTitleHeight + frameBodyHeight * 0.15; }
if (y > frameTitleHeight + frameBodyHeight * 0.80) { y = frameTitleHeight + frameBodyHeight * 0.80; }
printLabel('Open', X_AXIS * 1 / 2, y , '1');
printLabel(currentCandle.innerCandle.open, X_AXIS * 1 / 2, y + frameBodyHeight * 0.05, '0.50');
y = Y_AXIS + currentCandle.bodyHeight / 2;
if (y < frameTitleHeight + frameBodyHeight * 0.15) { y = frameTitleHeight + frameBodyHeight * 0.15; }
if (y > frameTitleHeight + frameBodyHeight * 0.80) { y = frameTitleHeight + frameBodyHeight * 0.80; }
printLabel('Close', X_AXIS * 3 / 2, y , '1');
printLabel(currentCandle.innerCandle.close, X_AXIS * 3 / 2, y + frameBodyHeight * 0.05, '0.50');
function printLabel(labelToPrint, x, y, opacity) {
let labelPoint;
let fontSize = 10;
browserCanvasContext.font = fontSize + 'px Courier New';
let label = '' + labelToPrint;
let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO;
labelPoint = {
x: x - xOffset,
y: y
};
labelPoint = currentCandlePanel.container.frame.frameThisPoint(labelPoint);
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, ' + opacity + ')';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
browserCanvasContext.closePath();
browserCanvasContext.fill();
}
}
+224
View File
@@ -0,0 +1,224 @@
function newCurrentVolumePanel() {
var currentVolumePanel = {
onCurrentVolumeChanged: onCurrentVolumeChanged,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
currentVolumePanel.container = container;
container.displacement.containerName = "Current Volume Panel";
container.zoom.containerName = "Current Volume Panel";
container.frame.containerName = "Current Volume Panel";
let currentVolume;
return currentVolumePanel;
function initialize() {
currentVolumePanel.container.frame.width = 180;
currentVolumePanel.container.frame.height = 300;
currentVolumePanel.container.frame.position.x = viewPort.visibleArea.topRight.x - currentVolumePanel.container.frame.width;
currentVolumePanel.container.frame.position.y = viewPort.visibleArea.topLeft.y;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onCurrentVolumeChanged(lastCurrentVolume) {
currentVolume = lastCurrentVolume;
}
function draw() {
this.container.frame.draw(false, false, true);
plotCurrentVolumeInfo();
}
function plotCurrentVolumeInfo() {
if (currentVolume === undefined) { return; }
if (currentVolume.innerVolumeBar === undefined) { return; }
const frameBodyHeight = currentVolumePanel.container.frame.getBodyHeight();
const frameTitleHeight = currentVolumePanel.container.frame.height - frameBodyHeight;
const X_AXIS = currentVolumePanel.container.frame.width / 2;
const Y_AXIS_BUY = frameTitleHeight + frameBodyHeight * 0.85;
const Y_AXIS_SELL = frameTitleHeight + frameBodyHeight * 0.15;
var buyVolumePoint1 = {
x: X_AXIS - currentVolume.buyInfo.baseWidth / 2,
y: Y_AXIS_BUY
};
var buyVolumePoint2 = {
x: X_AXIS - currentVolume.buyInfo.topWidth / 2,
y: Y_AXIS_BUY + currentVolume.buyInfo.height
};
var buyVolumePoint3 = {
x: X_AXIS + currentVolume.buyInfo.topWidth / 2,
y: Y_AXIS_BUY + currentVolume.buyInfo.height
};
var buyVolumePoint4 = {
x: X_AXIS + currentVolume.buyInfo.baseWidth / 2,
y: Y_AXIS_BUY
};
buyVolumePoint1 = currentVolumePanel.container.frame.fitIntoFrame(buyVolumePoint1);
buyVolumePoint2 = currentVolumePanel.container.frame.fitIntoFrame(buyVolumePoint2);
buyVolumePoint3 = currentVolumePanel.container.frame.fitIntoFrame(buyVolumePoint3);
buyVolumePoint4 = currentVolumePanel.container.frame.fitIntoFrame(buyVolumePoint4);
buyVolumePoint1 = currentVolumePanel.container.frame.frameThisPoint(buyVolumePoint1);
buyVolumePoint2 = currentVolumePanel.container.frame.frameThisPoint(buyVolumePoint2);
buyVolumePoint3 = currentVolumePanel.container.frame.frameThisPoint(buyVolumePoint3);
buyVolumePoint4 = currentVolumePanel.container.frame.frameThisPoint(buyVolumePoint4);
var sellVolumePoint1 = {
x: X_AXIS - currentVolume.buyInfo.baseWidth / 2,
y: Y_AXIS_SELL
};
var sellVolumePoint2 = {
x: X_AXIS - currentVolume.buyInfo.topWidth / 2,
y: Y_AXIS_SELL + currentVolume.sellInfo.height
};
var sellVolumePoint3 = {
x: X_AXIS + currentVolume.buyInfo.topWidth / 2,
y: Y_AXIS_SELL + currentVolume.sellInfo.height
};
var sellVolumePoint4 = {
x: X_AXIS + currentVolume.buyInfo.baseWidth / 2,
y: Y_AXIS_SELL
};
sellVolumePoint1 = currentVolumePanel.container.frame.fitIntoFrame(sellVolumePoint1);
sellVolumePoint2 = currentVolumePanel.container.frame.fitIntoFrame(sellVolumePoint2);
sellVolumePoint3 = currentVolumePanel.container.frame.fitIntoFrame(sellVolumePoint3);
sellVolumePoint4 = currentVolumePanel.container.frame.fitIntoFrame(sellVolumePoint4);
sellVolumePoint1 = currentVolumePanel.container.frame.frameThisPoint(sellVolumePoint1);
sellVolumePoint2 = currentVolumePanel.container.frame.frameThisPoint(sellVolumePoint2);
sellVolumePoint3 = currentVolumePanel.container.frame.frameThisPoint(sellVolumePoint3);
sellVolumePoint4 = currentVolumePanel.container.frame.frameThisPoint(sellVolumePoint4);
const OPACITY = '0.40';
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(buyVolumePoint1.x, buyVolumePoint1.y);
browserCanvasContext.lineTo(buyVolumePoint2.x, buyVolumePoint2.y);
browserCanvasContext.lineTo(buyVolumePoint3.x, buyVolumePoint3.y);
browserCanvasContext.lineTo(buyVolumePoint4.x, buyVolumePoint4.y);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(27, 105, 7, ' + OPACITY + ')';
browserCanvasContext.fillStyle = 'rgba(64, 217, 26, ' + OPACITY + ')';
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(sellVolumePoint1.x, sellVolumePoint1.y);
browserCanvasContext.lineTo(sellVolumePoint2.x, sellVolumePoint2.y);
browserCanvasContext.lineTo(sellVolumePoint3.x, sellVolumePoint3.y);
browserCanvasContext.lineTo(sellVolumePoint4.x, sellVolumePoint4.y);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(130, 9, 9, ' + OPACITY + ')';
browserCanvasContext.fillStyle = 'rgba(219, 18, 18, ' + OPACITY + ')';
browserCanvasContext.fill();
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
/* put the labels with the volumes values */
browserCanvasContext.beginPath();
printLabel('Buy Volume', X_AXIS, frameTitleHeight + frameBodyHeight * 0.95, '1');
printLabel(currentVolume.innerVolumeBar.amountBuy, X_AXIS, frameTitleHeight + frameBodyHeight * 0.90, '0.50');
printLabel('Sell Volume', X_AXIS, frameTitleHeight + frameBodyHeight * 0.05, '1');
printLabel(currentVolume.innerVolumeBar.amountSell, X_AXIS, frameTitleHeight + frameBodyHeight * 0.10, '0.50');
function printLabel(labelToPrint, x, y, opacity) {
let labelPoint;
let fontSize = 10;
browserCanvasContext.font = fontSize + 'px Courier New';
let label = '' + labelToPrint;
let xOffset = label.length / 2 * fontSize * FONT_ASPECT_RATIO;
labelPoint = {
x: x - xOffset,
y: y
};
labelPoint = currentVolumePanel.container.frame.frameThisPoint(labelPoint);
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, ' + opacity + ')';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
browserCanvasContext.closePath();
browserCanvasContext.fill();
}
}
+438
View File
@@ -0,0 +1,438 @@
function newOrderBookPanel() {
var orderBookPanel = {
onCurrentOrderBookChanged: onCurrentOrderBookChanged,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
orderBookPanel.container = container;
container.displacement.containerName = "Order Book Panel";
container.zoom.containerName = "Order Book Panel";
container.frame.containerName = "Order Book Panel";
let currentOrderBook;
let server;
var plotArea = newPlotArea();
return orderBookPanel;
function initialize() {
orderBookPanel.container.frame.width = 400;
orderBookPanel.container.frame.height = 300;
orderBookPanel.container.frame.position.x = 0;
orderBookPanel.container.frame.position.y = viewPort.visibleArea.bottomLeft.y - orderBookPanel.container.frame.height;
server = newFileServer();
server.initialize();
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function onZoomChanged(event) {
}
function onDragFinished() {
}
function getOrderBook() {
server.getOrderBook(exchangeId, marketId, onFileReady);
function onFileReady(file) {
currentOrderBook = file;
recalculateScale();
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
}
}
function onCurrentOrderBookChanged(orderBooksMap) {
currentOrderBook = [[], []];
for (let key of orderBooksMap.keys()) {
let orderBookPosition = orderBooksMap.get(key);
let position = [orderBookPosition.rate, (orderBookPosition.open + orderBookPosition.close) / 2];
if (orderBookPosition.type === 'bid') {
currentOrderBook[1].push(position);
}
if (orderBookPosition.type === 'ask') {
currentOrderBook[0].push(position);
}
}
recalculateScale();
}
function draw() {
return; // Do not show for now, under construction.
this.container.frame.draw(false, false, true);
plotCurrentOrderBook();
}
function recalculateScale() {
let bidPoints = currentOrderBook[1];
let askPoints = currentOrderBook[0];
let position;
/* Since the range of the data might change, we must calculate the plotArea everytime new data arrives. */
var minBidRate = bidPoints[bidPoints.length - 1];
var maxBidRate = bidPoints[0];
var minValue = {
x: 1,
y: 1
};
var maxValue = {
x: 1,
y: 1
};
if (bidPoints.length > 0) {
/* X AXIS:
We calculate the min value on x on the plot in this way:
1. We calculate the sum of all orders.
2. Then we find which orders are included in the 75% of the total sum.
3. The last order included will contain the minimun rate we need for the chart.
Regarding the maximun, we just take ask orders that mirrors the bids orders only.
*/
var sum = 0;
for (var i = 0; i < bidPoints.length; i++) {
position = {
rate: bidPoints[i][0],
amount: bidPoints[i][1]
};
sum = sum + position.amount;
}
target = sum * 0.75;
sum = 0;
lastOrder = bidPoints[0];
for (var i = 0; i < bidPoints.length; i++) {
position = {
rate: bidPoints[i][0],
amount: bidPoints[i][1]
};
sum = sum + position.amount;
if (sum < target) {
lastOrder = position;
}
}
position = {
rate: bidPoints[0][0],
amount: bidPoints[0][1]
};
var minBidRate = lastOrder.rate;
var maxBidRate = position.rate;
minValue.x = minBidRate;
maxValue.x = maxBidRate + (maxBidRate - minBidRate);
/* Y AXIS:
Now that we know which orders are included on the plot, we must see which is the highest value of
all of them. The highest value can be either at an ask, or at a bid order side of the chart.
*/
var selectedItem = position;
var currentMax = 0;
var sum = 0;
for (var i = 0; i < bidPoints.length; i++) {
position = {
rate: bidPoints[i][0],
amount: bidPoints[i][1]
};
if (position.rate >= minValue.x && position.rate <= maxValue.x) {
sum = sum + position.amount;
}
}
currentMax = sum;
var sum = 0;
for (var i = 0; i < askPoints.length; i++) {
position = {
rate: askPoints[i][0],
amount: askPoints[i][1]
};
if (position.rate >= minValue.x && position.rate <= maxValue.x) {
sum = sum + position.amount;
}
}
if (currentMax < sum) {
currentMax = sum;
}
minValue.y = 0;
maxValue.y = currentMax;
}
plotArea.initialize(
minValue,
maxValue,
orderBookPanel.container.frame.width,
orderBookPanel.container.frame.height - orderBookPanel.container.frame.height * 5 / 7
);
}
function plotCurrentOrderBook() {
if (currentOrderBook === undefined) { return; }
let bidPoints = currentOrderBook[1];
let askPoints = currentOrderBook[0];
let position;
/* The first part of this function will plot BIDs, the second one will plot the ASKs. */
if (bidPoints.length > 0) {
/* We calculate the first points of the chart. These are not points representing positions on the order book, but the lower part of the hill plotted. */
position = {
rate: bidPoints[0][0],
amount: bidPoints[0][1]
};
var maxBasePoint = {
x: 0,
y: orderBookPanel.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (position.rate - plotArea.min.x) * plotArea.scale.x, // We take the first Order Rate on the array for this.
y: orderBookPanel.container.frame.height * 5 / 7
};
maxBasePoint = orderBookPanel.container.frame.frameThisPoint(maxBasePoint);
minBasePoint = orderBookPanel.container.frame.frameThisPoint(minBasePoint);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var progressiveSum = 0;
var point = minBasePoint;
for (var i = 0; i < bidPoints.length; i++) {
position = {
rate: bidPoints[i][0],
amount: bidPoints[i][1]
};
if (position.rate >= plotArea.min.x && position.rate <= plotArea.max.x) {
progressiveSum = progressiveSum + position.amount;
point = {
x: (position.rate - plotArea.min.x) * plotArea.scale.x,
y: orderBookPanel.container.frame.height * 5 / 7 - progressiveSum * plotArea.scale.y
};
point = orderBookPanel.container.frame.frameThisPoint(point);
browserCanvasContext.lineTo(point.x, point.y);
}
}
browserCanvasContext.lineTo(maxBasePoint.x, point.y);
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(130, 180, 30, 0.50)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(50, 130, 30, 0.50)';
browserCanvasContext.lineWidth = 2;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
if (askPoints.length > 0) {
position = {
rate: askPoints[0][0],
amount: askPoints[0][1]
};
/* We calculate the first point of the chart */
var maxBasePoint = {
x: (plotArea.max.x - plotArea.min.x) * plotArea.scale.x,
y: orderBookPanel.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (position.rate - plotArea.min.x) * plotArea.scale.x, // We take the first Order Rate on the array for this.
y: orderBookPanel.container.frame.height * 5 / 7
};
maxBasePoint = orderBookPanel.container.frame.frameThisPoint(maxBasePoint);
minBasePoint = orderBookPanel.container.frame.frameThisPoint(minBasePoint);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var progressiveSum = 0;
var point = minBasePoint;
for (var i = 0; i < askPoints.length; i++) {
position = {
rate: askPoints[i][0],
amount: askPoints[i][1]
};
if (position.rate >= plotArea.min.x && position.rate <= plotArea.max.x) {
progressiveSum = progressiveSum + position.amount;
point = {
x: (position.rate - plotArea.min.x) * plotArea.scale.x,
y: orderBookPanel.container.frame.height * 5 / 7 - progressiveSum * plotArea.scale.y
};
point = orderBookPanel.container.frame.frameThisPoint(point);
browserCanvasContext.lineTo(point.x, point.y);
}
}
browserCanvasContext.lineTo(maxBasePoint.x, point.y);
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(180, 130, 30, 0.50)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(130, 50, 30, 0.50)';
browserCanvasContext.lineWidth = 2;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
}
}
+250
View File
@@ -0,0 +1,250 @@
function gravityForce(ball) {
/* We simulate a kind of gravity towards the target point of each ball. This force will make the ball to keep pushing to reach that point. */
const coulomb = .00001;
const minForce = 0.01;
var d = Math.sqrt(Math.pow(ball.targetPosition.x - ball.currentPosition.x, 2) + Math.pow(ball.targetPosition.y - ball.currentPosition.y, 2)); // ... we calculate the distance ...
var force = coulomb * d * d / ball.currentMass; // In this case the mass of the ball affects the gravity force that it receives, that gives priority to target position to bigger balls.
if (force < minForce) { // We need this attraction force to overcome the friction we imposed to the system.
force = minForce;
}
var pos1 = {
x: ball.currentPosition.x,
y: ball.currentPosition.y
};
var pos2 = {
x: ball.targetPosition.x,
y: ball.targetPosition.y
};
var posDiff = { // Next we need the vector resulting from the 2 positions.
x: pos2.x - pos1.x,
y: pos2.y - pos1.y
};
var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector.
x: posDiff.x / d,
y: posDiff.y / d
};
var forceVector = {
x: unitVector.x * force,
y: unitVector.y * force
};
/* We add the force vector to the speed vector */
ball.currentSpeed.x = ball.currentSpeed.x + forceVector.x;
ball.currentSpeed.y = ball.currentSpeed.y + forceVector.y;
}
function repulsionForce(currentBall) {
/* We generate a repulsion force between balls, that prevents them to be collisioning so often. */
const coulomb = 2;
var ball1 = balls[currentBall];
for (var i = 0; i < balls.length; i++) { // The force to be applied is considering all other balls...
if (i !== currentBall) { // ... except for the current one.
var ball2 = balls[i]; // So, for each ball...
var d = Math.sqrt(Math.pow(ball2.currentPosition.x - ball1.currentPosition.x, 2) + Math.pow(ball2.currentPosition.y - ball1.currentPosition.y, 2)); // ... we calculate the distance ...
var force = coulomb * ball2.currentMass / (d * d); // ... and with it the repulsion force.
/* We need to put a hard limit to this force, in order to to eject very little balls to the infinite and beyond. */
if (force > 1) {
force = 1;
}
var pos1 = {
x: ball1.currentPosition.x,
y: ball1.currentPosition.y
};
var pos2 = {
x: ball2.currentPosition.x,
y: ball2.currentPosition.y
};
var posDiff = { // Next we need the vector resulting from the 2 positions.
x: pos2.x - pos1.x,
y: pos2.y - pos1.y
};
var unitVector = { // To find the unit vector, we divide each component by the magnitude of the vector.
x: posDiff.x / d,
y: posDiff.y / d
};
var forceVector = {
x: unitVector.x * force,
y: unitVector.y * force
};
/* We substract the force vector to the speed vector of the current ball */
ball1.currentSpeed.x = ball1.currentSpeed.x - forceVector.x;
ball1.currentSpeed.y = ball1.currentSpeed.y - forceVector.y;
}
}
}
function colliding(ball1, ball2)
{
/* This function detects weather 2 balls collide with each other. */
var r1 = ball1.currentRadius;
var r2 = ball2.currentRadius;
var distance = Math.sqrt(Math.pow(ball2.currentPosition.x - ball1.currentPosition.x, 2) + Math.pow(ball2.currentPosition.y - ball1.currentPosition.y, 2));
if (distance > (r1 + r2)) {
// No solutions, the circles are too far apart.
return false;
}
else if (distance <= r1 + r2) {
// One circle contains the other.
return true;
}
else if ((distance === 0) && (r1 === r2)) {
// the circles coincide.
return true;
}
else return true;
}
function isInside(x, y) {
/* This function detects weather the point x,y is inside any of the balls. */
for (var i = 0; i < balls.length; i++) {
var ball = balls[i];
var distance = Math.sqrt(Math.pow(ball.currentPosition.x - x, 2) + Math.pow(ball.currentPosition.y - y, 2));
if (distance < ball.currentRadius) {
return i;
}
}
return -1;
}
function isInsideBall(ballIndex, x, y) {
/* This function detects weather the point x,y is inside one particular balls. */
var ball = balls[ballIndex];
var distance = Math.sqrt(Math.pow(ball.currentPosition.x - x, 2) + Math.pow(ball.currentPosition.y - y, 2));
if (distance < ball.currentRadius) {
return true;
}
return false;
}
function distance(x1, y1, x2, y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
function resolveCollision(ball1, ball2) {
/* This function changes speed and position of balls that are in collision */
var collisionision_angle = Math.atan2((ball2.currentPosition.y - ball1.currentPosition.y), (ball2.currentPosition.x - ball1.currentPosition.x));
var speed1 = Math.sqrt(ball1.currentSpeed.x * ball1.currentSpeed.x + ball1.currentSpeed.y * ball1.currentSpeed.y); // Magnitude of Speed Vector for ball 1
var speed2 = Math.sqrt(ball2.currentSpeed.x * ball2.currentSpeed.x + ball2.currentSpeed.y * ball2.currentSpeed.y); // Magnitude of Speed Vector for ball 2
var direction_1 = Math.atan2(ball1.currentSpeed.y, ball1.currentSpeed.x);
var direction_2 = Math.atan2(ball2.currentSpeed.y, ball2.currentSpeed.x);
var new_xspeed_1 = speed1 * Math.cos(direction_1 - collisionision_angle);
var new_yspeed_1 = speed1 * Math.sin(direction_1 - collisionision_angle);
var new_xspeed_2 = speed2 * Math.cos(direction_2 - collisionision_angle);
var new_yspeed_2 = speed2 * Math.sin(direction_2 - collisionision_angle);
var final_xspeed_1 = ((ball1.currentMass - ball2.currentMass) * new_xspeed_1 + (ball2.currentMass + ball2.currentMass) * new_xspeed_2) / (ball1.currentMass + ball2.currentMass);
var final_xspeed_2 = ((ball1.currentMass + ball1.currentMass) * new_xspeed_1 + (ball2.currentMass - ball1.currentMass) * new_xspeed_2) / (ball1.currentMass + ball2.currentMass);
var final_yspeed_1 = new_yspeed_1;
var final_yspeed_2 = new_yspeed_2;
var cosAngle = Math.cos(collisionision_angle);
var sinAngle = Math.sin(collisionision_angle);
ball1.currentSpeed.x = cosAngle * final_xspeed_1 - sinAngle * final_yspeed_1;
ball1.currentSpeed.y = sinAngle * final_xspeed_1 + cosAngle * final_yspeed_1;
ball2.currentSpeed.x = cosAngle * final_xspeed_2 - sinAngle * final_yspeed_2;
ball2.currentSpeed.y = sinAngle * final_xspeed_2 + cosAngle * final_yspeed_2;
var pos1 = {
x: ball1.currentPosition.x,
y: ball1.currentPosition.y
};
var pos2 = {
x: ball2.currentPosition.x,
y: ball2.currentPosition.y
};
// get the mtd
var posDiff = {
x: pos1.x - pos2.x,
y: pos1.y - pos2.y
};
var d = Math.sqrt(Math.pow(ball2.currentPosition.x - ball1.currentPosition.x, 2) + Math.pow(ball2.currentPosition.y - ball1.currentPosition.y, 2));
// minimum translation distance to push balls apart after intersecting
var scalar = (((ball1.currentRadius + ball2.currentRadius) - d) / d);
var minTD = {
x: posDiff.x * scalar,
y: posDiff.y * scalar
};
// resolve intersection --
// computing inverse mass quantities
var im1 = 1 / ball1.currentMass;
var im2 = 1 / ball2.currentMass;
// push-pull them apart based off their mass
pos1.x = pos1.x + minTD.x * (im1 / (im1 + im2));
pos1.y = pos1.y + minTD.y * (im1 / (im1 + im2));
pos2.x = pos2.x - minTD.x * (im2 / (im1 + im2));
pos2.y = pos2.y - minTD.y * (im2 / (im1 + im2));
ball1.currentPosition = pos1;
ball2.currentPosition = pos2;
}
+137
View File
@@ -0,0 +1,137 @@
/*
The Plot Area object is responsible for defining the area of a data set that is going to be plotted and
to the scales that actual values must be multiplied by in order to fit into a certain space.
*/
function newPlotArea() {
var plotArea = {
min: undefined,
max: undefined,
scale: undefined,
inverseTransform: inverseTransform,
inverseTransform2: inverseTransform2,
unInverseTransform: unInverseTransform,
inverseTransformUncappedY: inverseTransformUncappedY,
initializeX: initializeX,
initializeY: initializeY,
initialize: initialize
};
var min = {
x: 0,
y: 0
};
var max = {
x: 0,
y: 0
};
var scale = {
x: 0,
y: 0
};
plotArea.min = min;
plotArea.max = max;
plotArea.scale = scale;
return plotArea;
function initialize(minValue, maxValue, maxWidth, maxHeight) {
/* Defines the min and max value of rate that we are going to transport to the available screen at the center position. */
plotArea.min.x = minValue.x; // * 0.999; // 0.1% less
plotArea.max.x = maxValue.x; // * 1.001; // 0.1% more
plotArea.min.y = minValue.y; // * 0.999; // 0.1% less
plotArea.max.y = maxValue.y; // * 1.001; // 0.1% more
/* Defines the initial Zoom level at center position. */
plotArea.scale.x = maxWidth / (plotArea.max.x - plotArea.min.x);
plotArea.scale.y = maxHeight / (plotArea.max.y - plotArea.min.y);
}
function initializeX(minValue, maxValue, maxWidth) {
plotArea.min.x = minValue.x; // * 0.999; // 0.1% less
plotArea.max.x = maxValue.x; // * 1.001; // 0.1% more
plotArea.scale.x = maxWidth / (plotArea.max.x - plotArea.min.x);
}
function initializeY(minValue, maxValue, maxHeight) {
plotArea.min.y = minValue.y; // * 0.999; // 0.1% less
plotArea.max.y = maxValue.y; // * 1.001; // 0.1% more
plotArea.scale.y = maxHeight / (plotArea.max.y - plotArea.min.y);
}
function inverseTransform(point, inverseY) {
point = {
x: (point.x - this.min.x) * this.scale.x,
y: inverseY - (point.y - this.min.y) * this.scale.y
};
return point;
}
function inverseTransform2(point, inverseY) {
point = {
x: (point.x - this.min.x) * this.scale.x,
y: (inverseY - point.y - this.min.y) * this.scale.y
};
return point;
}
function unInverseTransform(point, inverseY) {
point = {
x: (point.x / this.scale.x) + this.min.x,
y: (inverseY - point.y) / this.scale.y + this.min.y
};
return point;
}
function inverseTransformUncappedY(point, inverseY) {
point = {
x: (point.x - this.min.x) * this.scale.x,
y: (inverseY - point.y) * this.scale.y
};
return point;
}
}
+206
View File
@@ -0,0 +1,206 @@
function newPriceChart() {
var trades = [];
var plotArea = newPlotArea();
var datetime;
var datetimeRange;
var priceChart = {
setDatetime: setDatetime,
setDatetimeRange: setDatetimeRange,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
priceChart.container = container;
container.displacement.containerName = "Price Chart";
container.zoom.containerName = "Price Chart";
container.frame.containerName = "Price Chart";
var marketId;
var exchangeId;
var marketTrades;
return priceChart;
function initialize(exchange, market, trades) {
marketId = market;
exchangeId = exchange;
marketTrades = trades;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function setDatetimeRange(newDatetimeRange) {
datetimeRange = newDatetimeRange;
trades = [];
marketTrades.getTradesByDateRange(datetimeRange, onTradesReady);
function onTradesReady(tradesReceived) {
trades = tradesReceived;
recalculateScale();
splitTrades();
}
}
function draw() {
this.container.frame.draw();
drawBackground();
plotPriceChart();
}
function recalculateScale() {
var minValue = {
x: 10000000000000,
y: 10000000000000
};
var maxValue = {
x: 0,
y: 0
};
for (var i = 0; i < trades.length; i++) {
var trade = trades[i];
var datetime = trade.datetime.valueOf();
if (minValue.x > datetime) {
minValue.x = datetime;
}
if (maxValue.x < datetime) {
maxValue.x = datetime;
}
var rate = trade.rate;
if (minValue.y > rate) {
minValue.y = rate;
}
if (maxValue.y < rate) {
maxValue.y = rate;
}
}
plotArea.initialize(
minValue,
maxValue,
priceChart.container.frame.width,
priceChart.container.frame.height
);
}
function plotPriceChart() {
if (trades.length > 0) {
var firstPoint = {
x: (trades[0].datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: priceChart.container.frame.height - (trades[0].rate - plotArea.min.y) * plotArea.scale.y
};
firstPoint = transformThisPoint(firstPoint, priceChart.container);
browserCanvasContext.moveTo(firstPoint.x, firstPoint.y);
for (var i = 0; i < trades.length; i++) {
var trade = trades[i];
point = {
x: (trade.datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: priceChart.container.frame.height - (trade.rate - plotArea.min.y) * plotArea.scale.y
};
point = transformThisPoint(point, priceChart.container);
browserCanvasContext.lineTo(point.x, point.y);
}
browserCanvasContext.strokeStyle = 'rgba(30, 30, 200, 0.50)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
}
}
function drawBackground() {
var market = markets.get(marketId);
var label = market.assetA + " " + market.assetB;
var fontSize = 50;//+ priceChart.container.zoom.level();
browserCanvasContext.font = fontSize + 'px verdana';
/* Now we transform x on the actual coordinate on the canvas. */
var point = {
x: priceChart.container.frame.width / 2 - label.length / 2 * fontSize / 2,
y: priceChart.container.frame.height * 3 / 8
};
point = transformThisPoint(point, priceChart.container);
browserCanvasContext.fillStyle = 'rgba(190, 190, 190, 0.25)';
browserCanvasContext.fillText(label, point.x, point.y);
}
}
+1
View File
@@ -0,0 +1 @@
# AAWebPlatform
+16
View File
@@ -0,0 +1,16 @@
function newResistance() {
var resistance = {
begin: undefined,
end: undefined,
type: undefined,
rate: undefined,
min: undefined,
max: undefined,
open: undefined,
close: undefined
};
return resistance;
}
+155
View File
@@ -0,0 +1,155 @@
/*
The Splash Screen is to show some 'loading...' controls while the app is being loaded on the background. After the loading is complete the Splash Screens dissapears for good.
*/
function newSplashScreen() {
var splashScreen = {
container: undefined,
draw: draw,
timeMachines: [],
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
splashScreen.container = container;
splashScreen.container.frame.width = browserCanvas.width;
splashScreen.container.frame.height = browserCanvas.height;
container.displacement.containerName = "Splash Screen";
container.zoom.containerName = "Splash Screen";
container.frame.containerName = "Splash Screen";
container.frame.position.x = 0;
container.frame.position.y = 0;
container.isZoomeable = false;
container.isDraggeable = false;
let fadeOutCounter = 0;
let opacity = 1;
return splashScreen;
function initialize() {
}
function draw() {
if (splashScreenNeeded === false) {
stepsInitializationCounter = 100;
fadeOutCounter++;
if (fadeOutCounter > 20) {
return;
}
opacity = opacity - 0.05;
}
splashScreen.container.frame.draw(false, false);
let label = '' + stepsInitializationCounter + ' %';
stepsInitializationCounter++;
if (stepsInitializationCounter > 99) { stepsInitializationCounter = 99;}
let fontSize = 50;
let labelPoint = {
x: splashScreen.container.frame.width / 2 - label.length / 2 * fontSize * FONT_ASPECT_RATIO -30,
y: splashScreen.container.frame.height / 2 + fontSize / 2 + fontSize * 0.1
};
browserCanvasContext.beginPath();
browserCanvasContext.rect(0, 0, splashScreen.container.frame.width, splashScreen.container.frame.height);
browserCanvasContext.fillStyle = 'rgba(255, 255, 255, ' + opacity + ')';
browserCanvasContext.closePath();
browserCanvasContext.fill();
browserCanvasContext.font = fontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(200, 200, 200, ' + opacity + ')';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
let title;
let titlePoint;
fontSize = 100;
title = "Advanced"
titlePoint = {
x: splashScreen.container.frame.width / 2 - title.length / 2 * fontSize * FONT_ASPECT_RATIO - 230,
y: splashScreen.container.frame.height / 2 - fontSize * 2 + 50
};
browserCanvasContext.font = fontSize + 'px Verdana';
browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')';
browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y);
title = "A"
browserCanvasContext.fillStyle = 'rgba(255, 0, 0, ' + opacity + ')';
browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y);
title = "Algos"
titlePoint = {
x: splashScreen.container.frame.width / 2 - title.length / 2 * fontSize * FONT_ASPECT_RATIO + 230,
y: splashScreen.container.frame.height / 2 - fontSize * 2 + 50
};
browserCanvasContext.font = fontSize + 'px Verdana';
browserCanvasContext.fillStyle = 'rgba(0, 0, 0, ' + opacity + ')';
browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y);
title = "A"
browserCanvasContext.fillStyle = 'rgba(255, 0, 0, ' + opacity + ')';
browserCanvasContext.fillText(title, titlePoint.x, titlePoint.y);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
/* Now we see which is the inner most container that has it */
// add validation of inner most containers here.
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
}
+310
View File
@@ -0,0 +1,310 @@
function newSpreadChart() {
var trades = [];
var sells = [];
var buys = [];
var plotArea = newPlotArea();
var datetime;
var datetimeRange;
var spreadChart = {
setDatetime: setDatetime,
setDatetimeRange: setDatetimeRange,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
spreadChart.container = container;
container.displacement.containerName = "Spread Chart";
container.zoom.containerName = "Spread Chart";
container.frame.containerName = "Spread Chart";
var marketId;
var exchangeId;
var marketTrades;
return spreadChart;
function initialize(exchange, market, trades) {
marketId = market;
exchangeId = exchange;
marketTrades = trades;
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function setDatetime(newDatetime) {
datetime = newDatetime;
}
function setDatetimeRange(newDatetimeRange) {
datetimeRange = newDatetimeRange;
trades = [];
marketTrades.getTradesByDateRange(datetimeRange, onTradesReady);
function onTradesReady(tradesReceived) {
trades = tradesReceived;
recalculateScale();
splitTrades();
}
}
function draw() {
this.container.frame.draw();
drawBackground();
plotSpreadChart();
}
function recalculateScale() {
var minValue = {
x: 10000000000000,
y: 10000000000000
};
var maxValue = {
x: 0,
y: 0
};
for (var i = 0; i < trades.length; i++) {
var trade = trades[i];
var datetime = trade.datetime.valueOf();
if (minValue.x > datetime) {
minValue.x = datetime;
}
if (maxValue.x < datetime) {
maxValue.x = datetime;
}
var rate = trade.rate;
if (minValue.y > rate) {
minValue.y = rate;
}
if (maxValue.y < rate) {
maxValue.y = rate;
}
}
plotArea.initialize(
minValue,
maxValue,
spreadChart.container.frame.width,
spreadChart.container.frame.height
);
}
function splitTrades() {
for (let i = 0; i < trades.length; i++) {
let trade = trades[i];
if (trade.type === "sell") {
sells.push(trade);
} else {
buys.push(trade);
}
}
}
function plotSpreadChart() {
if (sells.length > 0) {
let point;
let firstPoint = {
x: (sells[0].datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: spreadChart.container.frame.height - (sells[0].rate - plotArea.min.y) * plotArea.scale.y
};
firstPoint = transformThisPoint(firstPoint, spreadChart.container);
let seconddPoint = {
x: (sells[0].datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: spreadChart.container.frame.height
};
seconddPoint = transformThisPoint(seconddPoint, spreadChart.container);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(seconddPoint.x, seconddPoint.y);
browserCanvasContext.lineTo(firstPoint.x, firstPoint.y);
let thirdPoint;
for (let i = 0; i < sells.length; i++) {
let sell = sells[i];
point = {
x: (sell.datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: spreadChart.container.frame.height - (sell.rate - plotArea.min.y) * plotArea.scale.y
};
thirdPoint = {
x: point.x,
y: spreadChart.container.frame.height
};
point = transformThisPoint(point, spreadChart.container);
browserCanvasContext.lineTo(point.x, point.y);
}
thirdPoint = transformThisPoint(thirdPoint, spreadChart.container);
browserCanvasContext.lineTo(thirdPoint.x, thirdPoint.y);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(117, 27, 5, 0.70)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.fillStyle = 'rgba(230, 67, 34, 0.70)';
browserCanvasContext.fill();
}
if (buys.length > 0) {
let firstPoint = {
x: (buys[0].datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: spreadChart.container.frame.height - (buys[0].rate - plotArea.min.y) * plotArea.scale.y
};
firstPoint = transformThisPoint(firstPoint, spreadChart.container);
let seconddPoint = {
x: (buys[0].datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: 0
};
seconddPoint = transformThisPoint(seconddPoint, spreadChart.container);
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(seconddPoint.x, seconddPoint.y);
browserCanvasContext.lineTo(firstPoint.x, firstPoint.y);
let thirdPoint;
for (let i = 0; i < buys.length; i++) {
let buy = buys[i];
point = {
x: (buy.datetime.valueOf() - plotArea.min.x) * plotArea.scale.x,
y: spreadChart.container.frame.height - (buy.rate - plotArea.min.y) * plotArea.scale.y
};
thirdPoint = {
x: spreadChart.container.frame.width,
y: 0
};
point = transformThisPoint(point, spreadChart.container);
browserCanvasContext.lineTo(point.x, point.y);
}
thirdPoint = transformThisPoint(thirdPoint, spreadChart.container);
browserCanvasContext.lineTo(thirdPoint.x, thirdPoint.y);
browserCanvasContext.closePath();
browserCanvasContext.strokeStyle = 'rgba(4, 74, 117, 0.70)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.fillStyle = 'rgba(34, 174, 230, 0.70)';
browserCanvasContext.fill();
}
}
function drawBackground() {
var market = markets.get(marketId);
var label = market.assetA + " " + market.assetB;
var fontSize = 50;//+ spreadChart.container.zoom.level();
browserCanvasContext.font = fontSize + 'px verdana';
/* Now we transform x on the actual coordinate on the canvas. */
var point = {
x: spreadChart.container.frame.width / 2 - label.length / 2 * fontSize / 2,
y: spreadChart.container.frame.height * 3 / 8
};
point = transformThisPoint(point, spreadChart.container);
browserCanvasContext.fillStyle = 'rgba(190, 190, 190, 0.25)';
browserCanvasContext.fillText(label, point.x, point.y);
}
}
+141
View File
@@ -0,0 +1,141 @@
function newTextButton() {
var textButton = {
container: undefined,
draw: draw,
status: 'off',
type: undefined,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
container.isDraggeable = false;
container.isZoomeable = false;
container.isClickeable = true;
textButton.container = container;
return textButton;
function initialize() {
/* Lets set the basic dimensions of this textButton. */
var position = {
x: 0,
y: 0
};
this.container.frame.position = position;
this.container.frame.width = 180;
this.container.frame.height = 14;
/* Now we start listening to the onClick event from the mouse, so that we can allow users operate this textButton. */
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point, true) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function draw() {
drawIcon();
}
function drawIcon() {
centerPoint = {
x: 7,
y: 7
};
/* Now the transformations. */
centerPoint = textButton.container.frame.frameThisPoint(centerPoint);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.arc(centerPoint.x, centerPoint.y, 3, 0, 2 * Math.PI);
browserCanvasContext.closePath();
let offFillStyle = 'rgba(232, 28, 28, 1)';
let onFillStyle = 'rgba(45, 232, 28, 1)';
let invisibleFillStyle = 'rgba(247, 244, 27, 1)';
switch (textButton.status) {
case 'on':
browserCanvasContext.fillStyle = onFillStyle;
break;
case 'invisible':
browserCanvasContext.fillStyle = invisibleFillStyle;
break;
case 'off':
browserCanvasContext.fillStyle = offFillStyle;
break;
}
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(150, 150, 150, 1)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
/* print the text */
let labelPoint;
let fontSize = 10;
browserCanvasContext.font = fontSize + 'px Courier New';
let label = textButton.type;
let xOffset = 0;
let yOffset = 0;
labelPoint = {
x: 20,
y: textButton.container.frame.height - 5
};
labelPoint = textButton.container.frame.frameThisPoint(labelPoint);
browserCanvasContext.fillStyle = 'rgba(60, 60, 60, 0.50)';
browserCanvasContext.fillText(label, labelPoint.x, labelPoint.y);
}
}
+360
View File
@@ -0,0 +1,360 @@
function newTimeMachine() {
var timeMachine = {
container: undefined,
controlPanel: undefined,
draw: draw,
charts: [],
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
var container = newContainer();
container.initialize();
timeMachine.container = container;
timeMachine.container.isDraggeable = false;
container.displacement.containerName = "Time Machine";
container.zoom.containerName = "Time Machine";
container.frame.containerName = "Time Machine";
let currentCandlePanel;
let currentVolumePanel;
let chartLayersPanel;
let orderBookPanel;
return timeMachine;
function initialize() {
/* Each Time Machine has a Control Panel. */
var controlPanel = newControlPanel();
controlPanel.initialize();
this.controlPanel = controlPanel;
currentCandlePanel = newCurrentCandlePanel();
currentCandlePanel.initialize();
currentVolumePanel = newCurrentVolumePanel();
currentVolumePanel.initialize();
orderBookPanel = newOrderBookPanel();
orderBookPanel.initialize();
chartLayersPanel = newChartLayersPanel();
chartLayersPanel.initialize();
botsLayersPanel = newBotsLayersPanel();
botsLayersPanel.initialize();
let iteration = 0;
/* 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 timelineChart = newTimelineChart();
timelineChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
timelineChart.container.zoom.parentZoom = timeMachine.container.zoom;
timelineChart.container.frame.parentFrame = timeMachine.container.frame;
timelineChart.container.parentContainer = timeMachine.container;
timelineChart.container.frame.width = timeMachine.container.frame.width * 1;
timelineChart.container.frame.height = timeMachine.container.frame.height * 1 * CHART_ASPECT_RATIO;
timelineChart.container.frame.position.x = timeMachine.container.frame.width / 2 - timelineChart.container.frame.width / 2;
timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration;
timelineChart.initialize(1, INITIAL_DEFAULT_MARKET, currentCandlePanel, currentVolumePanel, chartLayersPanel, botsLayersPanel, orderBookPanel, onDefaultMarketInitialized);
iteration++;
function onDefaultMarketInitialized() {
timeMachine.charts.push(timelineChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined);
timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime);
initializeTheRestOfTheMarkets();
}
function initializeTheRestOfTheMarkets() {
markets.forEach(initializeTimelineChart);
function initializeTimelineChart(item, key, mapObj) {
if (key === INITIAL_DEFAULT_MARKET) { // We skip this market since it has already been initialized.
return;
}
let timelineChart = newTimelineChart();
timelineChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
timelineChart.container.zoom.parentZoom = timeMachine.container.zoom;
timelineChart.container.frame.parentFrame = timeMachine.container.frame;
timelineChart.container.parentContainer = timeMachine.container;
timelineChart.container.frame.width = timeMachine.container.frame.width * 1;
timelineChart.container.frame.height = timeMachine.container.frame.height * 1 * CHART_ASPECT_RATIO;
timelineChart.container.frame.position.x = timeMachine.container.frame.width / 2 - timelineChart.container.frame.width / 2;
timelineChart.container.frame.position.y = timelineChart.container.frame.height * 1.5 * iteration;
timelineChart.initialize(1, key, currentCandlePanel, currentVolumePanel, chartLayersPanel, botsLayersPanel, orderBookPanel, finalSteps);
iteration++;
function finalSteps() {
timeMachine.charts.push(timelineChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', timelineChart.setDatetime, undefined);
timelineChart.container.eventHandler.listenToEvent('Datetime Changed', controlPanel.setDatetime);
}
}
}
}
function otherCharts() {
/* Chart 1 */
/*
var orderBookChart = newOrderBookChart();
orderBookChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
orderBookChart.container.zoom.parentZoom = timeMachine.container.zoom;
orderBookChart.container.frame.parentFrame = timeMachine.container.frame;
orderBookChart.container.parentContainer = timeMachine.container;
orderBookChart.container.frame.width = timeMachine.container.frame.width * 0.50;
orderBookChart.container.frame.height = timeMachine.container.frame.height * 0.50;
orderBookChart.container.frame.position.x = timeMachine.container.frame.width * 0;
orderBookChart.container.frame.position.y = timeMachine.container.frame.height * 0.50;
orderBookChart.initialize(1);
orderBookChart.setDatetime(controlPanel.datetimeDisplay.currentDatetime);
timeMachine.charts.push(orderBookChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', orderBookChart.setDatetime, undefined);
*/
/* Chart 2 */
/*
var orderBookChart = newOrderBookChart();
orderBookChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
orderBookChart.container.zoom.parentZoom = timeMachine.container.zoom;
orderBookChart.container.frame.parentFrame = timeMachine.container.frame;
orderBookChart.container.parentContainer = timeMachine.container;
orderBookChart.container.frame.width = timeMachine.container.frame.width * 0.50;
orderBookChart.container.frame.height = timeMachine.container.frame.height * 0.50;
orderBookChart.container.frame.position.x = timeMachine.container.frame.width * 0.50;
orderBookChart.container.frame.position.y = timeMachine.container.frame.height * 0.50;
orderBookChart.initialize(2);
orderBookChart.setDatetime(controlPanel.datetimeDisplay.currentDatetime);
timeMachine.charts.push(orderBookChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', orderBookChart.setDatetime, undefined);
*/
/* Chart 3 */
/*
var priceChart = newPriceChart();
priceChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
priceChart.container.zoom.parentZoom = timeMachine.container.zoom;
priceChart.container.frame.parentFrame = timeMachine.container.frame;
priceChart.container.parentContainer = timeMachine.container;
priceChart.container.frame.width = timeMachine.container.frame.width * 1;
priceChart.container.frame.height = timeMachine.container.frame.height * 1 / 3;
priceChart.container.frame.position.x = timeMachine.container.frame.width * 0;
priceChart.container.frame.position.y = timeMachine.container.frame.height * 0;
priceChart.initialize(1, 2, marketTrades);
priceChart.setDatetime(controlPanel.datetimeDisplay.currentDatetime);
timeMachine.charts.push(priceChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', priceChart.setDatetime, undefined);
*/
/* Chart 5 */
/*
var spreadChart = newSpreadChart();
spreadChart.container.displacement.parentDisplacement = timeMachine.container.displacement;
spreadChart.container.zoom.parentZoom = timeMachine.container.zoom;
spreadChart.container.frame.parentFrame = timeMachine.container.frame;
spreadChart.container.parentContainer = timeMachine.container;
spreadChart.container.frame.width = timeMachine.container.frame.width * 1;
spreadChart.container.frame.height = timeMachine.container.frame.height * 1 / 3;
spreadChart.container.frame.position.x = timeMachine.container.frame.width * 0;
spreadChart.container.frame.position.y = timeMachine.container.frame.height * 1 / 3;
spreadChart.initialize(1, 2, marketTrades);
spreadChart.setDatetime(controlPanel.datetimeDisplay.currentDatetime);
timeMachine.charts.push(spreadChart);
controlPanel.container.eventHandler.listenToEvent('Datetime Changed', spreadChart.setDatetime, undefined);
*/
}
function draw() {
this.container.frame.draw(false, false);
/* When we draw a time machine, that means also to draw all the charts in it. */
for (var i = 0; i < this.charts.length; i++) {
let chart = this.charts[i];
chart.draw();
}
this.controlPanel.draw();
currentCandlePanel.draw();
currentVolumePanel.draw();
chartLayersPanel.draw();
botsLayersPanel.draw();
orderBookPanel.draw();
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
/* Now we see which is the inner most container that has it */
container = this.controlPanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
container = currentCandlePanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
container = currentVolumePanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
container = chartLayersPanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
container = botsLayersPanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
container = orderBookPanel.getContainer(point);
if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
return container;
}
//for (var i = 0; i < this.charts.length; i++) {
// container = this.charts[i].getContainer(point);
// if (container !== undefined) {
/* We found an inner container which has the point. We return it. */
// return container;
// }
//}
/* The point does not belong to any inner container, so we return the current container. */
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
}
+613
View File
@@ -0,0 +1,613 @@
function newTimelineChart() {
let layers = [];
let plotArea = newPlotArea();
let timePeriod = INITIAL_TIME_PERIOD;
var datetime;
var timelineChart = {
layers: layers,
setDatetime: setDatetime,
container: undefined,
draw: draw,
getContainer: getContainer,
initialize: initialize
};
var container = newContainer();
container.initialize();
timelineChart.container = container;
container.displacement.containerName = "Time Period Chart";
container.zoom.containerName = "Time Period Chart";
container.frame.containerName = "Time Period Chart";
let marketId;
let exchangeId;
let marketIndex;
let dailyFilesCursor;
let level;
let chartGrid;
let targetLabelFontSize = 150;
let fontSizeIncrement = 12.5;
let currentFontSize = 150;
let initializationReady = false;
let currentCandlePanel;
let currentVolumePanel;
let chartLayersPanel;
let botsLayersPanel;
let orderBookPanel;
return timelineChart;
function initialize(exchange, market, currentCandlePanelToUse, currentVolumePanelToUse, chartLayersPanelToUse, botsLayersPanelToUse, orderBookPanelToUse, callBackFunction) {
currentCandlePanel = currentCandlePanelToUse;
currentVolumePanel = currentVolumePanelToUse;
chartLayersPanel = chartLayersPanelToUse;
botsLayersPanel = botsLayersPanelToUse;
orderBookPanel = orderBookPanelToUse;
marketId = market;
exchangeId = exchange;
chartGrid = newChartGrid();
marketIndex = newMarketIndex();
marketIndex.initialize(exchangeId, marketId, continueInitialization);
function continueInitialization() {
recalculateScale();
dailyFilesCursor = newDailyFilesCursor();
dailyFilesCursor.initialize(exchangeId, marketId, finalSteps);
function finalSteps() {
/* Event Subscriptions - we need this events to be fired first here and then in layers. */
viewPort.eventHandler.listenToEvent("Offset Changed", onOffsetChanged);
viewPort.eventHandler.listenToEvent("Zoom Changed", onZoomChanged);
canvas.eventHandler.listenToEvent("Drag Finished", onDragFinished);
initializeLayers();
callBackFunction();
initializationReady = true;
marketInitializationCounter++;
}
}
}
function initializeLayers() {
/* All Time Layer */
var allTimeChartLayer = newAllTimeChartLayer();
allTimeChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
allTimeChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
allTimeChartLayer.container.frame.parentFrame = timelineChart.container.frame;
allTimeChartLayer.container.parentContainer = timelineChart.container;
allTimeChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
allTimeChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
allTimeChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - allTimeChartLayer.container.frame.width / 2;
allTimeChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - allTimeChartLayer.container.frame.height / 2;
allTimeChartLayer.initialize(exchangeId, marketId, marketIndex, chartLayersPanel);
/* Orderbook Resistances Layer */
var orderBooksChartLayer = newOrderBooksChartLayer();
orderBooksChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
orderBooksChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
orderBooksChartLayer.container.frame.parentFrame = timelineChart.container.frame;
orderBooksChartLayer.container.parentContainer = timelineChart.container;
orderBooksChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
orderBooksChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
orderBooksChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - orderBooksChartLayer.container.frame.width / 2;
orderBooksChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - orderBooksChartLayer.container.frame.height / 2;
orderBooksChartLayer.initialize(exchangeId, marketId, marketIndex, chartLayersPanel);
/* Candle Technical Analisys Layer */
var candleTechnicalAnalisysChartLayer = newCandleTechnicalAnalisysChartLayer();
candleTechnicalAnalisysChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
candleTechnicalAnalisysChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
candleTechnicalAnalisysChartLayer.container.frame.parentFrame = timelineChart.container.frame;
candleTechnicalAnalisysChartLayer.container.parentContainer = timelineChart.container;
candleTechnicalAnalisysChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
candleTechnicalAnalisysChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
candleTechnicalAnalisysChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - candleTechnicalAnalisysChartLayer.container.frame.width / 2;
candleTechnicalAnalisysChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - candleTechnicalAnalisysChartLayer.container.frame.height / 2;
candleTechnicalAnalisysChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* Volume Technical Analisys Layer */
var volumeTechnicalAnalisysChartLayer = newVolumeTechnicalAnalisysChartLayer();
volumeTechnicalAnalisysChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
volumeTechnicalAnalisysChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
volumeTechnicalAnalisysChartLayer.container.frame.parentFrame = timelineChart.container.frame;
volumeTechnicalAnalisysChartLayer.container.parentContainer = timelineChart.container;
volumeTechnicalAnalisysChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
volumeTechnicalAnalisysChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
volumeTechnicalAnalisysChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - volumeTechnicalAnalisysChartLayer.container.frame.width / 2;
volumeTechnicalAnalisysChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - volumeTechnicalAnalisysChartLayer.container.frame.height / 2;
volumeTechnicalAnalisysChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* Sopport Resistance Layer */
var supportResistanceChartLayer = newSupportResistanceChartLayer();
supportResistanceChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
supportResistanceChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
supportResistanceChartLayer.container.frame.parentFrame = timelineChart.container.frame;
supportResistanceChartLayer.container.parentContainer = timelineChart.container;
supportResistanceChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
supportResistanceChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
supportResistanceChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - supportResistanceChartLayer.container.frame.width / 2;
supportResistanceChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - supportResistanceChartLayer.container.frame.height / 2;
supportResistanceChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* High Low Layer */
var highLowChartLayer = newHighLowChartLayer();
highLowChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
highLowChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
highLowChartLayer.container.frame.parentFrame = timelineChart.container.frame;
highLowChartLayer.container.parentContainer = timelineChart.container;
highLowChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
highLowChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
highLowChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - highLowChartLayer.container.frame.width / 2;
highLowChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - highLowChartLayer.container.frame.height / 2;
highLowChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* Candles Layer */
var candleStickChartLayer = newCandleStickChartLayer();
candleStickChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
candleStickChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
candleStickChartLayer.container.frame.parentFrame = timelineChart.container.frame;
candleStickChartLayer.container.parentContainer = timelineChart.container;
candleStickChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
candleStickChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
candleStickChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - candleStickChartLayer.container.frame.width / 2;
candleStickChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - candleStickChartLayer.container.frame.height / 2;
candleStickChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel, chartLayersPanel);
/* Volume Layer */
var volumeChartLayer = newVolumeChartLayer();
volumeChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
volumeChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
volumeChartLayer.container.frame.parentFrame = timelineChart.container.frame;
volumeChartLayer.container.parentContainer = timelineChart.container;
volumeChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
volumeChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
volumeChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - volumeChartLayer.container.frame.width / 2;
volumeChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - volumeChartLayer.container.frame.height / 2;
volumeChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel, chartLayersPanel);
/* Accumulated Volume Volume Layer */
var accumulatedVolumeChartLayer = newAccumulatedVolumeChartLayer();
accumulatedVolumeChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
accumulatedVolumeChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
accumulatedVolumeChartLayer.container.frame.parentFrame = timelineChart.container.frame;
accumulatedVolumeChartLayer.container.parentContainer = timelineChart.container;
accumulatedVolumeChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
accumulatedVolumeChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
accumulatedVolumeChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - accumulatedVolumeChartLayer.container.frame.width / 2;
accumulatedVolumeChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - accumulatedVolumeChartLayer.container.frame.height / 2;
accumulatedVolumeChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* Forecast Layer */
var forecastChartLayer = newForecastChartLayer();
forecastChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
forecastChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
forecastChartLayer.container.frame.parentFrame = timelineChart.container.frame;
forecastChartLayer.container.parentContainer = timelineChart.container;
forecastChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
forecastChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
forecastChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - forecastChartLayer.container.frame.width / 2;
forecastChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - forecastChartLayer.container.frame.height / 2;
forecastChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
candleStickChartLayer.container.eventHandler.listenToEvent("Current Candle Changed", forecastChartLayer.setCurrentCandle);
forecastChartLayer.setCurrentCandle(candleStickChartLayer.currentCandle);
/* Linear Regression Curve Layer */
var linearRegressionCurveChartLayer = newLinearRegressionCurve();
linearRegressionCurveChartLayer.container.displacement.parentDisplacement = timelineChart.container.displacement;
linearRegressionCurveChartLayer.container.zoom.parentZoom = timelineChart.container.zoom;
linearRegressionCurveChartLayer.container.frame.parentFrame = timelineChart.container.frame;
linearRegressionCurveChartLayer.container.parentContainer = timelineChart.container;
linearRegressionCurveChartLayer.container.frame.width = timelineChart.container.frame.width * 1;
linearRegressionCurveChartLayer.container.frame.height = timelineChart.container.frame.height * 1;
linearRegressionCurveChartLayer.container.frame.position.x = timelineChart.container.frame.width / 2 - candleTechnicalAnalisysChartLayer.container.frame.width / 2;
linearRegressionCurveChartLayer.container.frame.position.y = timelineChart.container.frame.height / 2 - candleTechnicalAnalisysChartLayer.container.frame.height / 2;
linearRegressionCurveChartLayer.initialize(exchangeId, marketId, marketIndex, dailyFilesCursor, chartLayersPanel);
/* Add all layers to the internal array */
timelineChart.layers.push(allTimeChartLayer);
timelineChart.layers.push(orderBooksChartLayer);
timelineChart.layers.push(forecastChartLayer);
//timelineChart.layers.push(supportResistanceChartLayer);
timelineChart.layers.push(highLowChartLayer);
timelineChart.layers.push(candleTechnicalAnalisysChartLayer);
timelineChart.layers.push(volumeTechnicalAnalisysChartLayer);
timelineChart.layers.push(candleStickChartLayer);
timelineChart.layers.push(volumeChartLayer);
timelineChart.layers.push(accumulatedVolumeChartLayer);
timelineChart.layers.push(linearRegressionCurveChartLayer);
/* Wiring some charts with others using events */
candleStickChartLayer.container.eventHandler.listenToEvent("Candles Changed", candleTechnicalAnalisysChartLayer.onCandlesChanged);
candleStickChartLayer.container.eventHandler.listenToEvent("Candles Changed", highLowChartLayer.onCandlesChanged);
candleStickChartLayer.container.eventHandler.listenToEvent("Candles Changed", supportResistanceChartLayer.onCandlesChanged);
candleStickChartLayer.container.eventHandler.listenToEvent("Current Candle Info Changed", currentCandlePanel.onCurrentCandleChanged);
candleStickChartLayer.container.eventHandler.listenToEvent("Candles Changed", linearRegressionCurveChartLayer.onCandlesChanged);
volumeChartLayer.container.eventHandler.listenToEvent("Current Volume Info Changed", currentVolumePanel.onCurrentVolumeChanged);
volumeChartLayer.container.eventHandler.listenToEvent("Volumes Changed", volumeTechnicalAnalisysChartLayer.onVolumesChanged);
orderBooksChartLayer.container.eventHandler.listenToEvent("Current Order Book Changed", orderBookPanel.onCurrentOrderBookChanged);
/* Connecting all layers to the panel that provides a user interface to turn them on - visible - off */
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", accumulatedVolumeChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", candleStickChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", candleTechnicalAnalisysChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", highLowChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", volumeChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", volumeTechnicalAnalisysChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", allTimeChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", forecastChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", orderBooksChartLayer.onLayerStatusChanged);
chartLayersPanel.container.eventHandler.listenToEvent("Layer Status Changed", linearRegressionCurveChartLayer.onLayerStatusChanged);
}
function onZoomChanged(event) {
if (initializationReady === true) {
level = event.newLevel; // for debugging purposes only
let currentTimePeriod = timePeriod;
timePeriod = recalculatePeriod(event.newLevel);
if (timePeriod !== currentTimePeriod) {
for (var i = 0; i < timelineChart.layers.length; i++) {
let layer = timelineChart.layers[i];
layer.setTimePeriod(timePeriod);
}
}
recalculateCurrentDatetime();
if (timelineChart.container.frame.isInViewPort() && tooSmall() === false) {
dailyFilesCursor.setDatetime(datetime);
}
}
}
function onDragFinished() {
if (initializationReady === true) {
if (timelineChart.container.frame.isInViewPort() && tooSmall() === false) {
dailyFilesCursor.setDatetime(datetime);
}
}
}
function onOffsetChanged() {
if (initializationReady === true) {
if (timelineChart.container.frame.isInViewPort()) {
recalculateCurrentDatetime();
}
}
}
function recalculateCurrentDatetime() {
let center = {
x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2,
y: (viewPort.visibleArea.bottomRight.y - viewPort.visibleArea.topRight.y) / 2
};
center = unTransformThisPoint(center, timelineChart.container);
center = plotArea.unInverseTransform(center, timelineChart.container.frame.height);
let newDate = new Date(0);
newDate.setUTCSeconds(center.x / 1000);
datetime = newDate;
for (var i = 0; i < timelineChart.layers.length; i++) {
let layer = timelineChart.layers[i];
layer.setDatetime(datetime);
}
timelineChart.container.eventHandler.raiseEvent("Datetime Changed", datetime);
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
function setDatetime(newDatetime) {
if (timelineChart.container.frame.isInViewPort()) {
for (var i = 0; i < timelineChart.layers.length; i++) {
let layer = timelineChart.layers[i];
layer.setDatetime(newDatetime);
if (layer.positionAtDatetime !== undefined) {
layer.positionAtDatetime(newDatetime);
}
}
}
}
function draw() {
if (timelineChart.container.frame.isInViewPort()) {
this.container.frame.draw();
drawBackground();
chartGrid.draw(timelineChart.container, plotArea);
for (var i = 0; i < this.layers.length; i++) {
let layer = this.layers[i];
layer.draw();
}
}
}
function recalculateScale() {
var minValue = {
x: EARLIEST_DATE.valueOf(),
y: 0
};
var maxValue = {
x: MAX_PLOTABLE_DATE.valueOf(),
y: nextPorwerOf10(marketIndex.maxRate())
};
plotArea.initialize(
minValue,
maxValue,
timelineChart.container.frame.width,
timelineChart.container.frame.height
);
}
function tooTiny() {
if (viewPort.zoomLevel < Math.trunc(-28.25 * 100) / 100) {
return true;
} else {
return false;
}
}
function tooSmall() {
if (viewPort.zoomLevel < Math.trunc(-27.25 * 100) / 100) {
return true;
} else {
return false;
}
}
function drawBackground() {
var market = markets.get(marketId);
var label = market.assetA + " " + market.assetB;
//label = '' + level; // Math.trunc(timePeriod / 1000 / 60);
if (tooTiny() === true ) {
return;
}
let topPoint = {
x: 0,
y: 0
};
let bottomPoint = {
x: 0,
y: timelineChart.container.frame.height
};
topPoint = transformThisPoint(topPoint, timelineChart.container);
bottomPoint = transformThisPoint(bottomPoint, timelineChart.container);
/* We want the label of the market to be always centered in the middle of the screen, unless the upper or lower border of the frame is visible on the screen */
let point;
if (targetLabelFontSize !== currentFontSize) {
if (targetLabelFontSize > currentFontSize) {
currentFontSize = currentFontSize + fontSizeIncrement;
} else {
currentFontSize = currentFontSize - fontSizeIncrement;
}
}
if (topPoint.y > viewPort.visibleArea.topLeft.y || bottomPoint.y < viewPort.visibleArea.bottomRight.y) {
targetLabelFontSize = 150 / 2;
point = {
x: 0,
y: timelineChart.container.frame.height / 2
};
point = transformThisPoint(point, timelineChart.container);
point = {
x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2 - label.length / 2 * currentFontSize * 0.60,
y: point.y + currentFontSize * 0.60 / 2
};
} else {
targetLabelFontSize = 150;
point = {
x: (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / 2 - label.length / 2 * currentFontSize * 0.60,
y: (viewPort.visibleArea.bottomLeft.y - viewPort.visibleArea.topLeft.y) / 2 + currentFontSize * 0.60 / 2
};
}
browserCanvasContext.font = currentFontSize + 'px Courier New';
browserCanvasContext.fillStyle = 'rgba(75, 86, 235, 0.07)';
browserCanvasContext.fillText(label, point.x, point.y);
}
}
+16
View File
@@ -0,0 +1,16 @@
function newTrade(id, type, rate, amountA, amountB, datetime) {
var trade = {
id: id,
type: type,
rate: rate,
amountA: amountA,
amountB: amountB,
datetime: datetime
};
return trade;
}
+38
View File
@@ -0,0 +1,38 @@
function newTradesCursor() {
let trades = [];
let tradesCursor = {
eventHandler: undefined,
newTradesReady: newTradesReady,
trades: undefined,
initialize: initialize
}
tradesCursor.trades = trades;
let marketId;
let exchangeId;
let marketTrades;
tradesCursor.eventHandler = newEventHandler();
return tradesCursor;
function initialize(exchange, market, marketTrades) {
marketId = market;
exchangeId = exchange;
marketTrades = marketTrades;
}
function newTradesReady(tradesReceived) {
tradesCursor.trades = tradesReceived;
tradesCursor.eventHandler.raiseEvent("Trades Changed", undefined);
}
}
+86
View File
@@ -0,0 +1,86 @@
function transformThisPoint(point, container) {
/* We make the point relative to the current frame */
point = container.frame.frameThisPoint(point);
/* We add the possible displacement */
point = container.displacement.displaceThisPoint(point);
/* We apply the zoom factor. */
point = container.zoom.zoomThisPoint(point);
/* We viewport Transformation. */
point = viewPort.zoomThisPoint(point);
return point;
}
function unTransformThisPoint(point, container) {
point = viewPort.unzoomThisPoint(point);
point = container.zoom.unzoomThisPoint(point);
point = container.displacement.undisplaceThisPoint(point);
point = container.frame.unframeThisPoint(point);
return point;
}
function nextPorwerOf10(number) {
for (let i = -10; i <= 10; i++) {
if (number < Math.pow(10, i)) {
return Math.pow(10, i);
}
}
}
function pad(str, max) {
str = str.toString();
return str.length < max ? pad("0" + str, max) : str;
}
function getDateFromPoint(point, container, plotArea) {
point = unTransformThisPoint(point, container);
point = plotArea.unInverseTransform(point, container.frame.height);
let date = new Date(point.x);
date = removeTime(date);
return date;
}
function getRateFromPoint(point, container, plotArea) {
point = unTransformThisPoint(point, container);
point = plotArea.unInverseTransform(point, container.frame.height);
return point.y;
}
function getMilisecondsFromPoint(point, container, plotArea) {
point = unTransformThisPoint(point, container);
point = plotArea.unInverseTransform(point, container.frame.height);
return point.x;
}
function removeTime(datetime) {
if (datetime === undefined) { return;}
let dateOnly = new Date(Math.trunc(datetime.valueOf() / ONE_DAY_IN_MILISECONDS) * ONE_DAY_IN_MILISECONDS);
return dateOnly;
}
+402
View File
@@ -0,0 +1,402 @@
function newViewPort() {
let ANIMATION_INCREMENT = 0.25;
const TOP_MARGIN = 15;
const BOTTOM_MARGIN = 0;
const LEFT_MARGIN = 0;
const RIGHT_MARGIN = 50;
let viewPort = {
visibleArea: undefined,
eventHandler: undefined,
zoomLevel: 0,
mousePosition: undefined,
applyZoom: applyZoom,
zoomFontSize: zoomFontSize,
zoomThisPoint: zoomThisPoint,
unzoomThisPoint: unzoomThisPoint,
isThisPointVisible: isThisPointVisible,
fitIntoVisibleArea: fitIntoVisibleArea,
displace: displace,
displaceTarget: displaceTarget,
animate: animate,
draw: draw,
initialize: initialize
};
targetLevel = 0;
let increment = 0.035;
var offset = {
x: 0,
y: 0
};
var targetOffset = {
x: 0,
y: 0
};
let offsetIncrement = {
x: 0,
y: 0
};
viewPort.mousePosition = {
x: 0,
y: 0
};
viewPort.eventHandler = newEventHandler();
return viewPort;
function initialize() {
viewPort.visibleArea = {
topLeft: { x: LEFT_MARGIN, y: TOP_MARGIN },
topRight: { x: browserCanvas.width - RIGHT_MARGIN , y: TOP_MARGIN },
bottomRight: { x: browserCanvas.width - RIGHT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN},
bottomLeft: { x: LEFT_MARGIN, y: browserCanvas.height - BOTTOM_MARGIN}
};
}
function animate() {
if (viewPort.zoomLevel < targetLevel) {
if (targetLevel - viewPort.zoomLevel < ANIMATION_INCREMENT) {
ANIMATION_INCREMENT = Math.abs(targetLevel - viewPort.zoomLevel);
}
viewPort.zoomLevel = viewPort.zoomLevel + ANIMATION_INCREMENT;
changeZoom(viewPort.zoomLevel - ANIMATION_INCREMENT, viewPort.zoomLevel);
}
if (viewPort.zoomLevel > targetLevel) {
if (viewPort.zoomLevel - targetLevel < ANIMATION_INCREMENT) {
ANIMATION_INCREMENT = Math.abs(targetLevel - viewPort.zoomLevel);
}
viewPort.zoomLevel = viewPort.zoomLevel - ANIMATION_INCREMENT;
changeZoom(viewPort.zoomLevel + ANIMATION_INCREMENT, viewPort.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;
} else {
offsetIncrement.y = 0;
}
}
}
function displace(displaceVector) {
offset.x = offset.x + displaceVector.x;
offset.y = offset.y + displaceVector.y;
let event = {
newOffset: offset
};
viewPort.eventHandler.raiseEvent("Offset Changed", event);
}
function displaceTarget(displaceVector) {
targetOffset.x = targetOffset.x + displaceVector.x;
targetOffset.y = targetOffset.y + displaceVector.y;
offsetIncrement = {
x: (targetOffset.x - offset.x) / 10,
y: (targetOffset.y - offset.y) / 10
};
}
function applyZoom(amount) {
if (amount > 0) {
if (targetLevel > -5) {
amount = amount * 2;
}
if (targetLevel > 10) {
amount = amount * 3;
}
if (targetLevel > 15) {
amount = amount * 4;
}
}
if (amount < 0) {
if (targetLevel > -4) {
amount = amount * 2;
}
if (targetLevel > 13) {
amount = amount * 3;
}
if (targetLevel > 19) {
amount = amount * 4;
}
}
if (targetLevel + amount > 1000) {
return false;
}
if (targetLevel <= -27 && amount < 0) {
amount = amount / 4;
}
if (targetLevel < -27 && amount > 0) {
amount = amount / 4;
}
if (targetLevel + amount < -28.25) {
return false;
}
targetLevel = targetLevel + amount;
ANIMATION_INCREMENT = Math.abs(targetLevel - viewPort.zoomLevel) / 3;
let event = {
newLevel: targetLevel,
newOffset: offset,
type: undefined
};
if (amount > 0) {
event.type = "Zoom In";
} else {
event.type = "Zoom Out";
}
viewPort.eventHandler.raiseEvent("Zoom Changed", event);
return true;
}
function changeZoom(oldLevel, newLevel) {
let mouseNoZoom = unzoomThisPoint(viewPort.mousePosition, oldLevel);
let newMouse = zoomThisPoint(mouseNoZoom, newLevel);
offset.x = offset.x - newMouse.x + viewPort.mousePosition.x;
offset.y = offset.y - newMouse.y + viewPort.mousePosition.y;
targetOffset.x = offset.x
targetOffset.y = offset.y ;
offsetIncrement = {
x: 0,
y: 0
};
}
function zoomFontSize(baseSize, level) {
let zoomFactor = increment; // + increment * viewPort.zoomLevel / 100;
if (level === undefined) {
baseSize = baseSize * (1 + zoomFactor * viewPort.zoomLevel);
} else {
baseSize = baseSize * (1 + zoomFactor * level);
}
return baseSize;
}
function fitIntoVisibleArea(point) {
/* Here we check the boundaries of the resulting points, so they dont go out of the visible area. */
if (point.x > viewPort.visibleArea.bottomRight.x + 1) {
point.x = viewPort.visibleArea.bottomRight.x + 1;
}
if (point.x < viewPort.visibleArea.topLeft.x - 1) {
point.x = viewPort.visibleArea.topLeft.x - 1;
}
if (point.y > viewPort.visibleArea.bottomRight.y + 1) {
point.y = viewPort.visibleArea.bottomRight.y + 1;
}
if (point.y < viewPort.visibleArea.topLeft.y - 1) {
point.y = viewPort.visibleArea.topLeft.y - 1;
}
return point;
}
function zoomThisPoint(point, level) {
let zoomFactor = increment; // + increment * viewPort.zoomLevel / 100;
if (level === undefined) {
point.x = point.x * (1 + zoomFactor * viewPort.zoomLevel) + offset.x;
point.y = point.y * (1 + zoomFactor * viewPort.zoomLevel) + offset.y;
} else {
point.x = point.x * (1 + zoomFactor * level) + offset.x;
point.y = point.y * (1 + zoomFactor * level) + offset.y;
}
return point;
}
function unzoomThisPoint(pointWithZoom, level) {
let pointWithoutZoom;
let zoomFactor = increment; // + increment * viewPort.zoomLevel / 100;
if (level === undefined) {
pointWithoutZoom = {
x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * viewPort.zoomLevel),
y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * viewPort.zoomLevel)
};
} else {
pointWithoutZoom = {
x: (pointWithZoom.x - offset.x) / (1 + zoomFactor * level),
y: (pointWithZoom.y - offset.y) / (1 + zoomFactor * level)
};
}
return pointWithoutZoom;
}
function isThisPointVisible(point) {
if (visibleArea === undefined) {
getVisibleArea();
}
if (point.x < visibleArea.topLeft.x || point.x > visibleArea.bottomRight.x || point.y < visibleArea.topLeft.y || point.y > visibleArea.bottomRight.y) {
return false;
} else {
return true;
}
}
function draw() {
/*
drawGrid(10);
drawGrid(1);
drawGrid(0.1);
*/
}
function drawGrid(step) {
let squareWidth = (viewPort.visibleArea.bottomRight.x - viewPort.visibleArea.bottomLeft.x) / step;
squareWidth = squareWidth + squareWidth * increment * viewPort.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 * viewPort.zoomLevel;
if (lineWidth < 0.5) {
return;
}
if (lineWidth > 2) {
lineWidth = 2;
}
browserCanvasContext.beginPath();
for (var i = startingX; i < viewPort.visibleArea.bottomRight.x; i = i + squareWidth) {
for (var j = startingY; j < viewPort.visibleArea.bottomRight.y; j = j + squareWidth) {
let point1 = {
x: viewPort.visibleArea.bottomLeft.x,
y: j
};
let point2 = {
x: viewPort.visibleArea.bottomRight.x,
y: j
};
browserCanvasContext.moveTo(point1.x, point1.y);
browserCanvasContext.lineTo(point2.x, point2.y);
}
let point3 = {
x: i,
y: viewPort.visibleArea.topLeft.y
};
let point4 = {
x: i,
y: viewPort.visibleArea.bottomLeft.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.lineWidth = lineWidth;
browserCanvasContext.stroke();
}
}
+12
View File
@@ -0,0 +1,12 @@
function newVolumeBar() {
var volumeBar = {
amountBuy: 0,
amountSell: 0,
begin: undefined,
end: undefined
};
return volumeBar;
}
+15
View File
@@ -0,0 +1,15 @@
function newVolumeStairs() {
var volumeStairs = {
type: undefined,
begin: undefined,
end: undefined,
direction: undefined,
barsCount: 0,
firstAmount: 0,
lastAmount: 0
};
return volumeStairs;
}
+221
View File
@@ -0,0 +1,221 @@
/* The Zoom is the factor that amplifies the current container coordinates, and everything included in that container. */
function newZoom() {
var zoom = {
containerName: "", // This is for debugging purposes only.
parentZoom: undefined, // Here we store the parent cointainer zoom object.
container: undefined,
levelX: 0, // this is the actual zoom level on the x axis.
incrementX: 0.1,
levelY: 0,
incrementY: 0.1,
levelR: -15,
incrementR: 0.05,
levelM: -15,
incrementM: 0.05,
xyZoom: xyZoom,
xZoom: xZoom,
yZoom: yZoom,
rZoom: rZoom,
mZoom: mZoom,
zoomThisPoint: zoomThisPoint,
unzoomThisPoint: unzoomThisPoint,
stack: stack,
level: level
};
return zoom;
function xyZoom(amount) {
var tempZoom = newZoom();
tempZoom.levelX = this.levelX + amount;
tempZoom.levelY = this.levelY + amount;
tempZoom.container = this.container;
tempZoom.parentZoom = this.parentZoom;
if (this.container.frame.canYouZoomHere(tempZoom)) {
/* Now we displace */
this.levelX = this.levelX + amount;
this.levelY = this.levelY + amount;
if (this.levelX < -50) {
this.levelX = -50; // There is a minimun zoom level.
}
if (this.levelY < -50) {
this.levelY = -50; // There is a minimun zoom level.
}
return true;
}
return false;
}
function xZoom(amount) {
this.levelX = this.levelX + amount;
if (this.levelX < -10) {
this.levelX = -10; // There is a minimun zoom level.
}
updateBallsTargets();
}
function yZoom(amount) {
this.levelY = this.levelY + amount;
if (this.levelY < -10) {
this.levelY = -10; // There is a minimun zoom level.
}
updateBallsTargets();
}
function rZoom(amount) {
this.levelR = this.levelR + amount;
var zoomLimit = - 1 / this.incrementR;
if (zoom.levelR <= zoomLimit + 1) {
zoom.levelR = zoomLimit + 2; // There is a minimun zoom level.
}
updateBallsTargets();
}
function mZoom(amount) {
this.levelM = this.levelM + amount;
var zoomLimit = - 1 / this.incrementM;
if (zoom.levelM <= zoomLimit + 1) {
zoom.levelM = zoomLimit + 2; // There is a minimun zoom level.
}
updateBallsTargets();
}
function zoomThisPoint(point) {
if (this.parentZoom !== undefined) {
point = this.parentZoom.zoomThisPoint(point);
}
/* The zoom center is needed to calculate the zoom for each point within this container. */
zoomAxisCenter = {
x: this.container.frame.width / 2,
y: this.container.frame.height / 2
}
/* Guess what? yes, the axis center itself must be framed and displaced before being used.*/
zoomAxisCenter = this.container.frame.frameThisPoint(zoomAxisCenter);
zoomAxisCenter = this.container.displacement.displaceThisPoint(zoomAxisCenter);
var diffX = point.x - zoomAxisCenter.x ;
point.x = zoomAxisCenter.x + diffX + diffX * this.incrementX * this.levelX;
var diffY = point.y - zoomAxisCenter.y;
point.y = zoomAxisCenter.y + diffY + diffY * this.incrementY * this.levelY;
return point;
}
function unzoomThisPoint(pointWithZoom) {
if (this.parentZoom !== undefined) {
pointWithZoom = this.parentZoom.unzoomThisPoint(pointWithZoom);
}
/* The zoom center is needed to calculate the zoom for each point within this container. */
zoomAxisCenter = {
x: this.container.frame.width / 2,
y: this.container.frame.height / 2
}
/* Guess what? yes, the axis center itself must be framed and displaced before being used.*/
zoomAxisCenter = this.container.frame.frameThisPoint(zoomAxisCenter);
zoomAxisCenter = this.container.displacement.displaceThisPoint(zoomAxisCenter);
var pointWithoutZoom = {
x: 0,
y: 0
}
pointWithoutZoom.x = (pointWithZoom.x - zoomAxisCenter.x) / (1 + this.incrementX * this.levelX) + zoomAxisCenter.x;
pointWithoutZoom.y = (pointWithZoom.y - zoomAxisCenter.y) / (1 + this.incrementY * this.levelY) + zoomAxisCenter.y;
return pointWithoutZoom;
}
function level() {
/* This function provides a sense of the zoom level all through the stack of containers object's zoom. */
var fullLevel = 0;
if (this.parentZoom !== undefined) {
fullLevel = this.parentZoom.level();
}
fullLevel = fullLevel + (this.levelX + this.levelY) / 2;
return fullLevel;
}
function stack() {
/* This function provides the factor by which the stack of cointainers need to be multiplied to aquire the final zoom. */
var fullStack = {
x: 1,
y: 1
}
if (this.parentZoom !== undefined) {
fullStack = this.parentZoom.stack();
}
fullStack.x = fullStack.x + fullStack.x * this.levelX * this.incrementX;
fullStack.y = fullStack.y + fullStack.y * this.levelY * this.incrementY;
return fullStack;
}
}
+89
View File
@@ -0,0 +1,89 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Advanced Algos</title>
<script type="text/javascript" src="FileServer.js"></script>
<script type="text/javascript" src="SplashScreen.js"></script>
<script type="text/javascript" src="Canvas.js"></script>
<script type="text/javascript" src="Button.js"></script>
<script type="text/javascript" src="TextButton.js"></script>
<script type="text/javascript" src="EventHandler.js"></script>
<script type="text/javascript" src="Frame.js"></script>
<script type="text/javascript" src="Container.js"></script>
<script type="text/javascript" src="TimeMachine.js"></script>
<script type="text/javascript" src="ChartSpace.js"></script>
<script type="text/javascript" src="FloatingSpace.js"></script>
<script type="text/javascript" src="Ball.js"></script>
<script type="text/javascript" src="Balls.js"></script>
<script type="text/javascript" src="Candle.js"></script>
<script type="text/javascript" src="VolumeBar.js"></script>
<script type="text/javascript" src="Order.js"></script>
<script type="text/javascript" src="Trade.js"></script>
<script type="text/javascript" src="MarketTrades.js"></script>
<script type="text/javascript" src="PriceChart.js"></script>
<script type="text/javascript" src="SpreadChart.js"></script>
<script type="text/javascript" src="ChartUtilities.js"></script>
<script type="text/javascript" src="OrderBookDepthChart.js"></script>
<script type="text/javascript" src="TimelineChart.js"></script>
<script type="text/javascript" src="OrderBookSnapShot.js"></script>
<script type="text/javascript" src="OrderBook.js"></script>
<script type="text/javascript" src="OrderBookChart.js"></script>
<script type="text/javascript" src="OrderBookFilesCursor.js"></script>
<script type="text/javascript" src="Resistance.js"></script>
<script type="text/javascript" src="ChartGrid.js"></script>
<script type="text/javascript" src="MarketIndex.js"></script>
<script type="text/javascript" src="DailyFileCursor.js"></script>
<script type="text/javascript" src="TradesCursor.js"></script>
<script type="text/javascript" src="Animation.js"></script>
<script type="text/javascript" src="Physics.js"></script>
<script type="text/javascript" src="Zoom.js"></script>
<script type="text/javascript" src="Displace.js"></script>
<script type="text/javascript" src="PlotArea.js"></script>
<script type="text/javascript" src="Utilities.js"></script>
<script type="text/javascript" src="ViewPort.js"></script>
<script type="text/javascript" src="AggregatedOrdersArray.js"></script>
<script type="text/javascript" src="Dashboard.js"></script>
<script type="text/javascript" src="AccumulatedVolumeBar.js"></script>
<script type="text/javascript" src="Azure/azure-storage.common.js"></script>
<script type="text/javascript" src="Azure/azure-storage.file.js"></script>
<script type="text/javascript" src="Panels/ControlPanel.js"></script>
<script type="text/javascript" src="Panels/ChartLayersPanel.js"></script>
<script type="text/javascript" src="Panels/BotsLayersPanel.js"></script>
<script type="text/javascript" src="Panels/CurrentCandlePanel.js"></script>
<script type="text/javascript" src="Panels/CurrentVolumePanel.js"></script>
<script type="text/javascript" src="Panels/OrderBookPanel.js"></script>
<script type="text/javascript" src="VolumeTechnicalAnalisys/Stairs.js"></script>
<script type="text/javascript" src="CandleTechnicalAnalisys/Stairs.js"></script>
<script type="text/javascript" src="CandleTechnicalAnalisys/Support.js"></script>
<script type="text/javascript" src="CandleTechnicalAnalisys/Resistance.js"></script>
<script type="text/javascript" src="CandleTechnicalAnalisys/HighLowFlag.js"></script>
<script type="text/javascript" src="ChartLayers/OrderBooksChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/ForecastChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/CandleTechnicalAnalisysChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/VolumeTechnicalAnalisysChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/AccumulatedVolumeChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/CandeStickChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/VolumeChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/SupportResistanceChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/HighLowChartLayer.js"></script>
<script type="text/javascript" src="ChartLayers/AllTimeChartLayer.js"></script>
<script type="text/javascript" src="Indicators/LRC.js"></script>
<script type="text/javascript" src="ChartLayers/LinearRegressionCurve.js"></script>
<style type="text/css">
browserCanvas {
border: 1px solid black;
}
</style>
</head>
<body id="body" style="margin: 0px; padding: 0px; border: 0px; overflow:hidden;" onload="dashboardStart();">
<canvas id="canvas" width="1400" height="600" border="0">
></canvas>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
{
"name": "browser",
"version": "0.0.0",
"description": "browser",
"main": "server.js",
"author": {
"name": "Luis"
}
}
+333
View File
@@ -0,0 +1,333 @@
const MODULE_NAME = "Node Server";
const START_BROWSER_APP = true;
const FILE_PATH = '../../AAlgos/Data';
///const DATABASE_MODULE = require('../../Picha - API/Picha/Database');
//const database = DATABASE_MODULE.newDatabase();
try {
// database.connectToServer(startHtttpServer);
}
catch (err) {
//console.log(err);
}
//'use strict';
var http = require('http');
var port = process.env.PORT || 1337;
startHtttpServer();
function onRequestReceivedFromBrowser(request, response) {
var htmlResponse;
var requestParameters = request.url.split("/");
switch (requestParameters[1]) {
case "index-files":
{
respondWithFile(FILE_PATH + '/index-files/' + requestParameters[2], response);
}
break;
case "daily-files":
{
respondWithFile(FILE_PATH + '/daily-files/' + requestParameters[2], response);
}
break;
case "other-files":
{
respondWithFile(FILE_PATH + '/other-files/' + requestParameters[2], response);
}
break;
case "all-times":
{
respondWithFile(FILE_PATH + '/all-times/' + requestParameters[2], response);
}
break;
case "order-books":
{
respondWithFile(FILE_PATH + '/order-books/' + requestParameters[2] + "/" + requestParameters[3] + "/" + requestParameters[4] + "/" + requestParameters[5] + "/" + requestParameters[6] + "/" + requestParameters[7], response);
}
break;
case "aggregatted-order-books":
{
respondWithFile(FILE_PATH + '/aggregatted-order-books/' + requestParameters[2] + "/" + requestParameters[3] + "/" + requestParameters[4] + "/" + requestParameters[5] + "/" + requestParameters[6] + "/" + requestParameters[7], response);
}
break;
case "CandleTechnicalAnalisys":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "VolumeTechnicalAnalisys":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "Panels":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "ChartLayers":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "Indicators":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "Azure":
{
respondWithFile('./' + requestParameters[1] + '/' + requestParameters[2], response);
}
break;
case "lastTrades":
{
const marketId = requestParameters[2];
const exchangeId = requestParameters[3];
const sqlQuery = "SELECT TOP 100000 "
+ " InternalExchangeTradeId AS Id, "
+ " Type, "
+ " Rate, "
+ " AmountAssetA AS AmountA, "
+ " AmountAssetB AS AmountB, "
+ " Timestamp "
+ " FROM Trades "
+ " WHERE "
+ " IdMarket = " + marketId + " "
+ " AND "
+ " IdExchange = " + exchangeId + " "
+ " ORDER BY IdExchange ASC, IdMarket ASC, InternalExchangeTradeId DESC"
;
////console.log("About to execute: " + sqlQuery);
/* Then we execute the query */
database.executeSQL(sqlQuery, function (err, resultSet) {
//console.log("Query executed: " + sqlQuery);
var myJsonString = JSON.stringify(resultSet);
////console.log(myJsonString);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write(myJsonString);
response.end("\n");
}
);
}
break;
case "trades":
{
const marketId = requestParameters[2];
const exchangeId = requestParameters[3];
const idBegin = unescape(requestParameters[4]);
const idEnd = unescape(requestParameters[5]);
const sqlQuery = "SELECT "
+ " InternalExchangeTradeId AS Id, "
+ " Type, "
+ " Rate, "
+ " AmountAssetA AS AmountA, "
+ " AmountAssetB AS AmountB, "
+ " Timestamp "
+ " FROM Trades "
+ " WHERE "
+ " IdExchange = " + exchangeId + " "
+ " AND "
+ " IdMarket = " + marketId + " "
+ " AND "
+ " InternalExchangeTradeId >= " + idBegin + " "
+ " AND "
+ " InternalExchangeTradeId <= " + idEnd + " "
+ " ORDER BY IdExchange, IdMarket, InternalExchangeTradeId "
;
let records = idEnd - idBegin;
console.log("Records Requested: " + records + " idBegin = " + idBegin + " idEnd = " + idEnd);
/* Then we execute the query */
database.executeSQL(sqlQuery, function (err, resultSet) {
//console.log("Query executed: " + sqlQuery);
var myJsonString = JSON.stringify(resultSet);
////console.log(myJsonString);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write(myJsonString);
response.end("\n");
}
);
}
break;
case "orderbook":
{
const marketId = requestParameters[2];
const datetimeBegin = unescape(requestParameters[3]);
const datetimeEnd = unescape(requestParameters[4]);
var sqlQuery = "SELECT "
+ " Id, "
+ " Rate, "
+ " Amount * Rate AS AmountA, "
+ " Amount AS AmountB, "
+ " Type AS Type, "
+ " DatetimeIn AS DatetimeIn, "
+ " ISNULL(DatetimeOut, '3000-01-01') AS DatetimeOut "
+ " FROM OrderBooks "
+ " WHERE "
+ " ( "
+ " IdMarket = " + marketId + " "
+ " ) "
+ " AND "
+ " ( "
+ " DatetimeIn <= '" + datetimeEnd + "' "
+ " ) "
+ " AND "
+ " ( "
+ " ISNULL(DatetimeOut, '3000-01-01') > '" + datetimeBegin + "' "
+ " ) "
;
//console.log(sqlQuery);
/* Then we execute the query */
database.executeSQL(sqlQuery, function (err, resultSet) {
var myJsonString = JSON.stringify(resultSet);
//console.log(myJsonString);
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write(myJsonString);
response.end("\n");
}
);
}
break;
default:
////console.log("Unknown request received from the browser: " + request.url);
if (requestParameters[1] === "") {
requestParameters[1] = "index.html";
}
respondWithFile("" + requestParameters[1], response);
}
function sendResponseToBrowser(htmlResponse) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(htmlResponse);
response.end("\n");
}
}
function respondWithFile(fileName, response) {
let fs = require('fs');
try {
fs.readFile(fileName, onFileRead);
function onFileRead(err, file) {
try {
let htmlResponse = file.toString();
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
response.setHeader("Access-Control-Allow-Origin", "*"); // Allows to access data from other domains.
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(htmlResponse);
response.end("\n");
console.log("File Sent: " + fileName);
//
}
catch (err) {
returnEmptyArray();
console.log("File Not Found: " + fileName);
}
}
}
catch (err) {
returnEmptyArray();
}
function returnEmptyArray() {
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write("[]");
response.end("\n");
}
}
function startHtttpServer() {
if (START_BROWSER_APP === true) {
try {
gWebServer = http.createServer(onRequestReceivedFromBrowser).listen(port);
}
catch (err) {
console.log(err);
}
}
}
+791
View File
@@ -0,0 +1,791 @@
function newOrderBookChart() {
/*
This particular chart, plots information valid at a certain point in time. That menas that first it needs to get that information, and it also
has to discard information that is not valid anymore. There is one issue: some graphics elements are displayed and animated, like balls, that
means that every time this chart request new info, it can not destroy all the current orders it is based on, since, if they are still valid
for the next period of time, recreating them would men producing a glinch on the visualization. So that means that every time that the time period
changes, it needs not only to incorporate new orders, but also it needs to eliminate the ones that are out of scope.
*/
var datetime;
var orderBookChart = {
setDatetime: setDatetime,
isInitialized: false,
container: undefined,
plotArea: undefined,
draw: draw,
getContainer: getContainer, // returns the inner most container that holds the point received by parameter.
initialize: initialize
};
/*
Here we will define the two arrays that will contain mostly the points to be plotted on the chart.
These arrays contains an array that have the following structure:
0. Rate
1. Amount A This is the SUM of Amounts A that belongs to this point in the chart.
2. The SUM of Amount A This is the cumulative SUM of SUMs of Amounts A, begining from the smaller rate and going up.
3. A Label Ball object
*/
var orderBookAsksChartPoints = [];
var orderBookBidsChartPoints = [];
var ballsOrdersQueue = []; // This is the queue of balls waiting for the order to be added to the array to be displayed.
var orderBallsReleaseTimer;
var container = newContainer();
container.initialize();
orderBookChart.container = container;
container.displacement.containerName = "Order Book Chart";
container.zoom.containerName = "Order Book Chart";
container.frame.containerName = "Order Book Chart";
var orderBookSnapShot = newOrderBookSnapShot();
return orderBookChart;
function initialize() {
orderBookSnapShot.initialize();
orderBookSnapShot.eventHandler.listenToEvent('Order Added', onOrderAdded, undefined);
orderBookSnapShot.eventHandler.listenToEvent('Order Removed', onOrderRemoved, undefined);
orderBookSnapShot.setDatetime(datetime);
orderBallsReleaseTimer = setInterval(onReleaseOneMoreBall, 100);
// clearTimeout(orderBallsReleaseTimer); Use this to cancel the timer.
}
function getContainer(point) {
var container;
/* First we check if this point is inside this space. */
if (this.container.frame.isThisPointHere(point) === true) {
return this.container;
} else {
/* This point does not belong to this space. */
return undefined;
}
}
/*
FUNCTIONS RELATED TO "HANDLING EVENTS"
*/
function onOrderAdded() {
}
function onOrderRemoved() {
}
function onOrderBookChanged() {
/*
Fresh data about the order book has just arrived. We need to take it an put it in the right way so that
this chart can show what it is supposed to show.
*/
/* Since the range of the data might change, we must calculate the plotArea everytime new data arrives. */
var plotArea = newPlotArea();
orderBookChart.plotArea = plotArea;
orderBookChart.plotArea.initialize(
orderBookChart.orderBook.server.orderBookStatistics.resultSet["row 1"].MIN_Rate,
orderBookChart.orderBook.server.orderBookStatistics.resultSet["row 2"].MAX_Rate,
orderBookChart.container.frame.width
);
/* Balls are being created, before they enter into the floating space. */
transformRecivedOrdersIntoOrderBalls();
orderBookChart.isInitialized = true;
}
function setDatetime(newDatetime) {
datetime = newDatetime;
orderBookChart.orderBookSnapShot.setDatetime(datetime);
}
function onReleaseOneMoreBall() {
/*
Orders that are queued to be displayed, are released, one by one every time this function is executed.
With released, we mean that are pushed to an array of balls that are currently rendered at the Floating Space.
*/
if (ballsOrdersQueue.length > 0) {
/* We take the first order in the queue and push it to the balls array. */
var ball = ballsOrdersQueue.shift();
balls.push(ball);
orderBookChart.addOrder(ball.linkedObject); // We add the order linked to this ball to the order book.
updateBallsTargets(); // This will recalculate the target for the new ball added.
}
}
/*
FUNCTIONS RELATED TO "PLOTTING THE CHART"
*/
function drawOrderBookChart() {
/*
This function is responsible for plotting the chart onto the browser canvas. It assumes that there exists 2 arrays, containing
the points already calculated to be plotted. Those calculations happens when a new order is added to the chart, in this function
we just plot whatever is already calculated.
*/
/* The first part of this function will plot BIDs, the second one will plot the ASKs. */
if (orderBookBidsChartPoints.length > 0) {
/* We calculate the first points of the chart. These are not points representing orders, but the lower part of the hill plotted. */
var maxBasePoint = {
x: (orderBookBidsChartPoints[orderBookBidsChartPoints.length - 1][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.plotArea.x, // We take the first Order Rate on the array for this.
y: orderBookChart.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (orderBookBidsChartPoints[0][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.x, // We take the first Order Rate on the array for this.
y: orderBookChart.container.frame.height * 5 / 7
};
/* We make the point relative to the current frame */
maxBasePoint = orderBookChart.container.frame.frameThisPoint(maxBasePoint);
minBasePoint = orderBookChart.container.frame.frameThisPoint(minBasePoint);
/* We add the possible displacement */
maxBasePoint = orderBookChart.container.displacement.displaceThisPoint(maxBasePoint);
minBasePoint = orderBookChart.container.displacement.displaceThisPoint(minBasePoint);
/* We apply the zoom factor. */
minBasePoint = orderBookChart.container.zoom.zoomThisPoint(minBasePoint);
maxBasePoint = orderBookChart.container.zoom.zoomThisPoint(maxBasePoint);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var sumY = 0;
for (var i = 0; i < orderBookBidsChartPoints.length; i++) {
sumY = sumY + orderBookBidsChartPoints[i][1];
var point = {
x: (orderBookBidsChartPoints[i][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.plotArea.x,
y: orderBookChart.container.frame.height * 5 / 7 - sumY
};
var rawPosition = {
x: point.x,
y: point.y
};
/* Frame the point */
point = orderBookChart.container.frame.frameThisPoint(point);
/* First we apply the displacement. */
point = orderBookChart.container.displacement.displaceThisPoint(point);
/* We apply the zoom factor. */
point = orderBookChart.container.zoom.zoomThisPoint(point);
browserCanvasContext.lineTo(point.x, point.y);
}
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(130, 180, 30, 0.9)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(30, 230, 30, 0.9)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
/* Ok, Now it is the turn of the ASKs, following is the code that plots them on the chart. */
if (orderBookAsksChartPoints.length > 0) {
/* We calculate the first point of the chart */
var maxBasePoint = {
x: (orderBookAsksChartPoints[orderBookAsksChartPoints.length - 1][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.plotArea.x, // We take the first Order Rate on the array for this.
y: orderBookChart.container.frame.height * 5 / 7
};
var minBasePoint = {
x: (orderBookAsksChartPoints[0][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.plotArea.x, // We take the first Order Rate on the array for this.
y: orderBookChart.container.frame.height * 5 / 7
};
/* We make the point relative to the current frame */
maxBasePoint = orderBookChart.container.frame.frameThisPoint(maxBasePoint);
minBasePoint = orderBookChart.container.frame.frameThisPoint(minBasePoint);
/* We add the possible displacement */
maxBasePoint = orderBookChart.container.displacement.displaceThisPoint(maxBasePoint);
minBasePoint = orderBookChart.container.displacement.displaceThisPoint(minBasePoint);
/* We apply the zoom factor. */
minBasePoint = orderBookChart.container.zoom.zoomThisPoint(minBasePoint);
maxBasePoint = orderBookChart.container.zoom.zoomThisPoint(maxBasePoint);
/* Lets start the drawing. */
browserCanvasContext.beginPath();
browserCanvasContext.moveTo(minBasePoint.x, minBasePoint.y);
var sumY = 0;
for (var i = 0; i < orderBookAsksChartPoints.length; i++) {
sumY = sumY + orderBookAsksChartPoints[i][1];
var point = {
x: (orderBookAsksChartPoints[i][0] - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.plotArea.x,
y: orderBookChart.container.frame.height * 5 / 7 - sumY
};
/* Frame the point */
point = orderBookChart.container.frame.frameThisPoint(point);
/* We add the possible displacement */
point = orderBookChart.container.displacement.displaceThisPoint(point);
/* We apply the zoom factor. */
point = orderBookChart.container.zoom.zoomThisPoint(point);
browserCanvasContext.lineTo(point.x, point.y);
}
browserCanvasContext.lineTo(maxBasePoint.x, maxBasePoint.y);
browserCanvasContext.lineTo(minBasePoint.x, minBasePoint.y);
browserCanvasContext.closePath();
browserCanvasContext.fillStyle = 'rgba(180, 130, 30, 0.75)';
browserCanvasContext.fill();
browserCanvasContext.strokeStyle = 'rgba(230, 30, 30, 0.75)';
browserCanvasContext.lineWidth = 1;
browserCanvasContext.stroke();
browserCanvasContext.closePath();
}
}
function drawXAxis() {
var step = (orderBookChart.plotArea.max.x - orderBookChart.plotArea.min.x) / 20;
var decimals;
/* Lets identify how many decimals are needed to be displayed. To do that we will chekck when is the first time that two consecutives points in the plotArea are different. */
for (var j = 0; j < 10; j++) {
var diff = (orderBookChart.plotArea.min.x + step * 2).toFixed(j) - (orderBookChart.plotArea.min.x + step * 1).toFixed(j);
if (diff !== 0 && decimals === undefined) {
decimals = j;
}
}
for (var i = 1; i < 20; i++) {
var point = {
x: orderBookChart.plotArea.min.x + step * i,
y: orderBookChart.container.frame.height * 6 / 7
};
browserCanvasContext.strokeStyle = 'rgba(10, 103, 201, 1)';
var fontSize = 10;// + orderBookChart.container.zoom.level();
browserCanvasContext.font = fontSize + 'px verdana';
/* Se the label */
var label = point.x.toFixed(decimals);
/* Now we transform x on the actual coordinate on the canvas. */
point.x = (point.x - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.scale.x; // Now x represent a coordinate on the canvas.
point = orderBookChart.container.frame.frameThisPoint(point);
point = orderBookChart.container.displacement.displaceThisPoint(point);
point = orderBookChart.container.zoom.zoomThisPoint(point);
browserCanvasContext.fillText(label, point.x, point.y);
}
}
function calculateOrdersSum(pointsArray) {
/* In this chart we represent the cummulative sum of all orders. That means that every time a new order arrives, we need to recalculate this. */
var sum = 0;
for (var i = 0; i < pointsArray.length; i++) {
sum = sum + pointsArray[i][1];
pointsArray[i][2] = sum;
}
}
/*
FUNCTIONS RELATED TO "NEW ORDERS"
*/
function removeOrder(order) {
/*
Here we will remove the order from the chart to be ploted. The chart has 2 parts: bids and asks, so we need to know which part to remove it from.
*/
if (order.type === 'Bid') {
removeOrderFromPointArray(order, orderBookBidsChartPoints);
calculateOrdersSum(orderBookBidsChartPoints); // We sum all the amounts into the 3rd column of the array.
} else {
removeOrderFromPointArray(order, orderBookAsksChartPoints);
calculateOrdersSum(orderBookAsksChartPoints); // We sum all the amounts into the 3rd column of the array.
}
}
function removeOrderFromPointArray(order, pointsArray) {
/* To remove an order, we simply scan the array received and when we find the same order rate, we substract the amount, and thats it. */
for (var i = 0; i < pointsArray.length; i++) {
if (pointsArray[i][0] === order.rate) { // We find the item in the pointArray where the rate is the same as the orders rate.
pointsArray[i][1] = pointsArray[i][1] - order.amountA;
if (pointsArray[i][1] === 0) { // If we reach zero, then there is no reason to keep this element in the array.
pointsArray.splice(i, 1); // This means remove this item from the array.
}
}
}
}
function addOrder(order) {
/*
This is the first function executed when a new order arrives. Here we still don't know if it is an ASK or BID. From here on we
do all the things needed to incorporate this new order to the chart.
*/
var pointIndex;
if (order.type === 'Bid') {
pointIndex = addNewBidOrder(order); // We add the new order to the array, if necesary.
calculateOrdersSum(orderBookBidsChartPoints); // We sum all the amounts into the 3rd column of the array.
//if (pointIndex >= 0) { // < 0 means that the amount of the order was summed into an existing item of the array.
// var ball;
// ball = addNewLabelBall(pointIndex, order.type, order.rate, 'rgba(30, 130, 30, 0.65)'); // We add a new ball.
// orderBookBidsChartPoints[pointIndex][3] = ball;
// updateLabelBallsLData(orderBookBidsChartPoints); // We update the labels of the balls we the new values, resulting of the sum calculation.
//}
} else {
pointIndex = addNewAskOrder(order);
calculateOrdersSum(orderBookAsksChartPoints); // We sum all the amounts into the 3rd column of the array.
//if (pointIndex >= 0) { // < 0 means that the amount of the order was summed into an existing item of the array.
// var ball;
// ball = addNewLabelBall(pointIndex, order.type, order.rate, 'rgba(130, 30, 30, 0.65)'); // We add a new ball.
// orderBookAsksChartPoints[pointIndex][3] = ball;
// updateLabelBallsLData(orderBookAsksChartPoints);
//}
}
}
function addNewBidOrder(order) {
/*
Everytime a new order arrives, we need to add it to the array that contains all the chart points for this type of order.
To add it, we need to follow certain rules, that are defined by this type of chart. This is what this function does for BID orders.
*/
if (orderBookBidsChartPoints.length === 0) {
orderBookBidsChartPoints.push([order.rate, order.amountA, 0, undefined]); // There it goes the first element of the order book.
return 0;
} else {
for (var i = 0; i < orderBookBidsChartPoints.length; i++) {
try {
if (order.rate < orderBookBidsChartPoints[i][0] && order.rate > orderBookBidsChartPoints[i + 1][0]) {
orderBookBidsChartPoints.splice(i + 1, 0, [order.rate, order.amountA, 0, undefined]);
return i + 1;
}
} catch (err) {
// It is fine if that does not work. It might be because the index i+1 does not exist.
}
if (order.rate === orderBookBidsChartPoints[i][0]) {
/* Orders with the exact same rate that previous orders on the order book, are added to the same item of the arrray. */
orderBookBidsChartPoints[i][1] = orderBookBidsChartPoints[i][1] + order.rate;
return -1; // This means that no new item was added.
} else {
if (order.rate > orderBookBidsChartPoints[i][0] && i === 0) {
orderBookBidsChartPoints.splice(i, 0, [order.rate, order.amountA, 0, undefined]);
return i;
} else {
if (order.rate < orderBookBidsChartPoints[i][0] && i === orderBookBidsChartPoints.length - 1) {
orderBookBidsChartPoints.push([order.rate, order.amountA, 0, undefined]);
return orderBookBidsChartPoints.length - 1;
}
}
}
}
}
}
function addNewAskOrder(order) {
/*
Everytime a new order arrives, we need to add it to the array that contains all the chart points for this type of order.
To add it, we need to follow certain rules, that are defined by this type of chart. This is what this function does for ASK orders.
*/
if (orderBookAsksChartPoints.length === 0) {
orderBookAsksChartPoints.push([order.rate, order.amountA, 0, undefined]); // There it goes the first element of the order book.
return 0;
} else {
for (var i = 0; i < orderBookAsksChartPoints.length; i++) {
try {
if (order.rate > orderBookAsksChartPoints[i][0] && order.rate < orderBookAsksChartPoints[i + 1][0]) {
orderBookAsksChartPoints.splice(i + 1, 0, [order.rate, order.amountA, 0, undefined]);
return i + 1;
}
} catch (err) {
// It is fine if that does not work. It might be because the index i+1 does not exist.
}
if (order.rate === orderBookAsksChartPoints[i][0]) {
/* Orders with the exact same rate that previous orders on the order book, are added to the same item of the arrray. */
orderBookAsksChartPoints[i][1] = orderBookAsksChartPoints[i][1] + order.rate;
return -1;
} else {
if (order.rate < orderBookAsksChartPoints[i][0]) {
orderBookAsksChartPoints.splice(i, 0, [order.rate, order.amountA, 0, undefined]);
return i;
} else {
if (order.rate > orderBookAsksChartPoints[i][0] && i === orderBookAsksChartPoints.length - 1) {
orderBookAsksChartPoints.push([order.rate, order.amountA, 0, undefined]);
return orderBookAsksChartPoints.length - 1;
}
}
}
}
}
}
/*
FUNCTIONS RELATED TO "THE ANIMATION"
*/
function draw() {
/* This function is meant to be executed to draw the whole chart, for instance, as part of some animation loop. */
this.container.frame.draw();
if (orderBookChart.isInitialized === true) {
drawOrderBookChart();
drawXAxis();
}
}
/*
FUNCTIONS RELATED TO "ORDER BALLS"
*/
function transformRecivedOrdersIntoOrderBalls() {
/*
Every new order we receive, we automatically transform it into a new ball. That doesnt mean that the ball is going to be
displayed right away, but anyway we have it ready for that.
*/
var totalRows = Object.keys(orderBookChart.orderBook.server.orderBookData.resultSet).length;
for (var i = 1; i <= totalRows; i++) {
var row = orderBookChart.orderBook.server.orderBookData.resultSet["row " + i];
/* We move the information from the result set to an order object, and use that from now on. */
var order = newOrder(undefined, row.Type, row.Rate, row.AmountA, row.AmountB, undefined, undefined);
/* Position of the ball without displacement or zoon. */
var rawPosition = {
x: (order.rate - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.scale.x,
y: orderBookChart.container.frame.height * 5 / 7
};
var ball = newBall();
ball.container = orderBookChart.container;
ball.radomizeCurrentSpeed();
ball.friction = .995;
ball.rawPosition = rawPosition;
ball.initializeMass(order.amountA * 5);
ball.initializeRadius(order.amountA * 3);
ball.initializeTargetPosition();
ball.radomizeCurrentPosition(ball.targetPosition);
ball.linkedObject = order;
ball.linkedObjectType = "order";
if (order.type === 'Bid') {
ball.fillStyle = 'rgba(102, 204, 0, 0.75)';
} else {
ball.fillStyle = 'rgba(222, 105, 42, 0.75)';
}
if (order.type === 'Bid') {
ball.labelStrokeStyle = 'rgba(255, 255, 255, 1)';
} else {
ball.labelStrokeStyle = 'rgba(255, 255, 255, 1)';
}
ball.labelFirstText = order.amountA;
ball.labelSecondText = order.rate;
ballsOrdersQueue.push(ball);
}
}
/*
FUNCTIONS RELATED TO "LABEL BALLS"
*/
function addNewLabelBall(id, type, rate, fillStyle) {
/* This function is used to create new balls, representing labels of each point on the chart. */
var rawPosition = {
x: (rate - orderBookChart.plotArea.min.x) * orderBookChart.plotArea.scale.x,
y: orderBookChart.container.frame.height * 5 / 7
};
var ball = newBall();
ball.container = orderBookChart.container;
ball.radomizeCurrentPosition(rawPosition);
ball.radomizeCurrentSpeed();
ball.friction = .995;
ball.rawPosition = rawPosition;
ball.initializeMass(15);
ball.initializeRadius(3);
ball.initializeTargetPosition();
ball.fillStyle = fillStyle;
ball.labelStrokeStyle = 'rgba(255, 255, 255, 1)';
ball.labelFirstText = 0; //.toFixed(4);
ball.labelSecondText = rate.toFixed(8);
balls.push(ball);
return ball;
}
function updateLabelBallsLData(pointsArray) {
/* When a new order arrives to the chart, all labels of balls representing points in the chart must be updated. */
var ball;
var sum;
for (var i = 0; i < pointsArray.length; i++) {
/* We update the balls label. */
ball = pointsArray[i][3];
sum = pointsArray[i][2];
ball.labelFirstText = sum.toFixed(2);
/* We update the balls raw position. */
var rawPositionY = orderBookChart.container.frame.height * 5 / 7 - sum;
ball.rawPosition.y = rawPositionY;
}
}
}