class CustomTradingChart extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.candles = [];
this.currentPrice = 7500;
}
connectedCallback() {
this.render();
this.canvas = this.shadowRoot.getElementById('chart-canvas');
this.ctx = this.canvas.getContext('2d');
this.resizeCanvas();
window.addEventListener('resize', () => this.resizeCanvas());
this.draw();
}
resizeCanvas() {
if (!this.canvas) return;
const rect = this.getBoundingClientRect();
this.canvas.width = rect.width;
this.canvas.height = 400;
this.draw();
}
updateChart(candles, currentPrice) {
this.candles = candles;
this.currentPrice = currentPrice;
this.draw();
}
render() {
this.shadowRoot.innerHTML = `
`;
}
draw() {
if (!this.ctx || !this.canvas) return;
const ctx = this.ctx;
const width = this.canvas.width;
const height = this.canvas.height;
// Clear canvas
ctx.clearRect(0, 0, width, height);
if (this.candles.length === 0) return;
// Calculate scales
const prices = this.candles.flatMap(c => [c.high, c.low]);
const minPrice = Math.min(...prices) * 0.999;
const maxPrice = Math.max(...prices) * 1.001;
const priceRange = maxPrice - minPrice;
const candleWidth = (width - 60) / this.candles.length * 0.8;
const spacing = (width - 60) / this.candles.length;
// Draw grid
ctx.strokeStyle = 'rgba(99, 102, 241, 0.1)';
ctx.lineWidth = 1;
for (let i = 0; i < 5; i++) {
const y = height - (height * (i / 4));
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
}
// Draw candles
this.candles.forEach((candle, i) => {
const x = i * spacing + 30;
const yOpen = height - ((candle.open - minPrice) / priceRange) * height;
const yClose = height - ((candle.close - minPrice) / priceRange) * height;
const yHigh = height - ((candle.high - minPrice) / priceRange) * height;
const yLow = height - ((candle.low - minPrice) / priceRange) * height;
const isRise = candle.close >= candle.open;
const color = isRise ? '#10b981' : '#f43f5e';
// Wick
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x + candleWidth / 2, yHigh);
ctx.lineTo(x + candleWidth / 2, yLow);
ctx.stroke();
// Body
ctx.fillStyle = color;
const bodyHeight = Math.max(Math.abs(yClose - yOpen), 1);
const bodyY = Math.min(yOpen, yClose);
ctx.fillRect(x, bodyY, candleWidth, bodyHeight);
});
// Draw current price line
const currentY = height - ((this.currentPrice - minPrice) / priceRange) * height;
ctx.strokeStyle = '#6366f1';
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(0, currentY);
ctx.lineTo(width, currentY);
ctx.stroke();
ctx.setLineDash([]);
// Update price label
const label = this.shadowRoot.getElementById('price-label');
if (label) {
label.textContent = this.currentPrice.toFixed(2);
label.style.top = `${currentY}px`;
}
}
}
customElements.define('custom-trading-chart', CustomTradingChart);