// Function to generate random OHLC data
function generateOHLCData(count) {
const data = new Array(count);
let open = 50; // Starting price
for (let i = 0; i < count; i++) {
const delta = Math.random() * 20 - 10; // Random movement between -10 and +10
const close = open + delta;
const high = Math.max(open, close) + Math.random() * 5; // Random overshoot up to 5
const low = Math.min(open, close) - Math.random() * 5; // Random undershoot up to 5
data[i] = { open, high, low, close };
open = close; // Next open starts where the last close was
}
return data;
}
// Convert RGB to normalized color values (0 to 1)
function rgbToNormalized(r, g, b) {
return [r / 255, g / 255, b / 255];
}
// Arrays to store the instanced meshes and wicks
const instancedMeshes = [];
const wickLineSegmentsArray = [];
// Create instanced candlesticks with chunking
function createInstancedCandlesticks(data, chunkSize) {
const barWidth = 1;
// Materials
const material = new THREE.MeshBasicMaterial({
color: 0xffffff, // Set base color to white
vertexColors: THREE.InstanceColor // Use per-instance colors
});
const maxCandlesticks = chunkData.length;
// Create instanced mesh for candlesticks
const instancedMesh = new THREE.InstancedMesh(geometryBar, material, maxCandlesticks);
const wickVertices = new Float32Array(maxCandlesticks * 6); // 2 points per wick, x,y,z per point
const wickColors = new Float32Array(maxCandlesticks * 6); // Color per vertex
const colorArray = new Float32Array(maxCandlesticks * 3); // Color per instance
for (let index = 0; index < maxCandlesticks; index++) {
const d = chunkData[index];
const isBullish = d.close >= d.open;
const height = Math.abs(d.close - d.open);
const y = (d.close + d.open) / 2;
// Set the position and scale for the body
dummy.position.set(currentX, y, 0);
dummy.scale.set(1, height, 1);
dummy.updateMatrix();
instancedMesh.setMatrixAt(index, dummy.matrix);
// Set color for each instance
const color = isBullish ? bullishColor : bearishColor;
colorArray.set(color, index * 3);
// Wick positions
const wickIndex = index * 6;
wickVertices[wickIndex] = currentX;
wickVertices[wickIndex + 1] = d.low;
wickVertices[wickIndex + 2] = 0;
wickVertices[wickIndex + 3] = currentX;
wickVertices[wickIndex + 4] = d.high;
wickVertices[wickIndex + 5] = 0;
// Wick colors (same color for both points)
wickColors.set([...color, ...color], wickIndex);
// Increment x for the next candlestick
currentX += barWidth * 1.5;
}
// Assign the instance colors to the instanced mesh
instancedMesh.instanceColor = new THREE.InstancedBufferAttribute(colorArray, 3);
// instancedMesh.instanceColor.needsUpdate = true; // Not strictly necessary here
// Add the instances to the scene
scene.add(instancedMesh);
instancedMeshes.push(instancedMesh);
// Create and add wick line segments to the scene
const wickGeometry = new THREE.BufferGeometry();
wickGeometry.setAttribute('position', new THREE.BufferAttribute(wickVertices, 3));
wickGeometry.setAttribute('color', new THREE.BufferAttribute(wickColors, 3)); // Add color to wicks
const wickLineSegments = new THREE.LineSegments(wickGeometry, wickMaterial);
scene.add(wickLineSegments);
wickLineSegmentsArray.push(wickLineSegments);
}
}
// Generate data and create instanced candlesticks
const ohlcData = generateOHLCData(5000000); // Adjust the number as needed
createInstancedCandlesticks(ohlcData, 5000); // Chunk size can be adjusted
// Zoom logic (based on mouse wheel and key modifiers)
const zoomSpeed = 0.8;
let visibilityUpdateTimeout; // Timeout variable for visibility updates
// Clear previous timeout if it exists
clearTimeout(visibilityUpdateTimeout);
// Set a new timeout to update visibility after a delay
visibilityUpdateTimeout = setTimeout(updateCandlestickVisibility, 100); // Adjust the delay as needed
}
// Function to update candlestick visibility based on zoom level
function updateCandlestickVisibility() {
const visibleWidth = camera.right - camera.left;
const candlestickWidth = 1.5; // Width of each candlestick including spacing
const visibleCandlesticks = visibleWidth / candlestickWidth;
// Adjust the threshold for visibility based on zoom level
const threshold = 1000;
// Panning functionality
let isPanning = false; // Track panning state
let isDraggingEndpoint = false; // Track endpoint dragging state
let selectedEndpointIndex = null; // Index of the selected endpoint (0 or 1)
const previousMousePosition = new THREE.Vector2(); // Store previous mouse position
// Raycaster for detecting line interaction
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
// Interactive line code
// Define line geometry and material
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const lineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-50, 0, 0),
new THREE.Vector3(50, 0, 0)
]);
const line = new THREE.Line(lineGeometry, lineMaterial);
line.frustumCulled = false; // Prevent the line from being culled
scene.add(line);
// Set the distance for grabbing the line (in world units)
let distanceForGrab = 2; // You can adjust this value to make grabbing easier
// Set the raycaster's line precision
raycaster.params.Line.threshold = distanceForGrab; // For Three.js r127 and above
// Predefine vectors to avoid excessive allocations
const mouseWorld = new THREE.Vector3();
const deltaWorld = new THREE.Vector3();
const currentMouse = new THREE.Vector2();
const previousMouseWorld = new THREE.Vector3();
// Mouse down event
function onMouseDown(event) {
if (event.button === 2) { // Right mouse button for panning
isPanning = true;
previousMousePosition.set(event.clientX, event.clientY);
} else if (event.button === 0) { // Left mouse button for line interaction
// Prepare raycaster
const rect = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
mouse.y = - ((event.clientY - rect.top) / rect.height) * 2 + 1;
code
raycaster.setFromCamera(mouse, camera);
// Check intersection with the line
const intersects = raycaster.intersectObject(line, true);
if (intersects.length > 0) {
// Clicked on the line
// Determine which endpoint is closer to the mouse
const positions = lineGeometry.attributes.position.array;
const lineStart = new THREE.Vector3(positions[0], positions[1], positions[2]);
const lineEnd = new THREE.Vector3(positions[3], positions[4], positions[5]);
mouseWorld.copy(intersects[0].point);
const distanceToStart = mouseWorld.distanceTo(lineStart);
const distanceToEnd = mouseWorld.distanceTo(lineEnd);
selectedEndpointIndex = (distanceToStart < distanceToEnd) ? 0 : 1;
isDraggingEndpoint = true;
// Set previous mouse position in NDC
previousMousePosition.set(mouse.x, mouse.y);
}
To achieve your desired effect of rendering a line chart when highly zoomed out, you can modify your code to display different levels of detail based on the zoom level:
Zoomed-in Level: Render everything, including the candlestick bodies and wicks.
Medium Zoomed-out Level: Render only the candle wicks, not the bodies.
Highly Zoomed-out Level: Render a simplified line chart representing the closing prices.
Below, I'll guide you through the necessary modifications to your code to implement this functionality.
1. Create the Line Chart
First, we'll create a line chart that represents your data when the user is highly zoomed out. We'll use the closing prices to draw the line chart.
Add the following code to create the line chart:
javascript
// Declare the line chart variable globally
let lineChart;
function createLineChart(data) {
const positions = new Float32Array(data.length * 3);
let currentX = 0;
const barWidth = 1.5; // Same spacing as candlesticks
for (let i = 0; i < data.length; i++) {
const d = data[i];
const y = d.close;
positions[i * 3] = currentX;
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = 0;
currentX += barWidth;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 }); // Green line
lineChart = new THREE.Line(geometry, material);
lineChart.visible = false; // Initially hide the line chart
scene.add(lineChart);
}
Call this function after generating your OHLC data:
javascript
// Generate data and create instanced candlesticks
const ohlcData = generateOHLCData(5000000); // Adjust the number as needed
createInstancedCandlesticks(ohlcData, 5000); // Chunk size can be adjusted
createLineChart(ohlcData); // Create the line chart
2. Update Visibility Based on Zoom Level
Next, we'll modify the updateCandlestickVisibility function to control the visibility of the candlestick bodies, wicks, and the line chart based on the zoom level.
Replace your existing updateCandlestickVisibility function with the following:
javascript
// Function to update candlestick visibility based on zoom level
function updateCandlestickVisibility() {
const visibleWidth = camera.right - camera.left;
const candlestickWidth = 1.5; // Width of each candlestick including spacing
const visibleCandlesticks = visibleWidth / candlestickWidth;
// Adjust thresholds for visibility based on zoom level
const bodiesThreshold = 1000; // Threshold for showing bodies
const wicksThreshold = 5000; // Threshold for showing wicks
// Determine visibility based on thresholds
const bodiesVisible = visibleCandlesticks <= bodiesThreshold;
const wicksVisible = visibleCandlesticks <= wicksThreshold && !bodiesVisible;
const lineChartVisible = !bodiesVisible && !wicksVisible;
// Update visibility of candlestick bodies
for (const mesh of instancedMeshes) {
mesh.visible = bodiesVisible;
}
// Update visibility of wicks
for (const wick of wickLineSegmentsArray) {
wick.visible = wicksVisible;
}
// Update visibility of line chart
if (lineChart) {
lineChart.visible = lineChartVisible;
}
}
Explanation:
Bodies Visibility: Candlestick bodies are visible when zoomed in close enough (visible candlesticks less than or equal to bodiesThreshold).
Wicks Visibility: Wicks are visible when zoomed out further but not beyond the wicksThreshold, and bodies are not visible.
Line Chart Visibility: The line chart is visible when both bodies and wicks are not visible (i.e., when zoomed out beyond wicksThreshold).
3. Adjust the Zoom Logic
Ensure that updateCandlestickVisibility is called whenever the zoom level changes.
Modify your onWheel function to call updateCandlestickVisibility directly without delay:
javascript
function onWheel(event) {
// Existing zoom code...
camera.updateProjectionMatrix();
// Update visibility immediately after zooming
updateCandlestickVisibility();
}
4. Call Visibility Update on Pan and Resize
You should also call updateCandlestickVisibility after panning or resizing the window to ensure the visibility updates accordingly.
Add the following line at the end of the onMouseMove function for panning:
javascript
// Update candlestick visibility after panning
updateCandlestickVisibility();
Ensure updateCandlestickVisibility is called in the onWindowResize function:
Rendering a line chart with millions of points can be performance-intensive. To optimize rendering when highly zoomed out, we'll sample the data to reduce the number of points in the line chart.
Modify the createLineChart function to accept a sampleRate parameter:
javascript
function createLineChart(data, sampleRate = 1) {
const sampledData = [];
for (let i = 0; i < data.length; i += sampleRate) {
sampledData.push(data[i]);
}
const positions = new Float32Array(sampledData.length * 3);
let currentX = 0;
const barWidth = 1.5 * sampleRate; // Adjust spacing based on sample rate
for (let i = 0; i < sampledData.length; i++) {
const d = sampledData[i];
const y = d.close;
positions[i * 3] = currentX;
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = 0;
currentX += barWidth;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.LineBasicMaterial({ color: 0x00ff00 }); // Green line
// Remove the old line chart if it exists
if (lineChart) {
scene.remove(lineChart);
}
lineChart = new THREE.Line(geometry, material);
lineChart.visible = false; // Initially hide the line chart
scene.add(lineChart);
}
Update the updateCandlestickVisibility function to recreate the line chart with appropriate sampling when zooming:
javascript
function updateCandlestickVisibility() {
const visibleWidth = camera.right - camera.left;
const candlestickWidth = 1.5; // Width of each candlestick including spacing
const visibleCandlesticks = visibleWidth / candlestickWidth;
// Adjust thresholds for visibility based on zoom level
const bodiesThreshold = 1000; // Threshold for showing bodies
const wicksThreshold = 5000; // Threshold for showing wicks
// Determine visibility based on thresholds
const bodiesVisible = visibleCandlesticks <= bodiesThreshold;
const wicksVisible = visibleCandlesticks <= wicksThreshold && !bodiesVisible;
const lineChartVisible = !bodiesVisible && !wicksVisible;
// Update visibility of candlestick bodies
for (const mesh of instancedMeshes) {
mesh.visible = bodiesVisible;
}
// Update visibility of wicks
for (const wick of wickLineSegmentsArray) {
wick.visible = wicksVisible;
}
// Update or recreate the line chart with appropriate sampling
if (lineChartVisible) {
const maxPoints = 2000; // Maximum points to display in the line chart
const sampleRate = Math.ceil(ohlcData.length / maxPoints);
createLineChart(ohlcData, sampleRate);
lineChart.visible = true;
} else {
if (lineChart) {
lineChart.visible = false;
}
}
}
Explanation:
Sample Rate Calculation: We calculate the sampleRate based on the total number of data points and the maximum number of points we want to render in the line chart. This reduces the number of points when zoomed out, improving performance.
Recreating the Line Chart: When the visibility changes, we recreate the line chart with the new sample rate.
6. Update Visibility on Animation Frame
To ensure that visibility updates correctly when the camera parameters change (e.g., during panning or zooming), call updateCandlestickVisibility in your animation loop.
Modify your animate function:
javascript
function animate() {
requestAnimationFrame(animate);
updateCandlestickVisibility();
renderer.render(scene, camera);
}
7. Additional Considerations
Performance Optimization: Continuously calling updateCandlestickVisibility and recreating the line chart can affect performance. If you notice any lag, you can implement a debounce mechanism or check for significant changes before updating the visibility or recreating the line chart.
Example Debounce Implementation:
javascript
let lastVisibilityUpdate = 0;
const visibilityUpdateInterval = 100; // In milliseconds
function animate() {
requestAnimationFrame(animate);
const now = Date.now();
if (now - lastVisibilityUpdate > visibilityUpdateInterval) {
updateCandlestickVisibility();
lastVisibilityUpdate = now;
}
renderer.render(scene, camera);
}
Threshold Adjustment: Adjust the bodiesThreshold, wicksThreshold, and maxPoints values to suit your application's performance and visual requirements.
Event Listeners: Ensure that all event listeners (e.g., for panning and zooming) correctly trigger visibility updates when necessary.
Full Updated Code Snippet
For clarity, here's how the modified sections of your code would look after implementing the above changes:
javascript
// Declare the line chart variable globally
let lineChart;
function createLineChart(data, sampleRate = 1) {
// ... (Code as shown above)
}
// Generate data and create instanced candlesticks
const ohlcData = generateOHLCData(5000000); // Adjust the number as needed
createInstancedCandlesticks(ohlcData, 5000); // Chunk size can be adjusted
createLineChart(ohlcData); // Create the line chart
// Function to update candlestick visibility based on zoom level
function updateCandlestickVisibility() {
// ... (Code as shown above)
}
// Modify the onWheel function
function onWheel(event) {
// ... (Existing zoom code)
camera.updateProjectionMatrix();
// Update visibility immediately after zooming
updateCandlestickVisibility();
}
// Modify the onMouseMove function to update visibility after panning
function onMouseMove(event) {
// ... (Existing panning and dragging code)
if (isPanning) {
// ... (Panning code)
// Update candlestick visibility after panning
updateCandlestickVisibility();
}
}
// Modify the onWindowResize function
function onWindowResize() {
// ... (Existing resize code)
// Update visibility after resizing
updateCandlestickVisibility();
}
// Render loop
function animate() {
requestAnimationFrame(animate);
updateCandlestickVisibility(); // Update visibility on each frame if needed
renderer.render(scene, camera);
}
Test and Adjust
Test the Zoom Levels: Zoom in and out to test if the candlestick bodies, wicks, and line chart appear and disappear at the desired zoom levels.
Adjust Thresholds: If necessary, adjust the bodiesThreshold, wicksThreshold, and maxPoints to achieve the smoothest performance and visual transition.
Monitor Performance: Keep an eye on the performance metrics (e.g., FPS) to ensure that the application remains responsive.
Note: The line chart will represent the data points using the closing prices. If you prefer to use a different price (e.g., average of high and low), adjust the y value accordingly in the createLineChart function.
Let me know if you have any questions or need further assistance with these modifications!