π Vanilla JavaScript Example
Complete vanilla JavaScript implementation that can be run directly in CodePen, CodeSandbox, or any web environment.
π Live Demo
CodePen Basic: https://codepen.io/Admin-GoCharting/pen/GgpVepqΒ CodePen Advanced: https://codepen.io/Admin-GoCharting/pen/xbwvBbeΒ CodeSandbox: https://codesandbox.io/s/gocharting-vanilla-jsΒ
π Complete Implementation
HTML Structure
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>GoCharting SDK - Vanilla JS Demo</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: white;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
}
.header {
text-align: center;
margin-bottom: 30px;
}
.header h1 {
font-size: 2.5rem;
margin-bottom: 10px;
background: linear-gradient(45deg, #00d4aa, #00a8ff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.header p {
font-size: 1.2rem;
opacity: 0.9;
}
.controls {
display: flex;
gap: 15px;
justify-content: center;
margin-bottom: 20px;
flex-wrap: wrap;
background: rgba(255, 255, 255, 0.1);
padding: 20px;
border-radius: 12px;
backdrop-filter: blur(10px);
}
.control-group {
display: flex;
flex-direction: column;
gap: 5px;
}
.control-group label {
font-size: 0.9rem;
font-weight: 600;
opacity: 0.9;
}
.controls select,
.controls button,
.controls input {
padding: 10px 15px;
border: none;
border-radius: 8px;
background: rgba(255, 255, 255, 0.2);
color: white;
font-size: 14px;
cursor: pointer;
transition: all 0.3s ease;
backdrop-filter: blur(5px);
}
.controls select:hover,
.controls button:hover,
.controls input:hover {
background: rgba(255, 255, 255, 0.3);
transform: translateY(-2px);
}
.controls button {
background: linear-gradient(45deg, #00d4aa, #00a8ff);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.controls button:hover {
background: linear-gradient(45deg, #00a8ff, #00d4aa);
box-shadow: 0 5px 15px rgba(0, 212, 170, 0.4);
}
.controls input::placeholder {
color: rgba(255, 255, 255, 0.7);
}
#chart-container {
width: 100%;
height: 600px;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
background: #1a1a1a;
position: relative;
}
.loading {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
font-size: 18px;
background: linear-gradient(45deg, #1a1a1a, #2d2d2d);
}
.loading::after {
content: "";
width: 30px;
height: 30px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-top: 3px solid #00d4aa;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-left: 15px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.status {
margin-top: 20px;
padding: 15px;
background: rgba(255, 255, 255, 0.1);
border-radius: 8px;
text-align: center;
backdrop-filter: blur(10px);
transition: all 0.3s ease;
}
.status.error {
background: rgba(244, 67, 54, 0.2);
border: 1px solid rgba(244, 67, 54, 0.5);
}
.status.success {
background: rgba(76, 175, 80, 0.2);
border: 1px solid rgba(76, 175, 80, 0.5);
}
.features {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-top: 30px;
}
.feature-card {
background: rgba(255, 255, 255, 0.1);
padding: 20px;
border-radius: 12px;
backdrop-filter: blur(10px);
transition: transform 0.3s ease;
}
.feature-card:hover {
transform: translateY(-5px);
}
.feature-card h3 {
color: #00d4aa;
margin-bottom: 10px;
}
@media (max-width: 768px) {
.controls {
flex-direction: column;
align-items: center;
}
.control-group {
width: 100%;
max-width: 200px;
}
#chart-container {
height: 400px;
}
.header h1 {
font-size: 2rem;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>π GoCharting SDK Demo</h1>
<p>Professional Financial Charting in Vanilla JavaScript</p>
</div>
<div class="controls">
<div class="control-group">
<label>Symbol</label>
<select id="symbol-selector">
<option value="NASDAQ:AAPL">Apple (AAPL)</option>
<option value="NASDAQ:MSFT">Microsoft (MSFT)</option>
<option value="NASDAQ:GOOGL">Google (GOOGL)</option>
<option value="NYSE:TSLA">Tesla (TSLA)</option>
<option value="BINANCE:BTCUSDT">Bitcoin (BTC)</option>
<option value="FOREX:EURUSD">EUR/USD</option>
</select>
</div>
<div class="control-group">
<label>Timeframe</label>
<select id="interval-selector">
<option value="1">1 Minute</option>
<option value="5">5 Minutes</option>
<option value="15">15 Minutes</option>
<option value="60">1 Hour</option>
<option value="1D" selected>1 Day</option>
<option value="1W">1 Week</option>
</select>
</div>
<div class="control-group">
<label>Chart Type</label>
<select id="chart-type-selector">
<option value="candlestick" selected>
Candlestick
</option>
<option value="line">Line</option>
<option value="area">Area</option>
<option value="bars">OHLC Bars</option>
</select>
</div>
<div class="control-group">
<label>Theme</label>
<select id="theme-selector">
<option value="dark" selected>Dark</option>
<option value="light">Light</option>
</select>
</div>
<div class="control-group">
<label>Custom Symbol</label>
<input
type="text"
id="custom-symbol"
placeholder="Enter symbol..."
/>
</div>
<div class="control-group">
<label> </label>
<button id="load-symbol-btn">Load Symbol</button>
</div>
<div class="control-group">
<label> </label>
<button id="refresh-btn">Refresh Data</button>
</div>
</div>
<div id="chart-container">
<div class="loading">Loading professional chart...</div>
</div>
<div id="status" class="status">Initializing GoCharting SDK...</div>
<div class="features">
<div class="feature-card">
<h3>π Professional Charts</h3>
<p>
Advanced candlestick, line, and area charts with
professional styling and smooth animations.
</p>
</div>
<div class="feature-card">
<h3>π Technical Indicators</h3>
<p>
50+ built-in technical indicators including RSI, MACD,
Bollinger Bands, and more.
</p>
</div>
<div class="feature-card">
<h3>π¨ Drawing Tools</h3>
<p>
Comprehensive drawing tools for technical analysis
including trendlines, Fibonacci, and shapes.
</p>
</div>
<div class="feature-card">
<h3>β‘ Real-time Data</h3>
<p>
Live market data updates with WebSocket support for
real-time price streaming.
</p>
</div>
</div>
</div>
<!-- GoCharting SDK -->
<script src="https://gocharting.com/sdk/library/demo-550e8400-e29b-41d4-a716-446655440000/index.umd.js"></script>
<script>
// Demo Data Provider for CodePen/CodeSandbox
class DemoDataProvider extends GoChartingSDK.DataProvider {
constructor() {
super();
this.cache = new Map();
}
async getBars(symbolInfo, resolution, periodParams) {
const { from, to } = periodParams;
console.log(`π Fetching bars for ${symbolInfo.name}`);
// Generate demo data
const bars = this.generateDemoData(
symbolInfo,
from,
to,
resolution,
);
return {
bars: bars,
meta: { noData: bars.length === 0 },
};
}
resolveSymbol(symbolName, onResolve, onError) {
console.log(`π Resolving symbol: ${symbolName}`);
try {
const [exchange, ticker] = symbolName.includes(":")
? symbolName.split(":")
: ["DEMO", symbolName];
const symbolInfo = {
name: symbolName,
full_name: symbolName,
description: this.getSymbolDescription(ticker),
type: this.getSymbolType(exchange),
session: "24x7",
timezone: "Etc/UTC",
ticker: ticker,
tick_size: 0.01, // Minimum price movement
has_intraday: true,
has_daily: true,
supported_resolutions: [
"1",
"5",
"15",
"30",
"60",
"240",
"1D",
"1W",
"1M",
],
};
setTimeout(() => onResolve(symbolInfo), 100);
} catch (error) {
onError("Symbol not found");
}
}
searchSymbols(userInput, callback) {
const symbols = [
{
symbol: "AAPL",
full_name: "NASDAQ:AAPL",
description: "Apple Inc.",
exchange: "NASDAQ",
type: "stock",
},
{
symbol: "MSFT",
full_name: "NASDAQ:MSFT",
description: "Microsoft Corporation",
exchange: "NASDAQ",
type: "stock",
},
{
symbol: "GOOGL",
full_name: "NASDAQ:GOOGL",
description: "Alphabet Inc.",
exchange: "NASDAQ",
type: "stock",
},
{
symbol: "TSLA",
full_name: "NYSE:TSLA",
description: "Tesla Inc.",
exchange: "NYSE",
type: "stock",
},
{
symbol: "BTCUSDT",
full_name: "BINANCE:BTCUSDT",
description: "Bitcoin / Tether",
exchange: "BINANCE",
type: "crypto",
},
];
const filtered = symbols.filter(
(s) =>
s.symbol
.toLowerCase()
.includes(userInput.toLowerCase()) ||
s.description
.toLowerCase()
.includes(userInput.toLowerCase()),
);
callback(filtered);
}
generateDemoData(symbolInfo, from, to, resolution) {
const bars = [];
const interval = this.getIntervalMs(resolution);
const startTime = from * 1000;
const endTime = to * 1000;
let currentTime = startTime;
let price = 100 + Math.random() * 200; // Random starting price
while (currentTime <= endTime && bars.length < 1000) {
const volatility = 0.02; // 2% volatility
const change =
(Math.random() - 0.5) * price * volatility;
const open = price;
const close = Math.max(0.01, price + change);
const high =
Math.max(open, close) * (1 + Math.random() * 0.01);
const low =
Math.min(open, close) * (1 - Math.random() * 0.01);
const volume =
Math.floor(Math.random() * 1000000) + 100000;
bars.push({
time: currentTime,
open: Math.round(open * 100) / 100,
high: Math.round(high * 100) / 100,
low: Math.round(Math.max(0.01, low) * 100) / 100,
close: Math.round(close * 100) / 100,
volume: volume,
});
price = close;
currentTime += interval;
}
return bars;
}
getIntervalMs(resolution) {
const intervals = {
1: 60 * 1000,
5: 5 * 60 * 1000,
15: 15 * 60 * 1000,
30: 30 * 60 * 1000,
60: 60 * 60 * 1000,
240: 4 * 60 * 60 * 1000,
"1D": 24 * 60 * 60 * 1000,
"1W": 7 * 24 * 60 * 60 * 1000,
"1M": 30 * 24 * 60 * 60 * 1000,
};
return intervals[resolution] || intervals["1D"];
}
getSymbolDescription(ticker) {
const descriptions = {
AAPL: "Apple Inc.",
MSFT: "Microsoft Corporation",
GOOGL: "Alphabet Inc.",
TSLA: "Tesla Inc.",
BTCUSDT: "Bitcoin / Tether",
EURUSD: "Euro / US Dollar",
};
return descriptions[ticker] || `${ticker} Demo`;
}
getSymbolType(exchange) {
const types = {
NASDAQ: "stock",
NYSE: "stock",
BINANCE: "crypto",
FOREX: "forex",
};
return types[exchange] || "stock";
}
}
// Main Application Class
class ChartDemo {
constructor() {
this.chart = null;
this.dataProvider = new DemoDataProvider();
this.currentSymbol = "NASDAQ:AAPL";
this.currentInterval = "1D";
this.currentTheme = "dark";
this.currentChartType = "candlestick";
this.init();
}
async init() {
try {
this.updateStatus("Initializing chart...", "info");
await this.createChart();
this.setupEventListeners();
this.updateStatus(
"Chart ready! Try changing symbols or timeframes.",
"success",
);
} catch (error) {
console.error("Failed to initialize:", error);
this.updateStatus(
"Failed to initialize chart. Please refresh the page.",
"error",
);
}
}
async createChart() {
const config = {
theme: { name: this.currentTheme },
chart: {
chartType: this.currentChartType,
animations: true,
grid: { horizontal: true, vertical: true },
},
ui: {
showToolbar: true,
showVolumePanel: true,
showDrawingTools: true,
},
performance: {
maxCandles: 2000,
animations: true,
},
};
this.chart = new GoChartingSDK.ProfessionalChart({
container: document.getElementById("chart-container"),
symbol: this.currentSymbol,
interval: this.currentInterval,
datafeed: this.dataProvider,
licenseKey: "demo-550e8400-e29b-41d4-a716-446655440000",
config: config,
});
this.setupChartEvents();
}
setupChartEvents() {
this.chart.onChartReady(() => {
console.log("β
Chart ready");
this.updateStatus(
`Chart loaded: ${this.currentSymbol}`,
"success",
);
});
this.chart.onSymbolChange((symbolInfo) => {
this.currentSymbol = symbolInfo.name;
this.updateSymbolSelector();
this.updateStatus(
`Symbol: ${symbolInfo.description}`,
"info",
);
});
this.chart.onIntervalChange((interval) => {
this.currentInterval = interval;
this.updateIntervalSelector();
this.updateStatus(`Timeframe: ${interval}`, "info");
});
this.chart.onError((error) => {
console.error("Chart error:", error);
this.updateStatus(`Error: ${error.message}`, "error");
});
}
setupEventListeners() {
// Symbol selector
document
.getElementById("symbol-selector")
.addEventListener("change", (e) => {
this.changeSymbol(e.target.value);
});
// Interval selector
document
.getElementById("interval-selector")
.addEventListener("change", (e) => {
this.changeInterval(e.target.value);
});
// Chart type selector
document
.getElementById("chart-type-selector")
.addEventListener("change", (e) => {
this.changeChartType(e.target.value);
});
// Theme selector
document
.getElementById("theme-selector")
.addEventListener("change", (e) => {
this.changeTheme(e.target.value);
});
// Custom symbol
document
.getElementById("load-symbol-btn")
.addEventListener("click", () => {
const customSymbol = document
.getElementById("custom-symbol")
.value.trim();
if (customSymbol) {
this.changeSymbol(customSymbol.toUpperCase());
}
});
// Refresh button
document
.getElementById("refresh-btn")
.addEventListener("click", () => {
this.refreshChart();
});
// Enter key for custom symbol
document
.getElementById("custom-symbol")
.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
document
.getElementById("load-symbol-btn")
.click();
}
});
}
async changeSymbol(symbol) {
if (this.chart && symbol !== this.currentSymbol) {
this.updateStatus(`Loading ${symbol}...`, "info");
try {
await this.chart.setSymbol(symbol);
} catch (error) {
this.updateStatus(
`Failed to load ${symbol}`,
"error",
);
}
}
}
async changeInterval(interval) {
if (this.chart && interval !== this.currentInterval) {
this.updateStatus(`Changing to ${interval}...`, "info");
try {
await this.chart.setInterval(interval);
} catch (error) {
this.updateStatus(
"Failed to change timeframe",
"error",
);
}
}
}
changeChartType(chartType) {
if (this.chart && chartType !== this.currentChartType) {
this.currentChartType = chartType;
this.chart.setChartType(chartType);
this.updateStatus(`Chart type: ${chartType}`, "info");
}
}
changeTheme(theme) {
if (this.chart && theme !== this.currentTheme) {
this.currentTheme = theme;
this.chart.setTheme(theme);
this.updateStatus(`Theme: ${theme}`, "info");
}
}
refreshChart() {
if (this.chart) {
this.updateStatus("Refreshing data...", "info");
this.dataProvider.cache.clear();
this.chart.refreshData();
}
}
updateStatus(message, type = "info") {
const statusElement = document.getElementById("status");
statusElement.textContent = message;
statusElement.className = `status ${type}`;
}
updateSymbolSelector() {
document.getElementById("symbol-selector").value =
this.currentSymbol;
}
updateIntervalSelector() {
document.getElementById("interval-selector").value =
this.currentInterval;
}
}
// Initialize when DOM is ready
document.addEventListener("DOMContentLoaded", () => {
console.log("π Starting GoCharting Demo...");
window.chartDemo = new ChartDemo();
});
</script>
</body>
</html>π― Key Features Demonstrated
Professional Chart Display
- Candlestick, line, area, and OHLC bar charts
- Smooth animations and professional styling
- Responsive design for mobile and desktop
Interactive Controls
- Symbol selection with popular stocks and crypto
- Timeframe switching (1m to 1W)
- Chart type switching
- Theme switching (dark/light)
- Custom symbol input
Demo Data Generation
- Realistic price movements with volatility
- Volume data simulation
- Multiple asset types (stocks, crypto, forex)
Error Handling
- Graceful error handling and user feedback
- Loading states and status updates
- Fallback for failed operations
π§ Customization Options
Modify Chart Configuration
const customConfig = {
theme: {
name: "dark",
colors: {
background: "#1a1a1a",
upColor: "#00d4aa",
downColor: "#ff6b6b",
},
},
chart: {
chartType: "candlestick",
animations: true,
maxCandles: 5000,
},
ui: {
showToolbar: true,
showVolumePanel: true,
showDrawingTools: true,
showLegend: true,
},
};Add Custom Indicators
// Add RSI indicator
chart.addIndicator("RSI", {
period: 14,
overbought: 70,
oversold: 30,
});
// Add Moving Average
chart.addIndicator("SMA", {
period: 20,
source: "close",
});π± Mobile Responsive
The example includes responsive design that works on:
- Desktop - Full feature set with all controls
- Tablet - Optimized layout with touch support
- Mobile - Compact layout with essential controls
π Integration with Your App
To integrate this into your application:
- Replace Demo Data Provider with your real data source
- Add Authentication for your API endpoints
- Customize Styling to match your brand
- Add Trading Features if needed (requires Professional license)
π Next Steps
- React + TypeScript Integration - React and TypeScript implementation
- Time Marks Example - Adding custom time marks
- CodePen Examples - Live interactive demos
Ready to use this in production? Get your license key at gocharting.comΒ !
Last updated on