VibeFox JS Trading — Demo
Início rápido
HTML puro
Barras de um minuto exibidas como velas de 5 minutos, com a barra de ferramentas, a barra de ferramentas de desenho, um painel de EMA e um painel de RSI; um temporizador local envia um tick em tempo real a cada meio segundo. Role a roda do mouse para dar zoom, arraste para deslocar o gráfico, escolha um timeframe ou uma ferramenta de desenho.
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);Conceitos principais
Barras
Sessenta barras diárias escritas no código ({ time, open, high, low, close, volume }), exibidas como dias e reamostradas em semanas. Troque o timeframe com os botões.
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);Eventos
A linha acima do gráfico é preenchida pelos eventos crosshairMove e visibleRangeChange. Mova o mouse sobre as velas e depois dê zoom ou desloque o gráfico.
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);
});Dados e tempo real
Atualizações em tempo real
Um temporizador local substitui um feed em tempo real: addTick() a cada 200 ms, cinco segundos de tempo de mercado por tick, de modo que uma nova barra de um minuto abre a cada 12 ticks e barClose a contabiliza.
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);Marcadores
Marcadores de compra e de venda nas barras, acima ou abaixo das velas, com texto e cor próprios. Um clique em um marcador exibe seu texto acima do gráfico.
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; });Replay
O replay começa 150 barras antes do fim e reproduz o histórico barra a barra. Pause-o, avance cinco barras, retome ou pare (todas as barras voltam).
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);Tipos de série e de gráfico
Tipos de série
Escolha qualquer um dos 14 tipos de série na lista (SERIES_TYPES): candlestick, OHLC, linha, área, baseline, histograma, Heikin Ashi, velas vazadas e de volume, e os tipos construídos.
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);Tipos de gráfico construídos
Tijolos Renko de 0,5 com pavios, construídos a partir das barras de tempo (o eixo x é a sequência de tijolos). Escolha Kagi, Point & Figure, Line Break ou Range Bars; a linha acima exibe 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();Indicadores
Adição de indicadores
Uma SMA de 50 períodos e as Bandas de Bollinger no painel de preços, MACD em painel próprio com os valores na legenda do painel e rótulos no eixo de preços. Arraste a borda entre os painéis para redimensioná-los.
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 });Indicadores integrados
Escolha qualquer um dos 50 indicadores integrados na lista; o anterior é removido. Os indicadores sobrepostos vão para o painel de preços, os osciladores para um painel próprio.
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';Seus próprios indicadores
Um indicador registrado "Mid line": a SMA de 30 barras de (high + low) / 2, desenhada em roxo no painel de preços, como os integrados.
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 });Ferramentas de desenho
Ferramentas
A barra de ferramentas de desenho com todas as 48 ferramentas por grupo; a ferramenta de linha de tendência já está ativa. Clique em dois pontos do gráfico e depois escolha uma ferramenta de Fibonacci, pitchfork ou de posição na barra de ferramentas e desenhe-a.
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');Desenhos a partir do código
Uma linha de tendência tracejada e bloqueada, estendida para a direita, uma retração de Fibonacci com rótulos, um canal paralelo e um texto, adicionados com addDrawing(). Aplique zoom ou troque o timeframe: as âncoras são o tempo e o preço.
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 });Edição, seleção e desfazer
Um retângulo selecionado com o painel de propriedades aberto (showDrawingProperties()). Mude a cor ou a linha, arraste o desenho ou suas alças e depois pressione Ctrl+Z para desfazer.
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);Datafeed
Carregamento e erros
Um datafeed cujas primeiras cargas falham: após a nova tentativa, o gráfico exibe "Failed to load data" (evento dataError). Clique em Reload para chamar 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
O datafeed em memória com três símbolos aleatórios e ticks em tempo real a cada meio segundo. Escolha outro símbolo ou timeframe na barra de ferramentas; role para a esquerda para carregar o histórico mais antigo.
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 ticksComparação de símbolos
Dois outros símbolos como linhas sobre as velas principais; a escala foi alterada para percentual, de modo que cada série começa em 0% na primeira barra visível. Desloque o gráfico: o início acompanha a visualização.
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 });Escalas, navegação e navegador
Escalas e intervalo visível
Uma escala de preço logarítmica, linhas de quebra de sessão e as últimas 200 barras definidas com setVisibleRange(). Arraste a escala de preço para cima ou para baixo para dar zoom no preço; dê um duplo clique no gráfico para redefinir as duas escalas.
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);Navegador e botões de período
O navegador sob o gráfico mostra todo o histórico com o intervalo visível como uma janela; os botões de período mostram o último mês. Arraste ou redimensione a janela, ou clique em 5D, 3M ou 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');Perfil de volume
O volume por níveis de preço do intervalo visível com o point of control. Aplique zoom ou desloque: o perfil é calculado novamente para o novo intervalo.
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 });Fusos horários e sessões
Quatro dias de barras de cinco minutos com o horário de Nova York: os horários pré e pós-mercado ficam sombreados, linhas tracejadas marcam o início das sessões, o VWAP reinicia a cada dia de negociação e os horários estão no fuso da bolsa. Escolha outro fuso horário na lista.
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);Alertas
Duas linhas de alerta de preço e um alerta para quando o preço cruzar a SMA, verificado nos ticks em tempo real de um temporizador local que faz o preço oscilar; cada alerta disparado é adicionado à lista acima do gráfico. Arraste uma linha de alerta para outro preço.
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);Interface de terminal
A barra de ferramentas pronta (símbolo, timeframes, tipo de série, indicadores, comparação, alertas, desfazer / refazer, configurações, snapshot, tela cheia) e a barra de ferramentas de desenho. Abra Indicators para pesquisar e adicionar um, ou Settings para alterar cores e escalas.
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 });Lista de observação e busca de símbolos
Uma lista de observação em dois grupos, com o último preço, a variação e um sparkline, alimentada em tempo real por um datafeed em memória. Clique em uma linha para trocar o gráfico ou clique no símbolo na barra de ferramentas para pesquisar.
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));Vários gráficos e sincronização
Um layout de quatro gráficos com um único datafeed em memória: três timeframes de BTCUSD e ETHUSD, com o crosshair sincronizado pelo tempo. Mova o mouse sobre um gráfico; clique em um gráfico para torná-lo ativo.
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');Negociação a partir do gráfico
No gráfico
Uma posição comprada com stop loss e take profit, uma ordem limitada de compra e uma ordem stop de venda, e a escada de profundidade de mercado; a corretora é um pequeno objeto no código. Arraste uma linha de ordem para um novo preço ou clique em um preço na escada para colocar uma ordem.
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
O MockBroker em memória executa uma compra a mercado pelo preço em tempo real do gráfico e mantém o P&L da posição atualizado a cada tick. Use Buy / Sell ou o botão Trade para o ticket de ordem.
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);Backtests e estratégias
Uma estratégia
Uma estratégia de cruzamento de médias móveis executada nas barras do gráfico: marcadores de negociação com rótulos, além dos painéis de equity e de drawdown. Abra o relatório pelos botões: 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);Exportação
Clique em Snapshot: getImage() gera a imagem do gráfico com a faixa de título e a legenda OHLCV, exibida sob o gráfico (exportPNG() baixa a mesma imagem).
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();Renderização e grandes volumes de dados
100.000 barras de um minuto, todas na tela ao mesmo tempo; a linha acima informa o renderizador em uso (WebGL em uma GPU a partir de 5.000 barras visíveis, caso contrário canvas 2D). Aplique zoom com a roda do mouse para baixo até as velas individuais.
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);Temas e estilização
Temas
Escolha um tema na lista acima do gráfico: light, dark, high-contrast e os temas do pacote de 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);Variáveis CSS
Velas azuis e laranja, sem linhas de grade e com um crosshair personalizado, definidos como variáveis CSS --vfjs-trading-* deste elemento do gráfico; o canvas é redesenhado quando uma variável muda.
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 });Estilos prontos
Escolha um dos estilos prontos na lista: classic, terminal (sempre escuro), monochrome, light (sempre claro) ou none para a aparência padrão.
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';Densidade e tamanho
O mesmo gráfico com --vfjs-size-unit: 1.3px: a barra de ferramentas, os textos dos eixos, as larguras das linhas e os marcadores ficam maiores. Experimente a densidade compacta na lista.
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);Localização e RTL
Idiomas
O gráfico em russo: carregue o pacote de idioma vibefox-js-trading.ru.js depois da biblioteca e defina locale: 'ru'. A barra de ferramentas, a legenda, os nomes dos meses do eixo de tempo e os nomes dos indicadores são traduzidos.
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 });Da direita para a esquerda
A opção rtl: true: a barra de ferramentas de desenho fica à direita e a barra de ferramentas segue da direita, enquanto o próprio gráfico não é espelhado (o tempo vai da esquerda para a direita, a escala de preço continua à direita).
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,
});Acessibilidade
Teclado
O cursor de barra controlado pelo teclado sobre uma barra (focusBar()); a linha acima mostra o que um leitor de tela anuncia. Clique no gráfico e pressione as setas, Home, End ou ↑ / ↓ para dar zoom.
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);