VibeFox JS Trading — 데모
빠른 시작
일반 HTML
1분 봉을 5분 캔들로 표시합니다. 도구 모음, 그리기 도구 모음, EMA 및 RSI 패널이 있으며, 로컬 타이머가 0.5초마다 실시간 틱을 보냅니다. 마우스 휠로 확대/축소하고, 드래그로 이동하며, 타임프레임이나 그리기 도구를 선택할 수 있습니다.
document.getElementById('app').style.height = '480px';
// bars: { time (ms of the bar start), open, high, low, close, volume }
const bars = VibeFoxJSTrading.generateBars({ count: 1000, interval: 60000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '5m',
toolbar: true,
drawingToolbar: true,
});
chart.addIndicator('ema', { period: 21 });
chart.addIndicator('rsi');
// a live tick extends the last bar or opens a new one
let price = bars[bars.length - 1].close;
setInterval(() => {
price += (Math.random() - 0.5) * 0.15;
chart.addTick({ price, volume: 10 });
}, 500);핵심 개념
봉
코드에 적힌 일간 봉 60개({ time, open, high, low, close, volume })를 일 단위로 표시하고, 주 단위로 리샘플링합니다. 버튼으로 타임프레임을 전환합니다.
const bars = [];
let close = 50;
for (let i = 0; i < 60; i++) {
const open = close;
close = +(open + Math.sin(i / 5) * 1.5 + ((i % 3) - 1) * 0.4).toFixed(2);
bars.push({
time: Date.UTC(2026, 0, 1) + i * 86400000,
open, close,
high: +(Math.max(open, close) + 0.6).toFixed(2),
low: +(Math.min(open, close) - 0.6).toFixed(2),
volume: 1000 + ((i * 37) % 500),
});
}
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'MY BARS', timeframe: '1D' });
const buttons = document.createElement('p');
for (const [label, run] of [
['Days', () => chart.setTimeframe('1D')],
['Weeks', () => chart.setTimeframe('1W')],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);이벤트
차트 위의 줄은 crosshairMove와 visibleRangeChange 이벤트로 채워집니다. 캔들 위로 마우스를 이동한 다음 차트를 확대/축소하거나 이동하면 됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
const out = document.createElement('p');
out.textContent = 'Move the mouse over the chart';
document.getElementById('app').before(out);
const day = (t) => new Date(t).toISOString().slice(0, 16).replace('T', ' ');
chart.on('crosshairMove', (e) => {
if (e.bar) out.textContent = day(e.time) + ' close ' + e.bar.close.toFixed(2) + ' cursor ' + (e.price == null ? '-' : e.price.toFixed(2));
});
chart.on('visibleRangeChange', (e) => {
out.textContent = 'Visible: ' + day(e.timeFrom) + ' to ' + day(e.timeTo);
});데이터와 실시간
실시간 업데이트
로컬 타이머가 실시간 피드를 대신합니다. addTick()이 200 ms마다 호출되고 틱마다 시장 시간 5초가 지나므로, 12틱마다 새 1분 봉이 열리며 barClose가 이를 집계합니다.
const bars = VibeFoxJSTrading.generateBars({ count: 120, interval: 60000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'LIVE', timeframe: '1m' });
chart.addIndicator('sma', { period: 10 });
const out = document.createElement('p');
document.getElementById('app').before(out);
let price = bars[bars.length - 1].close;
let time = bars[bars.length - 1].time + 60000;
let closed = 0;
chart.on('barClose', () => { closed++; });
setInterval(() => {
price += (Math.random() - 0.48) * 0.12;
time += 5000;
chart.addTick({ price, volume: 5 + Math.random() * 20, time });
out.textContent = 'Last ' + price.toFixed(2) + ', bars closed: ' + closed;
}, 200);마커
봉 위치에 매수와 매도 마커가 캔들 위 또는 아래에 표시되며, 각각 텍스트와 고유한 색을 가집니다. 마커를 클릭하면 그 텍스트가 차트 위에 표시됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 120, to: bars.length });
chart.setMarkers([
{ time: bars[bars.length - 95].time, shape: 'arrowUp', position: 'below', text: 'Buy' },
{ time: bars[bars.length - 60].time, shape: 'arrowDown', position: 'above', text: 'Sell', color: '#dc2626' },
{ time: bars[bars.length - 40].time, shape: 'circle', position: 'below', text: 'News', color: '#7c3aed' },
{ time: bars[bars.length - 12].time, shape: 'arrowUp', position: 'below', text: 'Buy' },
]);
const out = document.createElement('p');
out.textContent = 'Click a marker';
document.getElementById('app').before(out);
chart.on('markerClick', (e) => { out.textContent = 'Clicked: ' + e.marker.text; });리플레이
리플레이는 끝에서 150봉 앞에서 시작해 이력을 봉 단위로 재생합니다. 일시 정지한 뒤 5봉씩 진행하거나, 재개하거나, 중지할 수 있습니다(중지하면 모든 봉이 다시 표시됩니다).
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'REPLAY', timeframe: '1h' });
chart.addIndicator('ema', { period: 20 });
chart.startReplay({ at: bars.length - 150, intervalMs: 300, autoplay: true });
const buttons = document.createElement('p');
for (const [label, run] of [
['Pause', () => chart.pauseReplay()],
['Resume', () => chart.resumeReplay()],
['Step 5', () => chart.stepReplay(5)],
['Restart', () => chart.startReplay({ at: bars.length - 150, intervalMs: 300, autoplay: true })],
['Stop', () => chart.stopReplay()],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);시리즈 및 차트 유형
시리즈 유형
목록에서 14가지 시리즈 유형(SERIES_TYPES) 중 하나를 선택할 수 있습니다: 캔들스틱, OHLC, 선, 영역, 기준선, 히스토그램, 하이킨 아시, 속이 빈 캔들과 거래량 캔들, 그리고 빌드된 차트 유형.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 150, to: bars.length });
const picker = document.createElement('select');
for (const name of VibeFoxJSTrading.SERIES_TYPES) picker.add(new Option(name));
picker.onchange = () => chart.setSeriesType(picker.value);
document.getElementById('app').before(picker);빌드된 차트 유형
시간 봉으로 만든 0.5 크기의 Renko 벽돌과 꼬리(윅)를 표시합니다(x축은 벽돌의 순서입니다). Kagi, Point & Figure, 라인 브레이크 또는 레인지 봉을 선택할 수 있으며, 위의 줄에는 getChartTypeInfo()의 결과가 표시됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
seriesType: 'renko',
chartTypes: { renko: { boxSize: 0.5, source: 'close', wicks: true } },
});
const info = document.createElement('p');
const show = () => {
const i = chart.getChartTypeInfo();
info.textContent = i.type + ': size ' + (i.size == null ? (i.percent == null ? '-' : i.percent + ' %') : i.size.toFixed(2)) + ', parameters ' + JSON.stringify(i.params);
};
const picker = document.createElement('select');
for (const name of VibeFoxJSTrading.BUILT_TYPES) picker.add(new Option(name));
picker.onchange = () => { chart.setSeriesType(picker.value); show(); };
document.getElementById('app').before(picker);
picker.after(info);
show();지표
지표 추가
가격 패널에는 50기간 SMA와 볼린저 밴드가 표시되고, MACD는 별도의 패널에 표시되며 패널 범례에 값이, 가격 축에 배지가 나타납니다. 패널 사이의 경계를 드래그해 크기를 조절할 수 있습니다.
document.getElementById('app').style.height = '460px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.addIndicator('sma', { period: 50 });
chart.addIndicator('bollinger', { period: 20, mult: 2 });
chart.addIndicator('macd');
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });기본 제공 지표
목록에서 기본 제공 지표 50개 중 하나를 선택할 수 있으며, 이전 지표는 제거됩니다. 오버레이는 가격 패널에, 오실레이터는 각자의 패널에 표시됩니다.
document.getElementById('app').style.height = '440px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });
let current = chart.addIndicator('ichimoku');
const names = Object.values(VibeFoxJSTrading.INDICATOR_GROUPS).flat();
const picker = document.createElement('select');
for (const name of names) picker.add(new Option(name));
picker.onchange = () => { chart.removeIndicator(current); current = chart.addIndicator(picker.value); };
document.getElementById('app').before(picker);
picker.value = 'ichimoku';직접 만든 지표
등록된 지표 "Mid line": (high + low) / 2의 30봉 SMA이며, 기본 제공 지표처럼 가격 패널에 보라색으로 그려집니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
VibeFoxJSTrading.registerIndicator({
name: 'midline',
label: 'Mid line',
pane: 'overlay', // 'overlay' | 'separate' | 'volume'
params: { period: 10 },
compute(bars, p) {
const mid = bars.map((b) => (b.high + b.low) / 2);
return { plots: [{ key: 'mid', values: VibeFoxJSTrading.sma(mid, p.period), color: '#9333ea', width: 2 }] };
},
});
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.addIndicator('midline', { period: 30 });
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });그리기 도구
도구
그룹별 48개 도구가 모두 들어 있는 그리기 도구 모음이 표시되며, 추세선 도구는 이미 활성화되어 있습니다. 차트에서 두 점을 클릭한 다음, 도구 모음에서 피보나치, 피치포크 또는 포지션 도구를 선택해 그릴 수 있습니다.
document.getElementById('app').style.height = '460px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h', drawingToolbar: true });
chart.setVisibleRange({ from: bars.length - 150, to: bars.length });
chart.setTool('trendline');코드로 그리기
addDrawing()으로 추가된 점선의 잠긴 추세선(오른쪽으로 연장됨), 레이블이 있는 피보나치 되돌림, 평행 채널과 텍스트가 표시됩니다. 확대/축소하거나 타임프레임을 바꿔 보십시오. 앵커는 시간과 가격입니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 160, to: bars.length });
const a = bars[bars.length - 140], b = bars[bars.length - 30];
const lo = Math.min(...bars.slice(-140).map((x) => x.low));
const hi = Math.max(...bars.slice(-140).map((x) => x.high));
const id = chart.addDrawing({ tool: 'trendline', points: [{ time: a.time, price: a.low }, { time: b.time, price: b.low }],
color: '#2563eb', lineWidth: 2, extendRight: true });
chart.updateDrawing(id, { lineStyle: 'dashed', locked: true });
chart.addDrawing({ tool: 'fib', points: [{ time: a.time, price: lo }, { time: b.time, price: hi }], showLabels: true });
chart.addDrawing({ tool: 'text', points: [{ time: b.time, price: hi }], text: 'Range high', fontSize: 14, bold: true });편집, 선택, 실행 취소
속성 패널이 열려 있는 상태에서 선택된 사각형이 표시됩니다(showDrawingProperties()). 색상이나 선을 변경하고, 그리기 또는 그 핸들을 드래그한 다음 Ctrl+Z를 눌러 실행 취소하십시오.
document.getElementById('app').style.height = '440px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 120, to: bars.length });
const a = bars[bars.length - 90], b = bars[bars.length - 40];
chart.addDrawing({ tool: 'hline', points: [{ time: a.time, price: a.close }] });
const id = chart.addDrawing({ tool: 'rect', points: [{ time: a.time, price: a.high }, { time: b.time, price: b.low }],
fill: true, fillOpacity: 0.15 });
chart.selectDrawing(id);
chart.showDrawingProperties(id);데이터피드
로드 및 오류
처음 로드가 실패하는 데이터피드입니다. 재시도 후 차트에 "Failed to load data"가 표시됩니다(이벤트 dataError). Reload를 클릭하면 reloadData()가 호출됩니다.
const memory = new VibeFoxJSTrading.MemoryDatafeed({ symbols: ['DEMO'], latency: 100 });
memory.failNext(2, 'Server is down');
const chart = VibeFoxJSTrading.createTradingChart('#app', {
datafeed: memory,
symbol: 'DEMO',
timeframe: '5m',
datafeedOptions: { retries: 1, retryDelay: 300 },
});
const out = document.createElement('p');
document.getElementById('app').before(out);
chart.on('dataError', (e) => { out.textContent = 'dataError, attempt ' + e.attempt + (e.final ? ' (final)' : ''); });
chart.on('dataLoad', (e) => { out.textContent = 'dataLoad: ' + e.count + ' bars'; });
const buttons = document.createElement('p');
for (const [label, run] of [
['Reload', () => chart.reloadData()],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);MemoryDatafeed
메모리 내 데이터피드로, 무작위 심볼 3개와 0.5초마다 오는 실시간 틱을 제공합니다. 도구 모음에서 다른 심볼이나 타임프레임을 선택하고, 왼쪽으로 스크롤하면 이전 이력을 로드합니다.
const memory = new VibeFoxJSTrading.MemoryDatafeed({
symbols: {
BTCUSD: { startPrice: 60000, description: 'Bitcoin', type: 'crypto' },
ETHUSD: { startPrice: 3000, description: 'Ether', type: 'crypto' },
DEMO: { startPrice: 100 },
},
latency: [20, 80],
});
const chart = VibeFoxJSTrading.createTradingChart('#app', {
datafeed: memory,
symbol: 'BTCUSD',
timeframe: '5m',
toolbar: { items: ['symbol', 'timeframes', 'seriesType'], symbols: ['BTCUSD', 'ETHUSD', 'DEMO'] },
});
chart.whenLoaded().then(() => memory.start(500)); // live ticks심볼 비교
기본 캔들 위에 다른 두 심볼이 선으로 표시되며, 축은 백분율로 전환되어 모든 시리즈가 첫 번째 보이는 봉에서 0%로 시작합니다. 차트를 이동하면 시작점도 보기와 함께 이동합니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'MAIN', timeframe: '1h' });
chart.addCompare('ETH', { data: VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000, startPrice: 50, seed: 2 }), color: '#f59e0b' });
chart.addCompare('SPX', { data: VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000, startPrice: 4000, seed: 3 }), color: '#0891b2' });
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });축, 탐색 및 내비게이터
축과 보이는 범위
로그 가격 축, 세션 구분선, 그리고 setVisibleRange()로 설정된 마지막 200봉이 표시됩니다. 가격 축을 위아래로 드래그하면 가격이 확대/축소되며, 차트를 더블클릭하면 두 축이 모두 초기화됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 2000, interval: 3600000, startPrice: 20, volatility: 0.006 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
priceScale: { mode: 'log' },
timeScale: { sessionBreaks: true, rightOffset: 10 },
});
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });
const picker = document.createElement('select');
for (const name of ['log', 'linear', 'percent']) picker.add(new Option(name));
picker.onchange = () => chart.setPriceScaleMode(picker.value);
document.getElementById('app').before(picker);내비게이터와 기간 버튼
차트 아래의 내비게이터는 전체 이력을 보여 주며 보이는 범위를 창으로 표시합니다. 기간 버튼은 최근 1개월을 보여 줍니다. 창을 드래그하거나 크기를 조정하거나, 5D, 3M 또는 All을 클릭합니다.
document.getElementById('app').style.height = '460px';
const bars = VibeFoxJSTrading.generateBars({ count: 4000, interval: 3600000, volatility: 0.001 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h', navigator: true, periods: true });
chart.setPeriod('1M');볼륨 프로파일
보이는 범위의 가격 레벨별 거래량과 최대 거래 가격(POC)을 표시합니다. 확대/축소하거나 이동하면 새 범위에 대해 프로파일이 다시 계산됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
volumeProfile: { visible: true, bins: 24 },
});
chart.setVisibleRange({ from: bars.length - 200, to: bars.length });시간대와 세션
뉴욕 일정에 따라 4일 분량의 5분 봉이 표시됩니다. 프리마켓/애프터마켓 시간은 음영으로 표시되고, 점선은 세션 시작을 나타내며, VWAP은 매 거래일마다 다시 시작하고 시간은 거래소 시간대로 표시됩니다. 목록에서 다른 시간대를 선택할 수 있습니다.
const bars = VibeFoxJSTrading.generateBars({ count: 1200, interval: 300000, startPrice: 180 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'NYSE DEMO',
timeframe: '15m',
sessions: { preset: 'nyse', extended: true, highlight: true },
timezone: 'exchange',
timeScale: { sessionBreaks: true },
});
chart.addIndicator('vwap');
const picker = document.createElement('select');
for (const name of ['exchange', 'UTC', 'Europe/London', 'Asia/Tokyo']) picker.add(new Option(name));
picker.onchange = () => chart.setTimezone(picker.value);
document.getElementById('app').before(picker);알림
가격 알림 선 2개와 가격이 SMA를 교차할 때의 알림이 있으며, 가격을 등락시키는 로컬 타이머의 실시간 틱으로 검사됩니다. 발생한 알림은 모두 차트 위 목록에 추가됩니다. 알림 선을 다른 가격으로 드래그하십시오.
const bars = VibeFoxJSTrading.generateBars({ count: 200, interval: 60000, startPrice: 1.08 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'EURUSD', timeframe: '1m' });
const last = bars[bars.length - 1].close;
const sma = chart.addIndicator('sma', { period: 20 });
chart.addAlert(+(last + 0.004).toFixed(5), { label: 'Resistance' });
chart.addAlert(+(last - 0.004).toFixed(5), { label: 'Support', color: '#dc2626' });
chart.addAlert({ source: 'price', condition: 'crossing', target: { indicator: sma }, frequency: 'oncePerBar',
message: '{symbol}: price crossed SMA at {price}' });
const out = document.createElement('p');
out.textContent = 'Waiting for an alert...';
document.getElementById('app').before(out);
const fired = [];
chart.on('alertTrigger', (e) => {
fired.unshift(new Date().toLocaleTimeString() + ' ' + e.message);
out.textContent = fired.slice(0, 2).join(' | ');
});
// a local stand-in for live data: the price swings around the last close
let k = 0, time = bars[bars.length - 1].time + 60000;
setInterval(() => {
k++;
time += 6000;
const price = last + 0.006 * Math.sin(k / 6) + (Math.random() - 0.5) * 0.001;
chart.addTick({ price: +price.toFixed(5), volume: 5, time });
}, 200);터미널 UI
기본 제공 도구 모음(symbol, timeframes, series type, indicators, comparison, alerts, undo / redo, settings, snapshot, fullscreen)과 그리기 도구 모음입니다. Indicators를 열면 지표를 검색해 추가할 수 있고, Settings를 열면 색상과 축을 변경할 수 있습니다.
document.getElementById('app').style.height = '480px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'BTCUSD',
timeframe: '1h',
toolbar: {
items: ['symbol', 'timeframes', 'seriesType', '|', 'indicators', 'compare', 'alerts', '|', 'undo', 'redo', '-', 'settings', 'snapshot', 'fullscreen'],
favorites: ['15m', '1h', '4h', '1D'],
symbols: ['BTCUSD', 'ETHUSD'],
},
drawingToolbar: true,
});
chart.addIndicator('ema', { period: 50 });관심 종목 목록과 심볼 검색
두 그룹으로 나뉜 관심 종목 목록에 마지막 가격, 변동, 스파크라인이 표시되며, 메모리 내 데이터피드에서 실시간으로 값을 받습니다. 행을 클릭하면 차트가 전환되고, 도구 모음의 심볼을 클릭하면 검색할 수 있습니다.
document.getElementById('app').style.height = '460px';
const memory = new VibeFoxJSTrading.MemoryDatafeed({
symbols: {
BTCUSD: { startPrice: 60000, description: 'Bitcoin', type: 'crypto' },
ETHUSD: { startPrice: 3000, description: 'Ether', type: 'crypto' },
AAPL: { startPrice: 230, description: 'Apple', type: 'stock' },
MSFT: { startPrice: 420, description: 'Microsoft', type: 'stock' },
},
});
const chart = VibeFoxJSTrading.createTradingChart('#app', {
datafeed: memory,
symbol: 'BTCUSD',
timeframe: '15m',
toolbar: { items: ['symbol', 'timeframes', '-', 'watchlist'] },
symbolSearch: true,
watchlist: {
groups: [{ title: 'Crypto', symbols: ['BTCUSD', 'ETHUSD'] }, { title: 'Stocks', symbols: ['AAPL', 'MSFT'] }],
columns: ['last', 'changePct', 'spark'],
},
});
chart.whenLoaded().then(() => memory.start(700));여러 차트와 동기화
메모리 내 데이터피드 하나를 사용하는 차트 4개 레이아웃입니다. BTCUSD와 ETHUSD의 타임프레임 3개가 표시되며, 십자선은 시간을 기준으로 동기화됩니다. 차트 위로 마우스를 옮기고, 차트를 클릭하면 활성 차트가 됩니다.
document.getElementById('app').style.height = '560px';
const layout = VibeFoxJSTrading.createTradingLayout('#app', {
layout: '4',
datafeed: new VibeFoxJSTrading.MemoryDatafeed({ symbols: ['BTCUSD', 'ETHUSD'] }),
chart: { symbol: 'BTCUSD' },
charts: [{ timeframe: '1m' }, { timeframe: '5m' }, { timeframe: '1h' }, { symbol: 'ETHUSD', timeframe: '5m' }],
sync: { crosshair: true, drawings: true },
});
layout.getChart(2).addIndicator('rsi');차트에서 거래
차트 위
손절가와 목표가가 설정된 롱 포지션, 매수 지정가 주문과 매도 스톱 주문, 그리고 호가창이 표시됩니다. 브로커는 코드 안의 작은 객체입니다. 주문 선을 새 가격으로 드래그하거나, 호가창에서 가격을 클릭해 주문을 넣을 수 있습니다.
document.getElementById('app').style.height = '460px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const last = bars[bars.length - 1].close;
const p = (pct) => +(last * (1 + pct / 100)).toFixed(2);
let n = 0;
const broker = { // stands in for your server: accepts every request
placeOrder: (order) => ({ id: 'o' + ++n, status: order.type === 'market' ? 'filled' : 'working' }),
modifyOrder: (id, changes) => changes,
cancelOrder: () => ({ status: 'cancelled' }),
closePosition: () => ({ quantity: 0 }),
modifyPosition: (id, changes) => changes,
};
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
trade: { broker, quantity: 10, tickSize: 0.01, currency: 'USD', dom: true },
});
chart.setVisibleRange({ from: bars.length - 100, to: bars.length });
chart.setPositions([{ id: 'p1', side: 'long', quantity: 10, avgPrice: p(-0.6), sl: p(-1.1), tp: p(1.2) }]);
chart.setOrders([
{ id: 'o1', side: 'buy', type: 'limit', price: p(-0.85), quantity: 5 },
{ id: 'o2', side: 'sell', type: 'stop', stopPrice: p(0.8), quantity: 5 },
]);
const book = { bids: [], asks: [] };
for (let i = 1; i <= 10; i++) {
book.bids.push([+(last - i * 0.01).toFixed(2), 50 + i * 30]);
book.asks.push([+(last + i * 0.01).toFixed(2), 40 + i * 35]);
}
chart.setDepth(book);MockBroker
메모리 내 MockBroker는 차트의 실시간 가격으로 시장가 매수 주문을 체결하고, 틱마다 포지션 손익(P&L)을 최신 상태로 유지합니다. Buy / Sell을 사용하거나, 주문 티켓을 열려면 Trade 버튼을 사용하십시오.
document.getElementById('app').style.height = '460px';
const bars = VibeFoxJSTrading.generateBars({ count: 300, interval: 60000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1m',
toolbar: { items: ['symbol', 'timeframes', '-', 'trade', 'dom'] },
});
const mock = new VibeFoxJSTrading.MockBroker({ latency: 50, symbol: 'DEMO' }).attach(chart);
chart.setOptions({ trade: { broker: mock, quantity: 2, tickSize: 0.01 } });
let price = bars[bars.length - 1].close, time = bars[bars.length - 1].time + 60000;
setInterval(() => {
price += (Math.random() - 0.5) * 0.1;
time += 5000;
chart.addTick({ price, volume: 5, time });
}, 250);
setTimeout(() => chart.placeOrder({ side: 'buy', type: 'market', quantity: 2 }), 300);
const buttons = document.createElement('p');
for (const [label, run] of [
['Buy 2', () => chart.placeOrder({ side: 'buy', type: 'market', quantity: 2 })],
['Sell 2', () => chart.placeOrder({ side: 'sell', type: 'market', quantity: 2 })],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);백테스트와 전략
전략
차트의 봉에 대해 실행되는 이동평균 교차 전략입니다. 라벨이 있는 거래 마커와 자산 곡선 및 낙폭 패널이 표시됩니다. 보고서는 버튼(summary, trades, monthly results)으로 엽니다.
document.getElementById('app').style.height = '560px';
const bars = VibeFoxJSTrading.generateBars({ count: 1500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
const smaCross = {
name: 'SMA cross',
params: { fast: 10, slow: 30 },
indicators: (p) => ({ fast: ['sma', { period: p.fast }], slow: ['sma', { period: p.slow }] }),
onBar(ctx) {
if (ctx.crossover('fast', 'slow')) ctx.buy({ percent: 50, slOffset: 2 });
else if (ctx.crossunder('fast', 'slow')) ctx.sell({ percent: 50 });
},
};
chart.addIndicator('sma', { period: 10 });
chart.addIndicator('sma', { period: 30 });
chart.setStrategy(smaCross, { capital: 10000, commission: 0.05, markers: true, equity: true, drawdown: true });
chart.setVisibleRange({ from: bars.length - 250, to: bars.length });
const buttons = document.createElement('p');
for (const [label, run] of [
['Report: summary', () => chart.showBacktestReport('summary')],
['Report: trades', () => chart.showBacktestReport('trades')],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);내보내기
Snapshot을 클릭하면 getImage()가 차트 이미지를 만듭니다. 이미지에는 제목 띠와 OHLCV 범례가 포함되며 차트 아래에 표시됩니다(exportPNG()는 같은 이미지를 다운로드합니다).
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'BTC / USD', timeframe: '1h' });
chart.addIndicator('ema', { period: 20 });
chart.setVisibleRange({ from: bars.length - 120, to: bars.length });
const shot = document.createElement('p');
document.getElementById('app').after(shot);
const snap = () => {
const canvas = chart.getImage({ title: 'BTC / USD', subtitle: true, legend: true });
canvas.style.width = '50%';
canvas.style.border = '1px solid #ccc';
shot.replaceChildren(canvas);
};
const buttons = document.createElement('p');
for (const [label, run] of [
['Snapshot', snap],
]) {
const b = document.createElement('button');
b.textContent = label;
b.onclick = run;
buttons.append(b, ' ');
}
document.getElementById('app').before(buttons);
snap();렌더링과 대용량 데이터
1분 봉 100,000개를 한 번에 모두 화면에 표시합니다. 위의 줄에는 사용 중인 렌더러가 표시됩니다(보이는 봉이 5,000개 이상이면 GPU의 WebGL, 그 외에는 canvas 2D). 마우스 휠을 아래로 굴려 확대하면 개별 캔들까지 표시됩니다.
const bars = VibeFoxJSTrading.generateBars({ count: 100000, interval: 60000, volatility: 0.001 });
const t0 = performance.now();
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: '100K', timeframe: '1m' });
chart.fitContent();
const out = document.createElement('p');
document.getElementById('app').before(out);
const info = () => {
const r = chart.getRenderInfo();
out.textContent = bars.length + ' bars, created in ' + Math.round(performance.now() - t0) + ' ms, renderer: ' + r.renderer + ' (' + r.reason + ')';
};
info();
chart.on('rendererChange', info);테마 및 스타일
테마
차트 위 목록에서 테마를 선택할 수 있습니다: light, dark, high-contrast 및 vibefox-js-themes.css의 테마 팩(paper, ocean, sunset, graphite-dark).
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h', toolbar: true });
chart.addIndicator('bollinger');
const picker = document.createElement('select');
for (const name of ['light', 'dark', 'high-contrast', 'paper', 'ocean', 'sunset', 'graphite-dark']) picker.add(new Option(name));
picker.onchange = () => chart.setTheme(picker.value);
document.getElementById('app').before(picker);CSS 변수
파란색과 주황색 캔들, 격자선 없음, 사용자 지정 십자선을 이 차트 요소의 --vfjs-trading-* CSS 변수로 설정합니다. 변수가 바뀌면 캔버스가 다시 그려집니다.
const app = document.getElementById('app');
app.style.setProperty('--vfjs-trading-candle-up', '#0a7cff');
app.style.setProperty('--vfjs-trading-wick-up', '#0a7cff');
app.style.setProperty('--vfjs-trading-candle-down', '#ff7a00');
app.style.setProperty('--vfjs-trading-wick-down', '#ff7a00');
app.style.setProperty('--vfjs-trading-grid', 'transparent');
app.style.setProperty('--vfjs-trading-crosshair', '#9333ea');
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 120, to: bars.length });기본 제공 스타일
목록에서 기본 제공 스타일 중 하나를 선택할 수 있습니다: classic, terminal(항상 다크), monochrome, light(항상 라이트), 또는 기본 외관을 사용하려면 none.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h', style: 'terminal', toolbar: true });
chart.addIndicator('ema', { period: 20 });
chart.setVisibleRange({ from: bars.length - 120, to: bars.length });
const picker = document.createElement('select');
for (const name of ['none', ...VibeFoxJSTrading.TRADING_STYLES]) picker.add(new Option(name));
picker.onchange = () => chart.setStyle(picker.value === 'none' ? null : picker.value);
document.getElementById('app').before(picker);
picker.value = 'terminal';밀도와 크기
같은 차트를 --vfjs-size-unit: 1.3px로 표시하면 도구 모음, 축 텍스트, 선 두께, 마커가 더 커집니다. 목록에서 compact 밀도를 선택해 보십시오.
const app = document.getElementById('app');
app.style.setProperty('--vfjs-size-unit', '1.3px');
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h', toolbar: true });
chart.setVisibleRange({ from: bars.length - 80, to: bars.length });
const picker = document.createElement('select');
for (const name of ['size unit 1.3px', 'normal', 'compact', 'comfortable']) picker.add(new Option(name));
picker.onchange = () => {
app.style.setProperty('--vfjs-size-unit', picker.selectedIndex ? '1px' : '1.3px');
app.dataset.vfjsDensity = picker.selectedIndex ? picker.value : 'normal';
};
document.getElementById('app').before(picker);현지화 및 RTL
언어
러시아어로 표시한 차트입니다. 라이브러리 뒤에 언어 팩 vibefox-js-trading.ru.js를 로드하고 locale: 'ru'를 설정합니다. 도구 모음, 범례, 시간 축의 월 이름과 지표 이름이 번역됩니다.
document.getElementById('app').style.height = '440px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
locale: 'ru',
toolbar: true,
drawingToolbar: true,
});
chart.addIndicator('rsi');
chart.setVisibleRange({ from: bars.length - 150, to: bars.length });오른쪽에서 왼쪽 방향(RTL)
옵션 rtl: true를 설정하면 그리기 도구 모음이 오른쪽에 놓이고 도구 모음도 오른쪽부터 배치됩니다. 차트 자체는 미러링되지 않습니다(시간은 왼쪽에서 오른쪽으로 흐르고, 가격 축은 오른쪽에 유지됩니다).
document.getElementById('app').style.height = '480px';
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', {
data: bars,
symbol: 'DEMO',
timeframe: '1h',
rtl: true,
toolbar: true,
drawingToolbar: true,
});접근성
키보드
봉에 키보드 봉 커서가 놓입니다(focusBar()). 위의 줄에는 스크린 리더가 읽는 내용이 표시됩니다. 차트를 클릭한 다음 화살표 키, Home, End 또는 ↑ / ↓를 눌러 확대/축소하십시오.
const bars = VibeFoxJSTrading.generateBars({ count: 500, interval: 3600000 });
const chart = VibeFoxJSTrading.createTradingChart('#app', { data: bars, symbol: 'DEMO', timeframe: '1h' });
chart.setVisibleRange({ from: bars.length - 80, to: bars.length });
const out = document.createElement('p');
document.getElementById('app').before(out);
const read = () => {
const i = chart.getFocusedBar();
out.textContent = i == null ? chart.getSummary().text : chart.describeBar(i);
};
chart.focusBar(bars.length - 20);
read();
document.getElementById('app').addEventListener('keyup', read);