차트 트레이딩

오픈소스 차트 엔진

차트 트레이딩

차트에서 바로 거래하는 모의 예제입니다. 롱 또는 숏 포지션을 선택하고 위험 금액을 입력하면 손절까지의 거리로 수량이 계산됩니다. Place order를 누르면 방향, 진입가, 목표가, 손절가, 수량이 담긴 의도가 페이지에 전달됩니다. 주문된 포지션은 가격선으로 표시되며, TP나 SL을 드래그하면 먼저 페이지에 묻고 거부되면 선이 원래 자리로 돌아갑니다. 엔진은 어떤 거래소에도 연결하지 않고 아무것도 전송하지 않습니다.

Apache-2.0

차트 트레이딩: 체결과 매매 복기 예제

createTradeTicket · createTradingLines · priceLineDrag · drawings.add('long_position')

코드
import { FerroChart } from '@ferrochart/core';
import { createTradeTicket, createTradingLines } from '@ferrochart/core/trading';

const canvas = document.querySelector('canvas');
// Market data: the synthetic FerroChart demo API. Use your own feed.
const chart = await FerroChart.create(canvas, { theme: 'dark' });
const bars = await fetch('/api/bars?symbol=BTCUSD&interval=15m&count=600').then((r) => r.json());
const candles = chart.addCandlestickSeries();
candles.setData(bars);
const n = bars.time.length, entry = bars.close[n - 1];
// Paper trading: the order "fills" in this page and goes nowhere else. A real
// page sends the intent to its own server here.
const ui = (tag, css, parent = canvas.parentElement) => {
  const e = document.createElement(tag);
  e.style.cssText = css;
  parent.append(e);
  return e;
};
const BTN = 'font:600 12px system-ui;color:#fff;border:0;border-radius:5px;padding:7px 14px;cursor:pointer;white-space:nowrap;pointer-events:auto';
const bar = ui('div', 'position:absolute;left:12px;top:10px;right:84px;display:flex;flex-wrap:wrap;gap:8px;align-items:center;z-index:2;pointer-events:none');
const buy = ui('button', BTN + ';background:#26a69a', bar);
const sell = ui('button', BTN + ';background:#ef5350', bar);
buy.textContent = 'Buy / Long';
sell.textContent = 'Sell / Short';
const note = ui('span', 'font:500 12px system-ui;color:#8b93a7;margin-left:4px', bar);
const say = (text) => { note.textContent = `Paper trading · ${text}`; };

// The panel of the filled position, with a Close button.
const panel = ui('div', 'margin-left:auto;display:none;gap:10px;align-items:center;white-space:nowrap;' +
  'padding:4px 5px 4px 12px;border-radius:8px;background:rgba(30,34,45,.96);border:1px solid #363a45;' +
  'font:12px system-ui;color:#d1d4dc;font-variant-numeric:tabular-nums', bar);
const info = ui('span', '', panel);
const close = ui('button', BTN + ';background:#363a45;padding:5px 10px', panel);
close.textContent = 'Close position';

// Wide: controls over the chart, with room below the bars for the ticket.
// Narrow (phones): the chart leaves a strip above it for the buttons and one
// below it, where the ticket docks and the position panel goes.
const host = canvas.parentElement, css = canvas.style.cssText;
let narrow = null;
function layout() {
  const now = host.clientWidth < 480;
  if (now === narrow) return;
  narrow = now;
  canvas.style.cssText = css + (now ? ';margin-top:76px;height:calc(100% - 172px)' : '');
  const first = n - (now ? 30 : 110);
  chart.setVisibleLogicalRange(first, n + (now ? 34 : 40));
  // The bars in view and a 2% target on either side.
  chart.applyPriceScaleOptions({
    margins: now ? { top: 0.14, bottom: 0.14 } : { top: 0.12, bottom: 0.32 },
    range: {
      low: Math.min(entry * 0.98, ...bars.low.slice(first)),
      high: Math.max(entry * 1.02, ...bars.high.slice(first)),
    },
  });
  bar.style.right = now ? '12px' : '84px';
  note.style.flexBasis = now ? '100%' : 'auto';
  (now ? host : bar).append(panel);
  Object.assign(panel.style, now
    ? { position: 'absolute', left: '12px', right: '12px', bottom: '24px', justifyContent: 'space-between' }
    : { position: 'static', justifyContent: 'flex-start' });
}
layout();
const resized = new ResizeObserver(layout);
resized.observe(host);

// The lines of what was placed; drag TP or SL to change it.
let position = null;
const lines = createTradingLines(chart, candles, {
  priceStep: 0.5,
  async onModify({ kind, price }) {
    await new Promise((r) => setTimeout(r, 300)); // the server's answer
    if (!position) return false; // closed meanwhile
    const above = price > position.entry;
    if ((kind === 'takeProfit') !== (above === (position.side === 'buy'))) throw new Error('refused: wrong side of the entry');
    position[kind === 'takeProfit' ? 'target' : 'stop'] = price;
    say(`${kind === 'takeProfit' ? 'Take profit' : 'Stop'} moved to ${price}.`);
  },
  onError: (e) => say(`Change ${e.message}; the line went back.`),
});

// Buy and Sell open a position at the market price, 2% target and 1% stop;
// drag its handles to adjust. Users can also draw one with
// chart.drawings.startTool('long_position' or 'short_position').
const until = bars.time[n - 1] + 25 * 15 * 60_000;
function open(long) {
  for (const id of chart.drawings.ids()) if (chart.drawings.get(id)?.kind.endsWith('_position')) chart.drawings.remove(id);
  const k = long ? 1 : -1;
  chart.drawings.select(chart.drawings.add({ kind: long ? 'long_position' : 'short_position', anchors: [
    { time: bars.time[n - 1], price: entry },
    { time: until, price: entry * (1 + 0.02 * k) },
    { time: until, price: entry * (1 - 0.01 * k) },
  ] }));
  say('Adjust the target and stop, then Place order.');
}
buy.onclick = () => open(true);
sell.onclick = () => open(false);
// One position at a time: Buy and Sell wait until it is closed.
const holding = (on) => {
  for (const b of [buy, sell]) { b.disabled = on; b.style.opacity = on ? '0.4' : '1'; b.style.cursor = on ? 'default' : 'pointer'; }
  panel.style.display = on ? 'flex' : 'none';
};
close.onclick = () => {
  for (const id of lines.ids()) lines.remove(id);
  position = null;
  holding(false);
  say('Position closed. Buy or Sell to open another.');
};
open(true);

// The ticket beside the selected position: quantity from the amount at risk.
const ticket = createTradeTicket(chart, candles, {
  canvas, risk: 500, currency: '$', priceStep: 0.5, quantityStep: 0.001,
  async onPlaceOrder(intent) {
    buy.disabled = sell.disabled = true; // until the answer
    await new Promise((r) => setTimeout(r, 400));
    position = intent;
    const { entry, target, stop, quantity, side } = intent;
    lines.set({ id: 'position', kind: 'position', price: entry, quantity, title: `${side === 'buy' ? 'Long' : 'Short'} ${quantity}` });
    lines.set({ id: 'tp', kind: 'takeProfit', price: target, quantity });
    lines.set({ id: 'sl', kind: 'stopLoss', price: stop, quantity });
    chart.drawings.remove(intent.drawing);
    info.innerHTML = `<b style="color:${side === 'buy' ? '#26a69a' : '#ef5350'}">${side === 'buy' ? 'LONG' : 'SHORT'}</b> ${quantity} @ ${entry}`;
    holding(true);
    say('Filled. Drag TP or SL on the chart.');
  },
});

// The page calls this before it destroys the chart.
const stop = () => { resized.disconnect(); ticket.destroy(); lines.destroy(); bar.remove(); panel.remove(); canvas.style.cssText = css; };

틱 단위 데이터를 위해 만들었습니다.

Apple M4 Max · Chrome + WebGPU

브라우저에서 100만 봉을 로드하고 첫 프레임을 그리기까지

WASM · WebGPU

네이티브로 1,000만 봉 로드(LOD 피라미드 포함)

네이티브 Rust

이동, 확대·축소, 스트리밍 중 프레임당 힙 할당

정상 상태

WebAssembly 패키지 크기(gzip)

전체 기능 포함

브라우저 수치는 Google Chrome + WebGPU, 1,000만 봉 로드는 네이티브 Rust 기준입니다. 막대는 각 수치를 목표 대비 비율로 보여 줍니다(로드 300ms, 할당 없음, 패키지 1.5MB).

예제

320개의 예제,
20개의 활용 사례.

모든 예제는 FerroChart가 브라우저에서 실시간으로 그리는 차트이며 소스 코드가 함께 제공됩니다. 모든 데이터는 합성 데이터입니다.

봉 리플레이
실시간 스트림
캔들스틱 + 거래량
01

가격 차트

예제 28개 →

모든 시장의 캔들, 봉, 라인 차트를 실시간 스트리밍으로 보여 줍니다.

호가 히트맵
델타 풋프린트
풋프린트
04

오더플로우

예제 20개 →

풋프린트, 호가 히트맵, 마켓 프로파일을 컴퓨트 셰이더 경로로 처리합니다.

내재 변동성 · 베이시스
롱/숏 비율 · CVD
펀딩비 · 미결제약정 · 청산
06

암호화폐 파생상품

예제 15개 →

펀딩비, 미결제약정, 청산, 베이시스를 가격 아래 패널에 표시합니다.

리스크 리버설 · 버터플라이
만기까지 예상 변동폭
내재 대 실현 변동성 · IV 랭크
12

옵션과 변동성

예제 18개 →

내재 변동성 대 실현 변동성, 스큐, 예상 변동폭, 딜러 익스포저를 시간에 따라 보여 줍니다.

동시 낙폭
언더워터 곡선 · 최대 낙폭
자산 곡선 · 낙폭
16

포트폴리오, 리스크, 퀀트

예제 24개 →

자산 곡선, 낙폭, 롤링 통계, 팩터 연구, 리스크 점검.

그룹 컬럼
누적 컬럼
100% 누적 영역
19

커스텀 시리즈와 플러그인

예제 11개 →

누적, 그룹, 박스, 브러시 시리즈: 같은 GPU 프레임 위에 레이어 플러그인을 얹습니다.

활용 사례 20개 모두 보기

가격 차트

봉 유형과 변환

기술적 분석

오더플로우

체결과 매매 복기

암호화폐 파생상품

온체인

DeFi와 AMM

밈코인과 지갑

주식과 펀더멘털

중국 A주

옵션과 변동성

금리, 외환, 매크로

선물과 원자재

펀드와 ETF

포트폴리오, 리스크, 퀀트

사모 시장과 개인 재무

예측 시장

커스텀 시리즈와 플러그인

실험실과 대표 예제

기능

시장 데이터를 위해 설계했습니다.

01

크로스 플랫폼 렌더링

하나의 Rust 코어로 브라우저에서는 WebGPU와 WebGL2, 네이티브 앱에서는 wgpu로 Metal, Vulkan, DirectX 12, 서버에서는 CPU 렌더러를 사용합니다. 골든 이미지 테스트로 백엔드 간 출력을 일치시킵니다.

02

데이터 크기와 무관한 성능

봉 데이터는 GPU에 머물고 좌표 변환은 셰이더에서 처리하므로 이동과 확대·축소 시 몇 개의 uniform만 갱신합니다. LOD 피라미드 덕분에 수천만 봉도 부드럽게 다룹니다.

03

30개 내장 지표

SMA부터 일목균형표까지 이동평균, 채널, 오실레이터. 틱마다 증분 방식으로 갱신되며 참조 데이터로 검증합니다.

04

29개 드로잉 도구

추세선, 채널, 피보나치 도구, 피치포크, 갠 팬, 패턴, 엘리어트 파동, 범위, 포지션, 텍스트를 실행 취소·다시 실행과 함께 제공합니다. 드로잉과 차트 상태는 JSON으로 직렬화됩니다.

05

차트 동기화

동기화 그룹으로 여러 차트의 크로스헤어와 표시 범위를 연동합니다.

06

확장성

사용자 정의 시리즈, 레이어, 드로잉 도구를 위한 플러그인 인터페이스. JavaScript, Rust, Python 바인딩과 C#, C++, Qt, Flutter용 C ABI를 제공합니다.

시작하기

모든 언어에서 하나의 API.

모든 바인딩은 같은 모델을 따릅니다. 차트를 만들고, 시리즈를 추가하고, 데이터를 설정하고, 지표를 추가합니다. 데이터는 타입 배열, Rust 슬라이스, DataFrame에서 열 단위로 전달합니다.

  • JavaScript · TypeScript
  • Rust
  • Python · Jupyter
  • C, C#, C++
문서 읽기
main.js
$ npm install @ferrochart/core
import { FerroChart } from '@ferrochart/core';

const chart = await FerroChart.create(canvas, { theme: 'dark' });
const candles = chart.addCandlestickSeries();
chart.addVolumeSeries(candles);
candles.setData(bars); // [{ time, open, high, low, close, volume }, ...]
chart.addIndicator(candles, 'ema', { n: 20 });
chart.addIndicator(candles, 'macd'); // in a new pane

FerroChart

모든 시장.
모든 화면.
하나의 엔진.

Apache-2.0 오픈소스. 브라우저부터 트레이딩 데스크까지.