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25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/**

 * ═══════════════════════════════════════════════════════════════════

 * TRADINGVIEW STYLE CHARTS

 * Professional Trading Charts with Advanced Features

 * ═══════════════════════════════════════════════════════════════════

 */

// Chart instances storage
const tradingViewCharts = {};

/**

 * Create TradingView-style candlestick chart

 */
export function createCandlestickChart(canvasId, data, options = {}) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return null;

    // Destroy existing chart
    if (tradingViewCharts[canvasId]) {
        tradingViewCharts[canvasId].destroy();
    }

    const {
        symbol = 'BTC',
        timeframe = '1D',
        showVolume = true,
        showIndicators = true
    } = options;

    // Process candlestick data
    const labels = data.map(d => new Date(d.time).toLocaleDateString());
    const opens = data.map(d => d.open);
    const highs = data.map(d => d.high);
    const lows = data.map(d => d.low);
    const closes = data.map(d => d.close);
    const volumes = data.map(d => d.volume || 0);

    // Determine colors based on price movement
    const colors = data.map((d, i) => {
        if (i === 0) return closes[i] >= opens[i] ? '#10B981' : '#EF4444';
        return closes[i] >= closes[i - 1] ? '#10B981' : '#EF4444';
    });

    const datasets = [
        {
            label: 'Price',
            data: closes,
            borderColor: '#00D4FF',
            backgroundColor: 'rgba(0, 212, 255, 0.1)',
            borderWidth: 2,
            fill: true,
            tension: 0.1,
            pointRadius: 0,
            pointHoverRadius: 6,
            pointHoverBackgroundColor: '#00D4FF',
            pointHoverBorderColor: '#fff',
            pointHoverBorderWidth: 2,
            yAxisID: 'y'
        }
    ];

    if (showVolume) {
        datasets.push({
            label: 'Volume',
            data: volumes,
            type: 'bar',
            backgroundColor: colors.map(c => c + '40'),
            borderColor: colors,
            borderWidth: 1,
            yAxisID: 'y1',
            order: 2
        });
    }

    tradingViewCharts[canvasId] = new Chart(ctx, {
        type: 'line',
        data: { labels, datasets },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                    labels: {
                        usePointStyle: true,
                        padding: 15,
                        font: {
                            size: 12,
                            weight: 600,
                            family: "'Manrope', sans-serif"
                        },
                        color: '#E2E8F0'
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(15, 23, 42, 0.98)',
                    titleColor: '#00D4FF',
                    bodyColor: '#E2E8F0',
                    borderColor: 'rgba(0, 212, 255, 0.5)',
                    borderWidth: 1,
                    padding: 16,
                    displayColors: true,
                    boxPadding: 8,
                    usePointStyle: true,
                    callbacks: {
                        title: function(context) {
                            return context[0].label;
                        },
                        label: function(context) {
                            if (context.datasetIndex === 0) {
                                return `Price: $${context.parsed.y.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
                            } else {
                                return `Volume: ${context.parsed.y.toLocaleString()}`;
                            }
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false,
                        color: 'rgba(255, 255, 255, 0.05)'
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 11,
                            family: "'Manrope', sans-serif"
                        },
                        maxRotation: 0,
                        autoSkip: true,
                        maxTicksLimit: 12
                    },
                    border: {
                        display: false
                    }
                },
                y: {
                    type: 'linear',
                    position: 'left',
                    grid: {
                        color: 'rgba(255, 255, 255, 0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 11,
                            family: "'Manrope', sans-serif"
                        },
                        callback: function(value) {
                            return '$' + value.toLocaleString(undefined, { minimumFractionDigits: 0, maximumFractionDigits: 0 });
                        }
                    }
                },
                y1: showVolume ? {
                    type: 'linear',
                    position: 'right',
                    grid: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        display: false
                    }
                } : undefined
            }
        }
    });

    return tradingViewCharts[canvasId];
}

/**

 * Create advanced line chart with indicators

 */
export function createAdvancedLineChart(canvasId, priceData, indicators = {}) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return null;

    if (tradingViewCharts[canvasId]) {
        tradingViewCharts[canvasId].destroy();
    }

    const labels = priceData.map(d => new Date(d.time || d.timestamp).toLocaleDateString());
    const prices = priceData.map(d => d.price || d.value);

    // Calculate indicators
    const ma20 = indicators.ma20 || calculateMA(prices, 20);
    const ma50 = indicators.ma50 || calculateMA(prices, 50);
    const rsi = indicators.rsi || calculateRSI(prices, 14);

    const datasets = [
        {
            label: 'Price',
            data: prices,
            borderColor: '#00D4FF',
            backgroundColor: 'rgba(0, 212, 255, 0.1)',
            borderWidth: 2.5,
            fill: true,
            tension: 0.1,
            pointRadius: 0,
            pointHoverRadius: 6,
            yAxisID: 'y',
            order: 1
        }
    ];

    if (indicators.showMA20) {
        datasets.push({
            label: 'MA 20',
            data: ma20,
            borderColor: '#8B5CF6',
            backgroundColor: 'transparent',
            borderWidth: 1.5,
            borderDash: [5, 5],
            fill: false,
            tension: 0.1,
            pointRadius: 0,
            yAxisID: 'y',
            order: 2
        });
    }

    if (indicators.showMA50) {
        datasets.push({
            label: 'MA 50',
            data: ma50,
            borderColor: '#EC4899',
            backgroundColor: 'transparent',
            borderWidth: 1.5,
            borderDash: [5, 5],
            fill: false,
            tension: 0.1,
            pointRadius: 0,
            yAxisID: 'y',
            order: 3
        });
    }

    tradingViewCharts[canvasId] = new Chart(ctx, {
        type: 'line',
        data: { labels, datasets },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                    labels: {
                        usePointStyle: true,
                        padding: 15,
                        font: {
                            size: 12,
                            weight: 600,
                            family: "'Manrope', sans-serif"
                        },
                        color: '#E2E8F0'
                    }
                },
                tooltip: {
                    enabled: true,
                    backgroundColor: 'rgba(15, 23, 42, 0.98)',
                    titleColor: '#00D4FF',
                    bodyColor: '#E2E8F0',
                    borderColor: 'rgba(0, 212, 255, 0.5)',
                    borderWidth: 1,
                    padding: 16,
                    displayColors: true,
                    boxPadding: 8
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 11,
                            family: "'Manrope', sans-serif"
                        },
                        maxRotation: 0,
                        autoSkip: true
                    },
                    border: {
                        display: false
                    }
                },
                y: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 11,
                            family: "'Manrope', sans-serif"
                        },
                        callback: function(value) {
                            return '$' + value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
                        }
                    }
                }
            }
        }
    });

    return tradingViewCharts[canvasId];
}

/**

 * Calculate Moving Average

 */
function calculateMA(data, period) {
    const result = [];
    for (let i = 0; i < data.length; i++) {
        if (i < period - 1) {
            result.push(null);
        } else {
            const sum = data.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0);
            result.push(sum / period);
        }
    }
    return result;
}

/**

 * Calculate RSI (Relative Strength Index)

 */
function calculateRSI(data, period = 14) {
    const result = [];
    const gains = [];
    const losses = [];

    for (let i = 1; i < data.length; i++) {
        const change = data[i] - data[i - 1];
        gains.push(change > 0 ? change : 0);
        losses.push(change < 0 ? Math.abs(change) : 0);
    }

    for (let i = 0; i < data.length; i++) {
        if (i < period) {
            result.push(null);
        } else {
            const avgGain = gains.slice(i - period, i).reduce((a, b) => a + b, 0) / period;
            const avgLoss = losses.slice(i - period, i).reduce((a, b) => a + b, 0) / period;
            const rs = avgLoss === 0 ? 100 : avgGain / avgLoss;
            const rsi = 100 - (100 / (1 + rs));
            result.push(rsi);
        }
    }

    return result;
}

/**

 * Create volume chart

 */
export function createVolumeChart(canvasId, volumeData) {
    const ctx = document.getElementById(canvasId);
    if (!ctx) return null;

    if (tradingViewCharts[canvasId]) {
        tradingViewCharts[canvasId].destroy();
    }

    const labels = volumeData.map(d => new Date(d.time).toLocaleDateString());
    const volumes = volumeData.map(d => d.volume);
    const colors = volumeData.map((d, i) => {
        if (i === 0) return '#10B981';
        return volumes[i] >= volumes[i - 1] ? '#10B981' : '#EF4444';
    });

    tradingViewCharts[canvasId] = new Chart(ctx, {
        type: 'bar',
        data: {
            labels,
            datasets: [{
                label: 'Volume',
                data: volumes,
                backgroundColor: colors.map(c => c + '60'),
                borderColor: colors,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(15, 23, 42, 0.98)',
                    titleColor: '#00D4FF',
                    bodyColor: '#E2E8F0',
                    borderColor: 'rgba(0, 212, 255, 0.5)',
                    borderWidth: 1,
                    padding: 12
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 10,
                            family: "'Manrope', sans-serif"
                        }
                    },
                    border: {
                        display: false
                    }
                },
                y: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        color: '#94A3B8',
                        font: {
                            size: 10,
                            family: "'Manrope', sans-serif"
                        },
                        callback: function(value) {
                            if (value >= 1e9) return (value / 1e9).toFixed(2) + 'B';
                            if (value >= 1e6) return (value / 1e6).toFixed(2) + 'M';
                            if (value >= 1e3) return (value / 1e3).toFixed(2) + 'K';
                            return value;
                        }
                    }
                }
            }
        }
    });

    return tradingViewCharts[canvasId];
}

/**

 * Destroy chart

 */
export function destroyChart(canvasId) {
    if (tradingViewCharts[canvasId]) {
        tradingViewCharts[canvasId].destroy();
        delete tradingViewCharts[canvasId];
    }
}

/**

 * Update chart data

 */
export function updateChart(canvasId, newData) {
    if (tradingViewCharts[canvasId]) {
        tradingViewCharts[canvasId].data = newData;
        tradingViewCharts[canvasId].update();
    }
}