Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/binance-orderbook-trade-development.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ scripts/

The optional depth profile is a userscript-owned canvas beside the TradingView price axis. It does not clone Binance's native Depth React component. A feature-gated adapter reads the active TradingView main pane height and maps each depth price through the pane's current price scale, including logarithmic and inverted modes. The divider uses Binance's latest visible trade price rather than the order-book midpoint so it follows TradingView's live-price line. If that contract is unavailable or invalid, the profile fails closed instead of falling back to an approximate scale. Binance Basic and native Depth modes do not expose the verified coordinate contract, so the profile is hidden in those modes.

The userscript installs `core/binance-native-depth-source.js` at `document-start` and passively observes the native `/fapi/v1/rpiDepth?limit=1000` response and `{symbol}@rpiDepth@500ms` messages. It preserves Binance's original `fetch` result and WebSocket instances and never opens a second depth connection. `core/depth-profile-book.js` applies the observed `lastUpdateId`, `U`, `u`, and `pu` sequence contract and treats quantities as absolute values; zero removes a price level. `core/depth-profile-session.js` only subscribes the active symbol to that page-owned source. A sequence gap waits for Binance's native resynchronization instead of issuing a userscript-owned retry request, while a changed private RPI contract fails the profile explicitly without blocking Binance's own request.
The userscript installs `core/binance-native-depth-source.js` at `document-start` and passively observes the native `/fapi/v1/rpiDepth?limit=1000` response and `{symbol}@rpiDepth@500ms` messages. It preserves Binance's original `fetch` result and WebSocket instances and never opens a second depth connection. `core/depth-profile-book.js` applies the observed `lastUpdateId`, `U`, `u`, and `pu` sequence contract and treats quantities as absolute values; zero removes a price level. The profile keeps every active price accumulated from the native stream and defers pixel-row aggregation to rendering, so distant levels are not discarded by the snapshot limit. Rendering remains sparse: a row is painted only when at least one real price level maps to that chart pixel. `core/depth-profile-session.js` only subscribes the active symbol to that page-owned source. A sequence gap waits for Binance's native resynchronization instead of issuing a userscript-owned retry request, while a changed private RPI contract fails the profile explicitly without blocking Binance's own request.

The session must stop and invalidate old work on symbol change, non-trading routes, hidden documents, and `pagehide`. The overlay canvas uses `pointer-events: none`; only its compact collapse control may receive pointer input. Do not connect this visualization book to ladder pricing or any trading decision.

Expand Down
18 changes: 6 additions & 12 deletions scripts/binance-orderbook-trade.user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// @namespace binance.orderbook.trade
// @icon data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23f0b90b%22%2F%3E%3Ctext%20x%3D%2232%22%20y%3D%2249%22%20text-anchor%3D%22middle%22%20font-family%3D%22Arial%2C%20sans-serif%22%20font-size%3D%2242%22%20font-weight%3D%22800%22%20fill%3D%22%23111827%22%3EJ%3C%2Ftext%3E%3C%2Fsvg%3E
// @icon64 data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23f0b90b%22%2F%3E%3Ctext%20x%3D%2232%22%20y%3D%2249%22%20text-anchor%3D%22middle%22%20font-family%3D%22Arial%2C%20sans-serif%22%20font-size%3D%2242%22%20font-weight%3D%22800%22%20fill%3D%22%23111827%22%3EJ%3C%2Ftext%3E%3C%2Fsvg%3E
// @version 2.7.185
// @version 2.7.186
// @author jackhai9
// @description 单击订单簿价格,按当前开仓/平仓 tab 自动填数量并执行下单,内置数量倍率面板
// @match https://www.binance.com/*/futures/*
Expand Down Expand Up @@ -3408,7 +3408,6 @@
}
};
var MAX_BUFFERED_UPDATES = 500;
var DEPTH_PROFILE_LEVELS_PER_SIDE = 1e3;
function assertSymbol(value) {
if (typeof value !== "string" || !/^[A-Z0-9_]+$/.test(value)) {
throw new Error("Invalid depth profile symbol");
Expand Down Expand Up @@ -3553,11 +3552,11 @@
book.ready = false;
return applyBufferedUpdates(book);
}
function toSortedLevels(levels, direction, limit) {
function toSortedLevels(levels, direction) {
return [...levels.entries()].map(([price, quantity]) => ({
price: Number(price),
quantity: Number(quantity)
})).filter((level) => Number.isFinite(level.price) && Number.isFinite(level.quantity)).sort((left, right) => direction * (left.price - right.price)).slice(0, limit);
})).filter((level) => Number.isFinite(level.price) && Number.isFinite(level.quantity)).sort((left, right) => direction * (left.price - right.price));
}
function addCumulativeQuantity(levels) {
let cumulative = 0;
Expand All @@ -3566,15 +3565,10 @@
return { ...level, cumulative };
});
}
function buildDepthProfile(book, {
levelsPerSide = DEPTH_PROFILE_LEVELS_PER_SIDE
} = {}) {
function buildDepthProfile(book) {
if (!book.ready) throw new Error("Depth profile book is not ready");
if (!Number.isInteger(levelsPerSide) || levelsPerSide <= 0) {
throw new Error("Invalid depth profile level count");
}
const bids = addCumulativeQuantity(toSortedLevels(book.bids, -1, levelsPerSide));
const asks = addCumulativeQuantity(toSortedLevels(book.asks, 1, levelsPerSide));
const bids = addCumulativeQuantity(toSortedLevels(book.bids, -1));
const asks = addCumulativeQuantity(toSortedLevels(book.asks, 1));
if (!bids.length || !asks.length) throw new Error("Depth profile requires bids and asks");
const midPrice = (bids[0].price + asks[0].price) / 2;
const furthestDistance = Math.max(
Expand Down
17 changes: 5 additions & 12 deletions src/binance-orderbook-trade/core/depth-profile-book.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ export class DepthProfileSequenceError extends Error {
}

const MAX_BUFFERED_UPDATES = 500;
export const DEPTH_PROFILE_LEVELS_PER_SIDE = 1000;

function assertSymbol(value) {
if (typeof value !== 'string' || !/^[A-Z0-9_]+$/.test(value)) {
Expand Down Expand Up @@ -169,15 +168,14 @@ export function applyDepthProfileSnapshot(book, payload) {
return applyBufferedUpdates(book);
}

function toSortedLevels(levels, direction, limit) {
function toSortedLevels(levels, direction) {
return [...levels.entries()]
.map(([price, quantity]) => ({
price: Number(price),
quantity: Number(quantity),
}))
.filter((level) => Number.isFinite(level.price) && Number.isFinite(level.quantity))
.sort((left, right) => direction * (left.price - right.price))
.slice(0, limit);
.sort((left, right) => direction * (left.price - right.price));
}

function addCumulativeQuantity(levels) {
Expand All @@ -188,15 +186,10 @@ function addCumulativeQuantity(levels) {
});
}

export function buildDepthProfile(book, {
levelsPerSide = DEPTH_PROFILE_LEVELS_PER_SIDE,
} = {}) {
export function buildDepthProfile(book) {
if (!book.ready) throw new Error('Depth profile book is not ready');
if (!Number.isInteger(levelsPerSide) || levelsPerSide <= 0) {
throw new Error('Invalid depth profile level count');
}
const bids = addCumulativeQuantity(toSortedLevels(book.bids, -1, levelsPerSide));
const asks = addCumulativeQuantity(toSortedLevels(book.asks, 1, levelsPerSide));
const bids = addCumulativeQuantity(toSortedLevels(book.bids, -1));
const asks = addCumulativeQuantity(toSortedLevels(book.asks, 1));
if (!bids.length || !asks.length) throw new Error('Depth profile requires bids and asks');

const midPrice = (bids[0].price + asks[0].price) / 2;
Expand Down
2 changes: 1 addition & 1 deletion src/binance-orderbook-trade/index.user.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// @namespace binance.orderbook.trade
// @icon data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23f0b90b%22%2F%3E%3Ctext%20x%3D%2232%22%20y%3D%2249%22%20text-anchor%3D%22middle%22%20font-family%3D%22Arial%2C%20sans-serif%22%20font-size%3D%2242%22%20font-weight%3D%22800%22%20fill%3D%22%23111827%22%3EJ%3C%2Ftext%3E%3C%2Fsvg%3E
// @icon64 data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2064%2064%22%3E%3Crect%20width%3D%2264%22%20height%3D%2264%22%20rx%3D%2214%22%20fill%3D%22%23f0b90b%22%2F%3E%3Ctext%20x%3D%2232%22%20y%3D%2249%22%20text-anchor%3D%22middle%22%20font-family%3D%22Arial%2C%20sans-serif%22%20font-size%3D%2242%22%20font-weight%3D%22800%22%20fill%3D%22%23111827%22%3EJ%3C%2Ftext%3E%3C%2Fsvg%3E
// @version 2.7.185
// @version 2.7.186
// @author jackhai9
// @description 单击订单簿价格,按当前开仓/平仓 tab 自动填数量并执行下单,内置数量倍率面板
// @match https://www.binance.com/*/futures/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,40 @@ test('observes the native RPI snapshot and stream without creating another socke
source.restore();
});

test('retains distant active prices delivered after the 1000-level native snapshot', async () => {
const denseSnapshot = snapshot({
bids: Array.from({ length: 1000 }, (_, index) => [String(100 - index / 1000), '1']),
asks: Array.from({ length: 1000 }, (_, index) => [String(101 + index / 1000), '1']),
});
const { globalObject, source } = createHarness(new FakeResponse(denseSnapshot));
const profiles = [];
source.subscribe({
symbol: 'BTCUSDT',
onProfile: (profile) => profiles.push(profile),
onStatus: () => {},
});

const nativeSocket = new globalObject.WebSocket('wss://native-binance-stream.example/ws');
const responsePromise = globalObject.fetch('/fapi/v1/rpiDepth?symbol=BTCUSDT&limit=1000');
nativeSocket.message(rpiMessage());
await responsePromise;
await new Promise((resolve) => setImmediate(resolve));
nativeSocket.message(rpiMessage(update({
U: 103,
u: 104,
pu: 102,
b: [['50', '7']],
a: [['150', '8']],
})));

const profile = profiles.at(-1);
assert.equal(profile.bids.length, 1002);
assert.equal(profile.asks.length, 1002);
assert.equal(profile.bids.at(-1).price, 50);
assert.equal(profile.asks.at(-1).price, 150);
source.restore();
});

test('preserves native fetch, WebSocket prototype, instanceof, and static constants', async () => {
const {
fetchCalls,
Expand Down
18 changes: 9 additions & 9 deletions test/unit/binance-orderbook-trade/depth-profile-book.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
applyDepthProfileSnapshot,
buildDepthProfile,
createDepthProfileBook,
DEPTH_PROFILE_LEVELS_PER_SIDE,
DepthProfileSequenceError,
pushDepthProfileUpdate,
} from '../../../src/binance-orderbook-trade/core/depth-profile-book.js';
Expand Down Expand Up @@ -112,7 +111,7 @@ test('builds a symmetric vertical price range with cumulative depth', () => {
}));
applyDepthProfileSnapshot(book, snapshot());

const profile = buildDepthProfile(book, { levelsPerSide: 3 });
const profile = buildDepthProfile(book);

assert.equal(profile.midPrice, 100.5);
assert.equal(profile.minPrice, 98);
Expand All @@ -122,19 +121,20 @@ test('builds a symmetric vertical price range with cumulative depth', () => {
assert.equal(profile.maxCumulative, 20);
});

test('builds every level available from the 1000-level snapshot by default', () => {
test('preserves every active price level accumulated from the native depth stream', () => {
const book = createDepthProfileBook('BTCUSDT');
book.ready = true;
for (let index = 0; index < DEPTH_PROFILE_LEVELS_PER_SIDE + 1; index += 1) {
for (let index = 0; index < 1001; index += 1) {
book.bids.set(String(100 - index / 1000), '1');
book.asks.set(String(101 + index / 1000), '1');
}

const profile = buildDepthProfile(book);

assert.equal(DEPTH_PROFILE_LEVELS_PER_SIDE, 1000);
assert.equal(profile.bids.length, 1000);
assert.equal(profile.asks.length, 1000);
assert.equal(profile.bids.at(-1).cumulative, 1000);
assert.equal(profile.asks.at(-1).cumulative, 1000);
assert.equal(profile.bids.length, 1001);
assert.equal(profile.asks.length, 1001);
assert.equal(profile.bids.at(-1).price, 99);
assert.equal(profile.asks.at(-1).price, 102);
assert.equal(profile.bids.at(-1).cumulative, 1001);
assert.equal(profile.asks.at(-1).cumulative, 1001);
});
Loading