オープンソースのチャートエンジン
トレーリングストップと清算価格
10 倍レバレッジのロングポジション(再生した足でのシミュレーション)。ストップは最初エントリーの 4% 下にあり、含み益が 1.5% に達すると最高値の 3% 下を追従します。分離マージンの清算価格はオレンジの実線です。価格がストップに達するとポジションを決済し、約定マーカーと損益を表示してから再びエントリーします。エンジンは何も送信しません。
トレーリングストップと清算価格:執行とトレードレビューのサンプル
trailingStop · liquidationPrice · createTradingLines · tradeMarkers
コード
import { FerroChart } from '@ferrochart/core';
import { createTradingLines, trailingStop, liquidationPrice, tradeMarkers } 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=1h&count=400').then((r) => r.json());
// Bar replay with setData and update: all but the last 40 bars, then each
// step() moves the forming bar a little; it closes on its 4th tick. At the end
// of the data the replay starts over (restart() resets the example).
const n = bars.time.length, START = n - 40, TICKS = 4;
const head = (k) => Object.fromEntries(Object.entries(bars).map(([key, v]) => [key, v.slice(0, k)]));
const candles = chart.addCandlestickSeries();
candles.setData(head(START));
let next = START, tick = 0, forming = null;
function step() {
if (next === n) { next = START; candles.setData(head(START)); restart(); }
const i = next, t = ++tick, closed = t === TICKS, o = bars.open[i];
const noise = (Math.random() - 0.5) * (bars.high[i] - bars.low[i]) * 0.5;
const price = closed ? bars.close[i] : Math.round((o + (bars.close[i] - o) * t / TICKS + noise) * 10) / 10;
if (t === 1) forming = { time: bars.time[i], open: o, high: o, low: o };
forming = { ...forming, high: Math.max(forming.high, price), low: Math.min(forming.low, price), close: price, volume: bars.volume[i] * t / TICKS };
candles.update(forming);
if (closed) { next++; tick = 0; }
return { time: bars.time[i], price, closed };
}
const FROM = START - (canvas.clientWidth < 480 ? 30 : 80);
chart.setVisibleLogicalRange(FROM, n + 3);
// Paper trading: a simulated long of 0.5 BTC at 10x that opens and closes in
// this page; nothing is sent anywhere. A real page modifies its stop order on
// the exchange each time the trailing stop moves.
const QTY = 0.5;
const ui = (tag, css, parent = canvas.parentElement) => parent.appendChild(Object.assign(document.createElement(tag), { style: css }));
const note = ui('div', 'position:absolute;left:12px;top:10px;right:84px;font:500 12px system-ui;color:#c9d1e0;z-index:2;pointer-events:none');
const lines = createTradingLines(chart, candles);
const fills = [];
let trail = null, entry = 0, liq = null, wait = 0;
const show = () => candles.setMarkers(tradeMarkers(fills, { times: bars.time }));
function open(time, price) {
entry = price;
// 4% below the entry, then 3% below the best price once it is 1.5% up.
trail = trailingStop({ side: 'buy', percent: 3, activation: price * 1.015, stop: Math.floor(price * 0.96), priceStep: 1 });
liq = liquidationPrice({ side: 'buy', entry: price, quantity: QTY, margin: (price * QTY) / 10, maintenanceRate: 0.005 });
fills.push({ time, price, quantity: QTY, side: 'buy' });
lines.set({ id: 'entry', kind: 'position', price, quantity: QTY });
lines.set({ id: 'sl', kind: 'stopLoss', price: trail.stop, title: 'Stop' });
lines.set({ id: 'liq', kind: 'liquidation', price: liq, title: '10x liquidation' });
note.textContent = `Paper long ${QTY} BTC at ${price.toFixed(1)}, 10x. The stop trails 3% after a 1.5% gain.`;
show();
}
function exit(time, price) {
fills.push({ time, price, quantity: QTY, side: 'sell' });
const pnl = (price - entry) * QTY, margin = (entry * QTY) / 10;
note.textContent = `Stopped out at ${price.toFixed(1)}: P&L ${pnl < 0 ? '−' : '+'}$${Math.abs(pnl).toFixed(0)} (${(pnl / margin * 100).toFixed(1)}% of the margin). Reopening…`;
for (const id of lines.ids()) lines.remove(id);
trail = liq = null;
wait = 8; // ticks until the next entry
show();
}
function onPrice({ time, price }) {
if (!trail) {
if (--wait <= 0) open(time, price);
return;
}
if (price <= trail.stop) return exit(time, price);
const moved = trail.update(price);
if (moved !== null) lines.set({ id: 'sl', kind: 'stopLoss', price: moved, title: `Trailing stop ${moved}` });
}
// The scale keeps the liquidation price (about 9.5% below the entry) in view.
function fit() {
const low = Math.min(liq ?? Infinity, ...bars.low.slice(FROM, next + 1)), high = Math.max(...bars.high.slice(FROM, next + 1));
chart.applyPriceScaleOptions({ range: { low: low * 0.995, high: high * 1.005 } });
}
// The first position opened 60 bars ago: the same logic over those closes.
for (let i = START - 60; i < START; i++) onPrice({ time: bars.time[i], price: bars.close[i] });
fit();
function restart() { fills.length = 0; for (const id of lines.ids()) lines.remove(id); trail = liq = null; wait = 0; show(); }
const timer = setInterval(() => { onPrice(step()); fit(); }, 600);
// The page calls this before it destroys the chart.
const stop = () => { clearInterval(timer); lines.destroy(); note.remove(); };ティック単位のデータのために。
Apple M4 Max · Chrome + WebGPUブラウザで 100 万本の足を読み込み、最初のフレームを描画
WASM · WebGPU
ネイティブで 1,000 万本の足を読み込み(LOD ピラミッド構築を含む)
ネイティブ Rust
パン、ズーム、ストリーミング中のフレームあたりのヒープアロケーション
定常状態
WebAssembly パッケージのサイズ(gzip)
全機能込み
ブラウザの数値は Google Chrome + WebGPU、1,000 万本の読み込みはネイティブ Rust での計測です。バーは各数値の目標に対する割合を示します(読み込み 300 ms、アロケーションなし、パッケージ 1.5 MB)。
サンプル
320 のサンプル、
20 のユースケース。
どのサンプルも FerroChart がブラウザ上でリアルタイムに描画するチャートで、ソースコード付きです。データはすべて合成データです。



プライスアクション
28 件のサンプル →あらゆる市場のローソク足、バー、ラインをリアルタイムでストリーミング表示します。



オーダーフロー
20 件のサンプル →フットプリント、板のヒートマップ、マーケットプロファイルをコンピュートシェーダーで描画します。



暗号資産デリバティブ
15 件のサンプル →資金調達率、建玉、清算、ベーシスを価格の下のペインに表示します。



オプションとボラティリティ
18 件のサンプル →インプライド対実現ボラティリティ、スキュー、予想変動幅、ディーラーのエクスポージャーを時系列で表示します。



ポートフォリオ・リスク・クオンツ
24 件のサンプル →資産曲線、ドローダウン、ローリング統計、ファクターリサーチ、リスクチェックを扱います。



カスタムシリーズとプラグイン
11 件のサンプル →積み上げ、グループ、箱ひげ、ブラシ選択のシリーズを、同じGPUフレーム上のレイヤープラグインで描画します。
20 のユースケースをすべて見る
プライスアクション
足の種類と変換
テクニカル分析
オーダーフロー
執行とトレードレビュー
暗号資産デリバティブ
オンチェーン
DeFiとAMM
ミームコインとウォレット
株式とファンダメンタルズ
中国A株
オプションとボラティリティ
金利・為替・マクロ
先物とコモディティ
ファンドとETF
ポートフォリオ・リスク・クオンツ
プライベート市場と個人の資産管理
予測市場
カスタムシリーズとプラグイン
ラボとフラッグシップ
ローソク足と出来高
1 / 28The classic view. A day of real one-minute bars, updating every second, on a GPU-rendered price scale with a volume histogram below. Drag to pan, scroll or pinch to zoom.
FerroChart.createaddCandlestickSeriesaddVolumeSeriesドラッグでパン · ホイールまたはピンチでズーム · ダブルクリックでリセットリアルタイムデータ · OKXcandles
特長
市場データのための設計。
クロスプラットフォームの描画
ひとつの Rust コアで、ブラウザでは WebGPU と WebGL2、ネイティブアプリでは wgpu により Metal、Vulkan、DirectX 12、サーバーでは CPU レンダラーを使います。ゴールデンイメージテストで各バックエンドの出力を揃えています。
データ量に左右されない性能
足のデータは GPU 上に置かれ、座標変換はシェーダーで行うため、パンやズームでは少数の uniform を更新するだけです。LOD ピラミッドにより数千万本の足でも軽快に動きます。
30 の組み込みインジケーター
SMA から一目均衡表まで、移動平均、チャネル、オシレーター。値はティックごとにインクリメンタルに更新され、参照データでテストされています。
29 の描画ツール
トレンドライン、チャネル、フィボナッチ、ピッチフォーク、ギャンファン、パターン、エリオット波動、レンジ、ポジション、テキスト。元に戻す・やり直しに対応し、描画とチャートの状態は JSON に保存できます。
チャートの同期
同期グループで、複数のチャートのクロスヘアと表示範囲を連動させます。
拡張性
カスタムシリーズ、レイヤー、描画ツールのためのプラグインインターフェース。JavaScript、Rust、Python のバインディングと、C#、C++、Qt、Flutter 向けの C ABI を提供します。
はじめる
どの言語でも、同じ API。
どのバインディングも同じモデルです。チャートを作成し、シリーズを追加し、データを設定し、インジケーターを追加します。データは型付き配列、Rust のスライス、DataFrame から列として渡します。
- JavaScript・TypeScript
- Rust
- Python・Jupyter
- C、C#、C++
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