移动止损与清算价

开源图表引擎

移动止损与清算价

10 倍杠杆的多头仓位(基于回放 K 线的模拟)。止损起初在入场价下方 4%,盈利达到 1.5% 后改为跟随最高价、保持在其下方 3%;逐仓保证金的清算价是一条橙色实线。价格触及止损时平仓,显示成交标记和盈亏,随后重新开仓。引擎不发送任何数据。

Apache-2.0

移动止损与清算价:执行与交易复盘示例

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 万根 K 线并画出首帧

WASM · WebGPU

原生载入 1000 万根 K 线,含多级细节金字塔

原生 Rust

平移、缩放和实时推送时每帧的堆分配次数

稳定状态

WebAssembly 包体积(gzip)

包含全部功能

浏览器数据:Google Chrome + WebGPU;1000 万根 K 线的载入为原生 Rust。进度条表示各项数据相对于目标的比例:载入 300 毫秒、零分配、安装包 1.5 MB。

示例

320 个示例,
覆盖 20 个应用场景。

每个示例都是 FerroChart 在你的浏览器中实时渲染的图表,并附带源代码。所有数据均为模拟数据。

K 线回放
实时数据流
K 线 + 成交量
01

价格走势

28 个示例 →

适用于任何市场的 K 线、美国线和折线,实时流式更新。

深度热力图
Delta 足迹图
足迹图
04

订单流

20 个示例 →

足迹图、深度热力图和市场轮廓,走计算着色器路径。

隐含波动率 · 基差
多空比 · CVD
资金费率 · 持仓量 · 清算
06

加密衍生品

15 个示例 →

资金费率、持仓量、清算和基差,显示在价格下方的窗格中。

风险逆转 · 蝶式
到期预期波动幅度
隐含与已实现波动率 · IV Rank
12

期权与波动率

18 个示例 →

隐含波动率与已实现波动率、偏斜、预期波动幅度和做市商敞口随时间的变化。

联合回撤
水下曲线 · 最大回撤
净值曲线 · 回撤
16

组合、风险与量化

24 个示例 →

净值曲线、回撤、滚动统计、因子研究和风险检查。

分组柱状图
堆叠柱状图
100% 堆叠面积图
19

自定义系列与插件

11 个示例 →

堆叠、分组、箱线和刷选系列:在同一 GPU 帧上叠加图层插件。

浏览全部 20 个应用场景

价格走势

K 线类型与变换

技术分析

订单流

执行与交易复盘

加密衍生品

链上数据

DeFi 与 AMM

Meme 币与钱包

股票与基本面

A 股

期权与波动率

利率、外汇与宏观

期货与大宗商品

基金与 ETF

组合、风险与量化

私募市场与个人理财

预测市场

自定义系列与插件

实验室与旗舰示例

特性

为行情数据而设计。

01

跨平台渲染

同一个 Rust 内核:浏览器中使用 WebGPU 和 WebGL2 后端,原生应用中通过 wgpu 运行在 Metal、Vulkan 和 DirectX 12 上,服务器上使用 CPU 渲染器。黄金图像测试保证各后端输出一致。

02

性能与数据量无关

K 线数据常驻 GPU,坐标变换在着色器中完成,平移和缩放只需更新少量 uniform。多级细节金字塔让数千万根 K 线依然流畅。

03

30 个内置指标

从 SMA 到一目均衡表的均线、通道和震荡指标。每个 tick 增量更新,并用参考数据测试。

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 开源,从浏览器到交易台。