🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@pear-protocol/exchanges-sdk

Package Overview
Dependencies
Maintainers
3
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@pear-protocol/exchanges-sdk - npm Package Compare versions

Comparing version
0.0.13
to
0.0.14
+26
dist/account/exchanges/okx/asset-tracker.d.ts
import { OkxCredentialsDTO } from '@pear-protocol/types';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import './types.js';
type OnStateUpdate = (update: StateUpdate) => void;
type OnError = (error: Error) => void;
declare class OkxAssetTracker {
private onStateUpdate;
private onError;
private getCreds;
private getDemo;
private trackedAssetInfos;
constructor(deps: {
onStateUpdate: OnStateUpdate;
onError: OnError;
getCreds: () => OkxCredentialsDTO;
getDemo: () => boolean;
});
getInfos(): Map<string, TrackedAssetInfo>;
onAssetTracked(instId: string): void;
onAssetUntracked(instId: string): void;
}
export { OkxAssetTracker };
import { fetchLeverageInfo } from './rest';
class OkxAssetTracker {
onStateUpdate;
onError;
getCreds;
getDemo;
trackedAssetInfos = /* @__PURE__ */ new Map();
constructor(deps) {
this.onStateUpdate = deps.onStateUpdate;
this.onError = deps.onError;
this.getCreds = deps.getCreds;
this.getDemo = deps.getDemo;
}
getInfos() {
return this.trackedAssetInfos;
}
onAssetTracked(instId) {
fetchLeverageInfo(this.getCreds(), instId, this.getDemo()).then((info) => {
const leverage = info?.lever || "0";
const marginType = info?.mgnMode;
const trackedAssetInfo = { coin: instId, leverage, marginType };
this.trackedAssetInfos.set(instId, trackedAssetInfo);
const trackedAssets = /* @__PURE__ */ new Map([[instId, trackedAssetInfo]]);
this.onStateUpdate({ trackedAssets });
}).catch((err) => this.onError(err instanceof Error ? err : new Error(String(err))));
}
onAssetUntracked(instId) {
this.trackedAssetInfos.delete(instId);
this.onStateUpdate({ trackedAssets: new Map(this.trackedAssetInfos) });
}
}
export { OkxAssetTracker };
declare const REST_BASE_URL = "https://www.okx.com";
declare const WS_PRIVATE_URL = "wss://ws.okx.com:8443/ws/v5/private";
declare const WS_PRIVATE_URL_DEMO = "wss://wspap.okx.com:8443/ws/v5/private?brokerId=9999";
declare const DEFAULT_PING_INTERVAL_MS = 25000;
declare const LOGIN_TIMEOUT_MS = 10000;
export { DEFAULT_PING_INTERVAL_MS, LOGIN_TIMEOUT_MS, REST_BASE_URL, WS_PRIVATE_URL, WS_PRIVATE_URL_DEMO };
const REST_BASE_URL = "https://www.okx.com";
const WS_PRIVATE_URL = "wss://ws.okx.com:8443/ws/v5/private";
const WS_PRIVATE_URL_DEMO = "wss://wspap.okx.com:8443/ws/v5/private?brokerId=9999";
const DEFAULT_PING_INTERVAL_MS = 25e3;
const LOGIN_TIMEOUT_MS = 1e4;
export { DEFAULT_PING_INTERVAL_MS, LOGIN_TIMEOUT_MS, REST_BASE_URL, WS_PRIVATE_URL, WS_PRIVATE_URL_DEMO };
import { a as AccountBalance, c as AccountPosition } from '../../../types-Caz2X4h0.js';
import { OkxAccountType, OkxRawBalance, OkxRawBalanceDetail, OkxRawPosition } from './types.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../hyperliquid/types.js';
declare function mergeRawCoins(existing: Map<string, OkxRawBalanceDetail>, incoming: OkxRawBalanceDetail[]): Map<string, OkxRawBalanceDetail>;
declare function buildBalance(raw: OkxRawBalance, coins: Map<string, OkxRawBalanceDetail>, accountType: OkxAccountType | null): AccountBalance | null;
declare function mapSinglePosition(p: OkxRawPosition): AccountPosition;
declare function mapPositions(raw: OkxRawPosition[]): Map<string, AccountPosition>;
declare function mapPositionUpdates(raw: OkxRawPosition[]): Map<string, AccountPosition>;
declare function acctLvToAccountType(acctLv: string): OkxAccountType | null;
export { acctLvToAccountType, buildBalance, mapPositionUpdates, mapPositions, mapSinglePosition, mergeRawCoins };
import { positionKey } from '../../utils';
import { OkxAccountType } from './types';
function mergeRawCoins(existing, incoming) {
const merged = new Map(existing);
for (const d of incoming) {
merged.set(d.ccy, d);
}
return merged;
}
function buildBalance(raw, coins, accountType) {
if (!accountType) return null;
const isSpot = accountType === OkxAccountType.SPOT;
const free = {};
const used = {};
const total = {};
const assets = [];
let walletBalanceSum = 0;
for (const [, d] of coins) {
const eq = d.eq ?? "0";
const eqNum = parseFloat(eq);
const cashNum = parseFloat(d.cashBal ?? "0");
if (eqNum === 0 && cashNum === 0) continue;
const coinFree = isSpot ? d.availBal ?? "0" : d.availEq || d.availBal || "0";
const coinUsed = (eqNum - parseFloat(coinFree)).toString();
free[d.ccy] = coinFree;
used[d.ccy] = coinUsed;
total[d.ccy] = eq;
walletBalanceSum += cashNum;
assets.push({
asset: d.ccy,
free: coinFree,
used: coinUsed,
total: eq,
walletBalance: d.cashBal ?? "0",
usdValue: d.eqUsd ?? "0"
});
}
const availableToTrade = raw.availEq || raw.adjEq || "0";
return {
accountType,
free,
used,
total,
availableToTrade,
totalEquity: raw.totalEq ?? "0",
walletBalance: walletBalanceSum.toString(),
unrealizedPnl: raw.upl || "0",
initialMarginUsed: raw.imr || "0",
maintenanceMargin: raw.mmr || "0",
marginRatio: raw.mgnRatio || "0.0000",
assets,
timestamp: Date.now()
};
}
function mapSinglePosition(p) {
const posNum = parseFloat(p.pos ?? "0");
let side;
if (p.posSide === "long") side = "long";
else if (p.posSide === "short") side = "short";
else side = posNum < 0 ? "short" : "long";
const rawSize = p.pos ?? "0";
let size;
if (rawSize === "0" || rawSize === "") {
size = "0";
} else if (side === "short" && !rawSize.startsWith("-")) {
size = `-${rawSize}`;
} else {
size = rawSize;
}
const marginType = p.mgnMode;
return {
symbol: p.instId ?? "",
side,
size,
entryPrice: p.avgPx ?? "0",
unrealizedPnl: p.upl ?? "0",
leverage: p.lever ?? "0",
marginType,
liquidationPrice: p.liqPx || null
};
}
function mapPositions(raw) {
const positions = /* @__PURE__ */ new Map();
for (const p of raw) {
const pos = p.pos ?? "0";
if (pos === "0" || pos === "") continue;
const mapped = mapSinglePosition(p);
positions.set(positionKey(mapped.symbol, mapped.side), mapped);
}
return positions;
}
function mapPositionUpdates(raw) {
const positions = /* @__PURE__ */ new Map();
for (const p of raw) {
const mapped = mapSinglePosition(p);
positions.set(positionKey(mapped.symbol, mapped.side), mapped);
}
return positions;
}
function acctLvToAccountType(acctLv) {
switch (acctLv) {
case "1":
return OkxAccountType.SPOT;
case "2":
return OkxAccountType.SINGLE_CURRENCY_MARGIN;
case "3":
return OkxAccountType.MULTI_CURRENCY_MARGIN;
case "4":
return OkxAccountType.PORTFOLIO_MARGIN;
default:
return null;
}
}
export { acctLvToAccountType, buildBalance, mapPositionUpdates, mapPositions, mapSinglePosition, mergeRawCoins };
import { g as SupportedCredentials } from '../../../types-Caz2X4h0.js';
import { BaseOrchestrator, OrchestratorConfig } from '../base.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import './types.js';
declare class OkxOrchestrator extends BaseOrchestrator {
private ws;
private creds;
private stateHandler;
private assetTracker;
constructor(config: OrchestratorConfig, credentials: SupportedCredentials);
protected initAsync(): Promise<void>;
protected cleanupConnections(): void;
stop(): Promise<void>;
get isConnected(): boolean;
onAssetTracked(coin: string): void;
onAssetUntracked(coin: string): void;
}
export { OkxOrchestrator };
import { BaseOrchestrator } from '../base';
import { OkxAssetTracker } from './asset-tracker';
import { acctLvToAccountType } from './mapper';
import { fetchAccountConfig, fetchBalance, fetchPositions } from './rest';
import { OkxStateHandler } from './state-handler';
import { OkxWs } from './ws';
class OkxOrchestrator extends BaseOrchestrator {
ws = null;
creds;
stateHandler;
assetTracker;
constructor(config, credentials) {
super(config);
this.credentials = credentials;
this.creds = credentials;
this.assetTracker = new OkxAssetTracker({
onStateUpdate: (update) => this.onStateUpdate(update),
onError: (err) => this.onError(err),
getCreds: () => this.creds,
getDemo: () => this.demo
});
this.stateHandler = new OkxStateHandler({
onStateUpdate: (update) => this.onStateUpdate(update),
getTrackedAssetInfos: () => this.assetTracker.getInfos()
});
}
async initAsync() {
const [config, balance, positions] = await Promise.all([
fetchAccountConfig(this.creds, this.demo),
fetchBalance(this.creds, this.demo),
fetchPositions(this.creds, this.demo)
]);
this.stateHandler.setAccountType(acctLvToAccountType(config.acctLv));
this.stateHandler.handleInitialData(balance, positions);
this.ws = new OkxWs({ onMessage: (msg) => this.stateHandler.handleMessage(msg) }, this.demo);
await this.ws.connect(this.creds);
}
cleanupConnections() {
this.ws?.close();
}
async stop() {
this.stopped = true;
this.cleanupConnections();
}
get isConnected() {
return this.ws?.isConnected ?? false;
}
onAssetTracked(coin) {
this.assetTracker.onAssetTracked(coin);
}
onAssetUntracked(coin) {
this.assetTracker.onAssetUntracked(coin);
}
}
export { OkxOrchestrator };
import { OkxCredentialsDTO } from '@pear-protocol/types';
import { OkxRawAccountConfig, OkxRawBalance, OkxRawLeverageInfo, OkxRawPosition } from './types.js';
declare function fetchAccountConfig(creds: OkxCredentialsDTO, demo: boolean): Promise<OkxRawAccountConfig>;
declare function fetchBalance(creds: OkxCredentialsDTO, demo: boolean): Promise<OkxRawBalance>;
declare function fetchPositions(creds: OkxCredentialsDTO, demo: boolean): Promise<OkxRawPosition[]>;
declare function fetchLeverageInfo(creds: OkxCredentialsDTO, instId: string, demo: boolean): Promise<OkxRawLeverageInfo | undefined>;
export { fetchAccountConfig, fetchBalance, fetchLeverageInfo, fetchPositions };
import { hmacSha256Base64 } from '../../../utils/hmac';
import { REST_BASE_URL } from './const';
async function signedGet(creds, path, params, demo) {
const queryString = new URLSearchParams(params).toString();
const fullPath = queryString ? `${path}?${queryString}` : path;
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const signPayload = `${timestamp}GET${fullPath}`;
const signature = await hmacSha256Base64(creds.api_secret, signPayload);
const headers = {
"OK-ACCESS-KEY": creds.api_key,
"OK-ACCESS-SIGN": signature,
"OK-ACCESS-TIMESTAMP": timestamp,
"OK-ACCESS-PASSPHRASE": creds.api_pass,
"Content-Type": "application/json"
};
if (demo) {
headers["x-simulated-trading"] = "1";
}
const response = await fetch(`${REST_BASE_URL}${fullPath}`, { headers });
if (!response.ok) {
throw new Error(`OKX API error: ${response.status} ${response.statusText}`);
}
const body = await response.json();
if (body.code !== "0") {
throw new Error(`OKX API error: ${body.code} ${body.msg}`);
}
return body.data;
}
async function fetchAccountConfig(creds, demo) {
const data = await signedGet(creds, "/api/v5/account/config", {}, demo);
if (!data[0]) {
throw new Error("OKX API error: empty account config response");
}
return data[0];
}
async function fetchBalance(creds, demo) {
const data = await signedGet(creds, "/api/v5/account/balance", {}, demo);
if (!data[0]) {
throw new Error("OKX API error: empty balance response");
}
return data[0];
}
async function fetchPositions(creds, demo) {
return signedGet(creds, "/api/v5/account/positions", { instType: "SWAP" }, demo);
}
async function fetchLeverageInfo(creds, instId, demo) {
const result = await signedGet(
creds,
"/api/v5/account/leverage-info",
{ instId, mgnMode: "cross" },
demo
).catch(() => []);
return result[0];
}
export { fetchAccountConfig, fetchBalance, fetchLeverageInfo, fetchPositions };
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import { OkxAccountType, OkxRawBalance, OkxRawPosition, OkxWsMessage } from './types.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../hyperliquid/types.js';
type OnStateUpdate = (update: StateUpdate) => void;
declare class OkxStateHandler {
private onStateUpdate;
private getTrackedAssetInfos;
private rawCoins;
private lastBalance;
private accountType;
constructor(deps: {
onStateUpdate: OnStateUpdate;
getTrackedAssetInfos: () => Map<string, TrackedAssetInfo>;
});
setAccountType(type: OkxAccountType | null): void;
handleInitialData(balance: OkxRawBalance, positions: OkxRawPosition[]): void;
handleMessage(msg: OkxWsMessage): void;
private handleBalanceUpdate;
}
export { OkxStateHandler };
import { mergeRawCoins, buildBalance, mapPositions, mapPositionUpdates } from './mapper';
class OkxStateHandler {
onStateUpdate;
getTrackedAssetInfos;
rawCoins = /* @__PURE__ */ new Map();
lastBalance = null;
accountType = null;
constructor(deps) {
this.onStateUpdate = deps.onStateUpdate;
this.getTrackedAssetInfos = deps.getTrackedAssetInfos;
}
setAccountType(type) {
this.accountType = type;
}
handleInitialData(balance, positions) {
this.lastBalance = balance;
this.rawCoins = mergeRawCoins(/* @__PURE__ */ new Map(), balance.details ?? []);
const built = buildBalance(balance, this.rawCoins, this.accountType);
if (built) this.onStateUpdate({ balance: built });
this.onStateUpdate({ positions: mapPositions(positions) });
}
handleMessage(msg) {
if (msg.arg.channel === "account") {
const raw = msg.data[0];
if (raw) this.handleBalanceUpdate(raw);
return;
}
if (msg.arg.channel === "positions") {
const posMsg = msg;
const action = posMsg.action ?? "update";
const rawPositions = posMsg.data;
const positions = action === "snapshot" ? mapPositions(rawPositions) : mapPositionUpdates(rawPositions);
if (positions.size === 0 && action !== "snapshot") return;
const leverageSettings = /* @__PURE__ */ new Map();
for (const p of rawPositions) {
if (p.instId && p.lever) {
leverageSettings.set(p.instId, p.lever);
}
}
const trackedAssetInfos = this.getTrackedAssetInfos();
const trackedAssets = /* @__PURE__ */ new Map();
for (const p of rawPositions) {
const existing = trackedAssetInfos.get(p.instId);
if (existing) {
const leverage = p.lever || existing.leverage;
const marginType = p.mgnMode;
const updated = { ...existing, leverage, marginType };
trackedAssetInfos.set(p.instId, updated);
trackedAssets.set(p.instId, updated);
}
}
this.onStateUpdate({
positions,
leverageSettings,
...trackedAssets.size > 0 ? { trackedAssets } : {}
});
}
}
handleBalanceUpdate(raw) {
this.rawCoins = mergeRawCoins(this.rawCoins, raw.details ?? []);
const merged = this.lastBalance ? {
totalEq: raw.totalEq || this.lastBalance.totalEq,
adjEq: raw.adjEq || this.lastBalance.adjEq,
availEq: raw.availEq || this.lastBalance.availEq,
mmr: raw.mmr || this.lastBalance.mmr,
imr: raw.imr || this.lastBalance.imr,
upl: raw.upl || this.lastBalance.upl,
mgnRatio: raw.mgnRatio || this.lastBalance.mgnRatio,
details: raw.details ?? this.lastBalance.details
} : raw;
this.lastBalance = merged;
const built = buildBalance(merged, this.rawCoins, this.accountType);
if (built) this.onStateUpdate({ balance: built });
}
}
export { OkxStateHandler };
declare enum OkxAccountType {
SPOT = "OKX_SPOT",
SINGLE_CURRENCY_MARGIN = "OKX_SINGLE",
MULTI_CURRENCY_MARGIN = "OKX_MULTI",
PORTFOLIO_MARGIN = "OKX_PORTFOLIO"
}
interface OkxRawAccountConfig {
acctLv: string;
uid: string;
}
interface OkxRawBalanceDetail {
ccy: string;
eq: string;
availEq: string;
availBal: string;
cashBal: string;
frozenBal: string;
ordFrozen: string;
imr: string;
mmr: string;
upl: string;
eqUsd: string;
}
interface OkxRawBalance {
totalEq: string;
adjEq: string;
availEq: string;
mmr: string;
imr: string;
upl: string;
mgnRatio: string;
details: OkxRawBalanceDetail[];
}
interface OkxRawPosition {
instId: string;
instType: string;
posSide: string;
pos: string;
avgPx: string;
upl: string;
lever: string;
mgnMode: string;
liqPx: string;
ccy: string;
}
interface OkxRawLeverageInfo {
instId: string;
lever: string;
mgnMode: string;
}
interface OkxWsAccountMessage {
arg: {
channel: 'account';
};
data: OkxRawBalance[];
}
interface OkxWsPositionsMessage {
arg: {
channel: 'positions';
};
action?: 'snapshot' | 'update';
data: OkxRawPosition[];
}
type OkxWsMessage = OkxWsAccountMessage | OkxWsPositionsMessage;
interface OkxWsHandlers {
onMessage: (msg: OkxWsMessage) => void;
}
export { OkxAccountType, type OkxRawAccountConfig, type OkxRawBalance, type OkxRawBalanceDetail, type OkxRawLeverageInfo, type OkxRawPosition, type OkxWsAccountMessage, type OkxWsHandlers, type OkxWsMessage, type OkxWsPositionsMessage };
var OkxAccountType = /* @__PURE__ */ ((OkxAccountType2) => {
OkxAccountType2["SPOT"] = "OKX_SPOT";
OkxAccountType2["SINGLE_CURRENCY_MARGIN"] = "OKX_SINGLE";
OkxAccountType2["MULTI_CURRENCY_MARGIN"] = "OKX_MULTI";
OkxAccountType2["PORTFOLIO_MARGIN"] = "OKX_PORTFOLIO";
return OkxAccountType2;
})(OkxAccountType || {});
export { OkxAccountType };
import { OkxCredentialsDTO } from '@pear-protocol/types';
import { OkxWsHandlers } from './types.js';
declare class OkxWs {
private ws;
private pingTimer;
private handlers;
private demo;
private creds;
private readonly pingIntervalMs;
constructor(handlers: OkxWsHandlers, demo: boolean, pingIntervalMs?: number);
connect(creds: OkxCredentialsDTO): Promise<void>;
close(): void;
get isConnected(): boolean;
private clearPing;
private subscribe;
private login;
}
export { OkxWs };
import { hmacSha256Base64 } from '../../../utils/hmac';
import { createWs, waitForOpen, sendWs, ReconnectingWebSocket, clearIntervalTimer } from '../../../utils/ws';
import { DEFAULT_PING_INTERVAL_MS, WS_PRIVATE_URL_DEMO, WS_PRIVATE_URL, LOGIN_TIMEOUT_MS } from './const';
class OkxWs {
ws = null;
pingTimer = null;
handlers;
demo;
creds = null;
pingIntervalMs;
constructor(handlers, demo, pingIntervalMs = DEFAULT_PING_INTERVAL_MS) {
this.handlers = handlers;
this.demo = demo;
this.pingIntervalMs = pingIntervalMs;
}
async connect(creds) {
this.creds = creds;
this.ws = createWs(this.demo ? WS_PRIVATE_URL_DEMO : WS_PRIVATE_URL);
this.ws.addEventListener("message", (event) => {
const data = event.data;
if (typeof data !== "string" || data === "pong") return;
try {
const msg = JSON.parse(data);
if (msg.event) return;
if (msg.arg && msg.data) {
this.handlers.onMessage(msg);
}
} catch {
}
});
let initialOpen = true;
this.ws.addEventListener("open", () => {
if (initialOpen) {
initialOpen = false;
return;
}
if (!this.creds) return;
this.login(this.creds).then(() => this.subscribe()).catch(() => {
});
});
await waitForOpen(this.ws);
await this.login(creds);
this.subscribe();
this.pingTimer = setInterval(() => sendWs(this.ws, "ping"), this.pingIntervalMs);
}
close() {
this.clearPing();
this.creds = null;
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
get isConnected() {
return this.ws?.readyState === ReconnectingWebSocket.OPEN;
}
clearPing() {
this.pingTimer = clearIntervalTimer(this.pingTimer);
}
subscribe() {
sendWs(this.ws, {
op: "subscribe",
args: [{ channel: "account" }, { channel: "positions", instType: "SWAP" }]
});
}
async login(creds) {
const timestamp = (Date.now() / 1e3).toString();
const sign = await hmacSha256Base64(creds.api_secret, `${timestamp}GET/users/self/verify`);
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
this.ws?.removeEventListener("message", handler);
reject(new Error("OKX login timeout"));
}, LOGIN_TIMEOUT_MS);
const handler = (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.event === "login") {
clearTimeout(timeout);
this.ws?.removeEventListener("message", handler);
if (msg.code === "0") resolve();
else reject(new Error(`OKX login failed: ${msg.msg ?? "unknown"}`));
}
} catch {
}
};
this.ws?.addEventListener("message", handler);
sendWs(this.ws, {
op: "login",
args: [
{
apiKey: creds.api_key,
passphrase: creds.api_pass,
timestamp,
sign
}
]
});
});
}
}
export { OkxWs };
import { Connector, BinanceCredentialsDTO, BybitCredentialsDTO, HyperliquidCredentialsDTO, OkxCredentialsDTO } from '@pear-protocol/types';
import { BybitAccountType } from './account/exchanges/bybit/types.js';
import { HyperliquidAccountType } from './account/exchanges/hyperliquid/types.js';
import { OkxAccountType } from './account/exchanges/okx/types.js';
declare enum BinanceAccountType {
MULTI_ASSET = "MULTI_ASSET",
SINGLE_ASSET = "SINGLE_ASSET"
}
interface BinanceRawPositionRisk {
symbol: string;
leverage: string;
marginType: MarginMode;
isAutoAddMargin: string;
isolatedMargin: string;
positionAmt: string;
entryPrice: string;
breakEvenPrice: string;
unRealizedProfit: string;
liquidationPrice: string;
markPrice: string;
maxNotionalValue: string;
positionSide: string;
notional: string;
isolatedWallet: string;
updateTime: number;
}
interface BinanceRawAsset {
asset: string;
walletBalance: string;
availableBalance: string;
unrealizedProfit: string;
marginBalance: string;
initialMargin: string;
maintMargin: string;
marginAvailable: boolean;
}
interface BinanceRawAccountStatus {
totalWalletBalance: string;
totalMarginBalance: string;
availableBalance: string;
totalUnrealizedProfit: string;
totalInitialMargin: string;
totalMaintMargin: string;
assets?: BinanceRawAsset[];
}
interface BinanceMultiAssetsMarginResponse {
multiAssetsMargin: boolean;
}
interface BinanceAssetIndex {
symbol: string;
time: number;
index: string;
bidBuffer: string;
askBuffer: string;
bidRate: string;
askRate: string;
autoExchangeBidBuffer: string;
autoExchangeAskBuffer: string;
autoExchangeBidRate: string;
autoExchangeAskRate: string;
}
interface BinanceRawUserDataEvent {
e?: string;
ac?: {
s: string;
l: string;
};
a?: {
B?: unknown[];
P?: unknown[];
};
}
interface BinanceWsHandlers {
onUserDataEvent: (event: unknown) => void;
onWsApiResponse: (id: number, result: unknown) => void;
}
type MarginMode = 'cross' | 'isolated';
type AccountType = BinanceAccountType | BybitAccountType | HyperliquidAccountType | OkxAccountType;
declare const ACCOUNT_TYPE_LABELS: Record<AccountType, string>;
interface AssetBalance {
asset: string;
free: string;
used: string;
total: string;
walletBalance: string;
usdValue: string;
}
interface AccountBalance {
accountType: AccountType;
free: Record<string, string>;
used: Record<string, string>;
total: Record<string, string>;
availableToTrade: string;
totalEquity: string;
walletBalance: string;
unrealizedPnl: string;
initialMarginUsed: string;
maintenanceMargin: string;
marginRatio: string;
assets: AssetBalance[];
timestamp: number;
}
interface AccountPosition {
symbol: string;
side: 'long' | 'short' | 'both';
size: string;
entryPrice: string;
unrealizedPnl: string;
leverage: string;
marginType: MarginMode;
liquidationPrice: string | null;
}
interface TrackedAssetInfo {
coin: string;
leverage: string;
marginType: MarginMode;
}
interface ExchangeState {
balance: AccountBalance | null;
positions: Map<string, AccountPosition>;
leverageSettings: Map<string, string>;
trackedAssets: Map<string, TrackedAssetInfo>;
lastUpdated: number;
initialized: boolean;
}
type BalanceCallback = (balance: AccountBalance) => void;
type PositionsCallback = (positions: AccountPosition[]) => void;
type TrackedAssetCallback = (info: TrackedAssetInfo) => void;
interface Tracker<T> {
get(): T;
untrack(): void;
}
interface AccountConfig {
exchange: Connector;
demo?: boolean;
onAuthError?: () => void;
}
type HyperliquidAccountCredentials = HyperliquidCredentialsDTO & {
address: string;
};
type SupportedCredentials = BinanceCredentialsDTO | BybitCredentialsDTO | HyperliquidAccountCredentials | OkxCredentialsDTO;
interface StateUpdate {
balance?: AccountBalance;
positions?: Map<string, AccountPosition>;
leverageSettings?: Map<string, string>;
trackedAssets?: Map<string, TrackedAssetInfo>;
}
export { ACCOUNT_TYPE_LABELS as A, type BalanceCallback as B, type ExchangeState as E, type HyperliquidAccountCredentials as H, type MarginMode as M, type PositionsCallback as P, type StateUpdate as S, type TrackedAssetCallback as T, type AccountBalance as a, type AccountConfig as b, type AccountPosition as c, type AccountType as d, type AssetBalance as e, BinanceAccountType as f, type SupportedCredentials as g, type TrackedAssetInfo as h, type Tracker as i, type BinanceRawAccountStatus as j, type BinanceRawPositionRisk as k, type BinanceAssetIndex as l, type BinanceRawUserDataEvent as m, type BinanceWsHandlers as n, type BinanceMultiAssetsMarginResponse as o, type BinanceRawAsset as p };
+2
-1
import PearSDK from '@pear-protocol/core-sdk';
import { Connector } from '@pear-protocol/types';
import { Credentials } from '../credentials.js';
import { B as BalanceCallback, i as Tracker, a as AccountBalance, P as PositionsCallback, c as AccountPosition, T as TrackedAssetCallback, h as TrackedAssetInfo } from '../types-D2dbAtin.js';
import { B as BalanceCallback, i as Tracker, a as AccountBalance, P as PositionsCallback, c as AccountPosition, T as TrackedAssetCallback, h as TrackedAssetInfo } from '../types-Caz2X4h0.js';
import './exchanges/bybit/types.js';
import './exchanges/hyperliquid/types.js';
import './exchanges/okx/types.js';

@@ -8,0 +9,0 @@ declare class AccountManager {

@@ -1,5 +0,6 @@

import { b as AccountConfig, g as SupportedCredentials, B as BalanceCallback, a as AccountBalance, P as PositionsCallback, c as AccountPosition, T as TrackedAssetCallback, h as TrackedAssetInfo } from '../types-D2dbAtin.js';
import { b as AccountConfig, g as SupportedCredentials, B as BalanceCallback, a as AccountBalance, P as PositionsCallback, c as AccountPosition, T as TrackedAssetCallback, h as TrackedAssetInfo } from '../types-Caz2X4h0.js';
import '@pear-protocol/types';
import './exchanges/bybit/types.js';
import './exchanges/hyperliquid/types.js';
import './exchanges/okx/types.js';

@@ -6,0 +7,0 @@ declare class ExchangeAccount {

@@ -1,5 +0,6 @@

import { S as StateUpdate, g as SupportedCredentials } from '../../types-D2dbAtin.js';
import { S as StateUpdate, g as SupportedCredentials } from '../../types-Caz2X4h0.js';
import '@pear-protocol/types';
import './bybit/types.js';
import './hyperliquid/types.js';
import './okx/types.js';

@@ -6,0 +7,0 @@ type StateUpdateHandler = (update: StateUpdate) => void;

import { BinanceCredentialsDTO } from '@pear-protocol/types';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-D2dbAtin.js';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -22,3 +22,3 @@ import { fetchPositionRisk } from './rest';

const leverage = risk.leverage;
const marginType = risk.marginType === "isolated" ? "isolated" : "cross";
const marginType = risk.marginType;
const info = { coin, leverage, marginType };

@@ -25,0 +25,0 @@ this.trackedAssetInfos.set(coin, info);

@@ -1,5 +0,6 @@

import { j as BinanceRawAccountStatus, a as AccountBalance, k as BinanceRawPositionRisk, c as AccountPosition } from '../../../types-D2dbAtin.js';
import { j as BinanceRawAccountStatus, a as AccountBalance, k as BinanceRawPositionRisk, c as AccountPosition } from '../../../types-Caz2X4h0.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ declare function mapBalance(raw: BinanceRawAccountStatus): Omit<AccountBalance, 'accountType'>;

@@ -1,2 +0,2 @@

import { g as SupportedCredentials } from '../../../types-D2dbAtin.js';
import { g as SupportedCredentials } from '../../../types-Caz2X4h0.js';
import { BaseOrchestrator, OrchestratorConfig } from '../base.js';

@@ -6,2 +6,3 @@ import '@pear-protocol/types';

import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -8,0 +9,0 @@ type BinanceOrchestratorConfig = OrchestratorConfig & {

import { BinanceCredentialsDTO } from '@pear-protocol/types';
import { j as BinanceRawAccountStatus, k as BinanceRawPositionRisk, l as BinanceAssetIndex } from '../../../types-D2dbAtin.js';
import { j as BinanceRawAccountStatus, k as BinanceRawPositionRisk, l as BinanceAssetIndex } from '../../../types-Caz2X4h0.js';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ declare function createListenKey(apiKey: string, demo?: boolean): Promise<string>;

import { BinanceCredentialsDTO } from '@pear-protocol/types';
import { S as StateUpdate, h as TrackedAssetInfo, j as BinanceRawAccountStatus, k as BinanceRawPositionRisk, m as BinanceRawUserDataEvent } from '../../../types-D2dbAtin.js';
import { S as StateUpdate, h as TrackedAssetInfo, j as BinanceRawAccountStatus, k as BinanceRawPositionRisk, m as BinanceRawUserDataEvent } from '../../../types-Caz2X4h0.js';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -96,3 +96,3 @@ import { positionKey } from '../../utils';

leverage: risk.leverage ?? "0",
marginType: risk.marginType === "isolated" ? "isolated" : "cross",
marginType: risk.marginType,
liquidationPrice: risk.liquidationPrice || null

@@ -99,0 +99,0 @@ });

@@ -1,4 +0,5 @@

export { f as BinanceAccountType, l as BinanceAssetIndex, o as BinanceMultiAssetsMarginResponse, j as BinanceRawAccountStatus, p as BinanceRawAsset, k as BinanceRawPositionRisk, m as BinanceRawUserDataEvent, n as BinanceWsHandlers } from '../../../types-D2dbAtin.js';
export { f as BinanceAccountType, l as BinanceAssetIndex, o as BinanceMultiAssetsMarginResponse, j as BinanceRawAccountStatus, p as BinanceRawAsset, k as BinanceRawPositionRisk, m as BinanceRawUserDataEvent, n as BinanceWsHandlers } from '../../../types-Caz2X4h0.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';
import { BinanceCredentialsDTO } from '@pear-protocol/types';
import { n as BinanceWsHandlers } from '../../../types-D2dbAtin.js';
import { n as BinanceWsHandlers } from '../../../types-Caz2X4h0.js';
import '../bybit/types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ declare class BinanceWs {

import { BybitCredentialsDTO } from '@pear-protocol/types';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-D2dbAtin.js';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import './types.js';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -0,1 +1,2 @@

import '@pear-protocol/types';
import { fetchPositionLeverage } from './rest';

@@ -21,3 +22,3 @@

const leverage = pos?.leverage || "1";
const marginType = pos?.tradeMode === "1" ? "isolated" : "cross";
const marginType = pos?.tradeMode === "1" ? "cross" : "isolated";
const info = { coin, leverage, marginType };

@@ -24,0 +25,0 @@ this.trackedAssetInfos.set(coin, info);

@@ -1,5 +0,6 @@

import { a as AccountBalance, c as AccountPosition } from '../../../types-D2dbAtin.js';
import { a as AccountBalance, c as AccountPosition } from '../../../types-Caz2X4h0.js';
import { BybitRawWallet, BybitRawCoin, BybitAccountType, BybitRawPosition } from './types.js';
import '@pear-protocol/types';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ declare function buildBalance(raw: BybitRawWallet, coins: Map<string, BybitRawCoin>, accountType: BybitAccountType | null): AccountBalance | null;

@@ -1,2 +0,2 @@

import { g as SupportedCredentials } from '../../../types-D2dbAtin.js';
import { g as SupportedCredentials } from '../../../types-Caz2X4h0.js';
import { BaseOrchestrator, OrchestratorConfig } from '../base.js';

@@ -6,2 +6,3 @@ import '@pear-protocol/types';

import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -8,0 +9,0 @@ declare class BybitOrchestrator extends BaseOrchestrator {

@@ -1,5 +0,6 @@

import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-D2dbAtin.js';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import { BybitRawWallet, BybitRawPosition, BybitAccountType, BybitWsMessage } from './types.js';
import '@pear-protocol/types';
import '../hyperliquid/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -1,2 +0,2 @@

import { S as StateUpdate } from '../../../types-D2dbAtin.js';
import { S as StateUpdate } from '../../../types-Caz2X4h0.js';
import { WebSocket } from 'partysocket';

@@ -6,2 +6,3 @@ import { ActiveAssetDataEvent } from './types.js';

import '../bybit/types.js';
import '../okx/types.js';

@@ -8,0 +9,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -1,5 +0,6 @@

import { a as AccountBalance, c as AccountPosition } from '../../../types-D2dbAtin.js';
import { a as AccountBalance, c as AccountPosition } from '../../../types-Caz2X4h0.js';
import { AggregatedClearinghouseSummary, HyperliquidCoinBalance, HyperliquidAccountType, AssetPosition } from './types.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ declare function mapBalance(summary: AggregatedClearinghouseSummary, spotCoinBalances: Map<string, HyperliquidCoinBalance>, accountType: HyperliquidAccountType | null, availableToTradeByCollateral: Map<string, number>): AccountBalance | null;

@@ -1,2 +0,2 @@

import { g as SupportedCredentials } from '../../../types-D2dbAtin.js';
import { g as SupportedCredentials } from '../../../types-Caz2X4h0.js';
import { BaseOrchestrator, OrchestratorConfig } from '../base.js';

@@ -6,2 +6,3 @@ import '@pear-protocol/types';

import './types.js';
import '../okx/types.js';

@@ -8,0 +9,0 @@ declare class HyperliquidOrchestrator extends BaseOrchestrator {

@@ -1,5 +0,6 @@

import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-D2dbAtin.js';
import { S as StateUpdate, h as TrackedAssetInfo } from '../../../types-Caz2X4h0.js';
import { AllPerpMetasResponse, AllDexsClearinghouseStateEvent, ActiveAssetDataEvent, WebData3Event, SpotStateEvent } from './types.js';
import '@pear-protocol/types';
import '../bybit/types.js';
import '../okx/types.js';

@@ -6,0 +7,0 @@ type OnStateUpdate = (update: StateUpdate) => void;

@@ -100,3 +100,3 @@ import { mapPositions, mapBalance } from './mapper';

leverage: (data.leverage?.value ?? 1).toString(),
marginType: data.leverage?.type === "isolated" ? "isolated" : "cross"
marginType: data.leverage?.type
};

@@ -103,0 +103,0 @@ }

import { Connector } from '@pear-protocol/types';
import { g as SupportedCredentials } from '../../types-Caz2X4h0.js';
export { f as BinanceAccountType } from '../../types-Caz2X4h0.js';
import { OrchestratorConfig, Orchestrator } from './base.js';
import { g as SupportedCredentials } from '../../types-D2dbAtin.js';
export { f as BinanceAccountType } from '../../types-D2dbAtin.js';
export { BybitAccountType } from './bybit/types.js';
export { HyperliquidAccountType } from './hyperliquid/types.js';
export { OkxAccountType } from './okx/types.js';

@@ -8,0 +9,0 @@ declare function createOrchestrator(exchange: Connector, config: OrchestratorConfig, credentials: SupportedCredentials): Orchestrator;

@@ -5,5 +5,7 @@ import './base';

import { HyperliquidOrchestrator } from './hyperliquid/orchestrator';
import { OkxOrchestrator } from './okx/orchestrator';
export { BinanceAccountType } from './binance/types';
export { BybitAccountType } from './bybit/types';
export { HyperliquidAccountType } from './hyperliquid/types';
export { OkxAccountType } from './okx/types';

@@ -22,2 +24,5 @@ function createOrchestrator(exchange, config, credentials) {

break;
case "okx":
orchestrator = new OkxOrchestrator(config, credentials);
break;
default:

@@ -24,0 +29,0 @@ throw new Error(`Unsupported exchange: ${exchange}`);

export { AccountManager } from './account-manager.js';
export { ExchangeAccount } from './exchange-account.js';
export { createOrchestrator } from './exchanges/index.js';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, f as BinanceAccountType, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from '../types-D2dbAtin.js';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, f as BinanceAccountType, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from '../types-Caz2X4h0.js';
export { BybitAccountType } from './exchanges/bybit/types.js';
export { HyperliquidAccountType } from './exchanges/hyperliquid/types.js';
export { OkxAccountType } from './exchanges/okx/types.js';
export { Orchestrator, OrchestratorConfig } from './exchanges/base.js';

@@ -8,0 +9,0 @@ import '@pear-protocol/core-sdk';

import '@pear-protocol/types';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from '../types-D2dbAtin.js';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from '../types-Caz2X4h0.js';
import './exchanges/bybit/types.js';
import './exchanges/hyperliquid/types.js';
import './exchanges/okx/types.js';
import { BinanceAccountType } from './exchanges/binance/types';
import { BybitAccountType } from './exchanges/bybit/types';
import { HyperliquidAccountType } from './exchanges/hyperliquid/types';
import { OkxAccountType } from './exchanges/okx/types';

@@ -15,5 +16,9 @@ const ACCOUNT_TYPE_LABELS = {

[HyperliquidAccountType.PORTFOLIO_MARGIN]: "Portfolio Margin",
[HyperliquidAccountType.UNIFIED_ACCOUNT]: "Unified Account"
[HyperliquidAccountType.UNIFIED_ACCOUNT]: "Unified Account",
[OkxAccountType.SPOT]: "Spot Mode",
[OkxAccountType.SINGLE_CURRENCY_MARGIN]: "Single-Currency Margin",
[OkxAccountType.MULTI_CURRENCY_MARGIN]: "Multi-Currency Margin",
[OkxAccountType.PORTFOLIO_MARGIN]: "Portfolio Margin"
};
export { ACCOUNT_TYPE_LABELS };

@@ -1,5 +0,6 @@

import { E as ExchangeState } from '../types-D2dbAtin.js';
import { E as ExchangeState } from '../types-Caz2X4h0.js';
import '@pear-protocol/types';
import './exchanges/bybit/types.js';
import './exchanges/hyperliquid/types.js';
import './exchanges/okx/types.js';

@@ -6,0 +7,0 @@ declare function createEmptyState(): ExchangeState;

@@ -5,6 +5,7 @@ import PearSDK from '@pear-protocol/core-sdk';

export { createOrchestrator } from './account/exchanges/index.js';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, f as BinanceAccountType, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from './types-D2dbAtin.js';
export { A as ACCOUNT_TYPE_LABELS, a as AccountBalance, b as AccountConfig, c as AccountPosition, d as AccountType, e as AssetBalance, B as BalanceCallback, f as BinanceAccountType, E as ExchangeState, H as HyperliquidAccountCredentials, M as MarginMode, P as PositionsCallback, S as StateUpdate, g as SupportedCredentials, T as TrackedAssetCallback, h as TrackedAssetInfo, i as Tracker } from './types-Caz2X4h0.js';
import { Credentials } from './credentials.js';
export { BybitAccountType } from './account/exchanges/bybit/types.js';
export { HyperliquidAccountType } from './account/exchanges/hyperliquid/types.js';
export { OkxAccountType } from './account/exchanges/okx/types.js';
export { Orchestrator, OrchestratorConfig } from './account/exchanges/base.js';

@@ -11,0 +12,0 @@ import '@pear-protocol/types';

declare function hmacSha256Hex(secret: string, message: string): Promise<string>;
declare function hmacSha256Base64(secret: string, message: string): Promise<string>;
export { hmacSha256Hex };
export { hmacSha256Base64, hmacSha256Hex };
const encoder = new TextEncoder();
async function hmacSha256Hex(secret, message) {
async function sign(secret, message) {
const key = await crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
"sign"
]);
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(message));
return crypto.subtle.sign("HMAC", key, encoder.encode(message));
}
async function hmacSha256Hex(secret, message) {
const signature = await sign(secret, message);
return Array.from(new Uint8Array(signature)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
async function hmacSha256Base64(secret, message) {
const signature = await sign(secret, message);
const bytes = new Uint8Array(signature);
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary);
}
export { hmacSha256Hex };
export { hmacSha256Base64, hmacSha256Hex };
{
"name": "@pear-protocol/exchanges-sdk",
"version": "0.0.13",
"version": "0.0.14",
"description": "Pear Protocol Exchanges SDK",

@@ -5,0 +5,0 @@ "private": false,

@@ -12,2 +12,3 @@ # @pear-protocol/exchanges-sdk

| Hyperliquid | `hyperliquid` | Perpetuals |
| OKX | `okx` | Linear SWAP Perpetuals |

@@ -156,2 +157,7 @@ ## Installation

> **Symbol format per exchange:** `trackAsset` takes the exchange's native symbol:
> - Binance / Bybit: `BTCUSDT`
> - Hyperliquid: `BTC`
> - OKX: `BTC-USDT-SWAP`
### Managing Leverage

@@ -158,0 +164,0 @@

import { Connector, BinanceCredentialsDTO, BybitCredentialsDTO, HyperliquidCredentialsDTO } from '@pear-protocol/types';
import { BybitAccountType } from './account/exchanges/bybit/types.js';
import { HyperliquidAccountType } from './account/exchanges/hyperliquid/types.js';
declare enum BinanceAccountType {
MULTI_ASSET = "MULTI_ASSET",
SINGLE_ASSET = "SINGLE_ASSET"
}
interface BinanceRawPositionRisk {
symbol: string;
leverage: string;
marginType: MarginMode;
isAutoAddMargin: string;
isolatedMargin: string;
positionAmt: string;
entryPrice: string;
breakEvenPrice: string;
unRealizedProfit: string;
liquidationPrice: string;
markPrice: string;
maxNotionalValue: string;
positionSide: string;
notional: string;
isolatedWallet: string;
updateTime: number;
}
interface BinanceRawAsset {
asset: string;
walletBalance: string;
availableBalance: string;
unrealizedProfit: string;
marginBalance: string;
initialMargin: string;
maintMargin: string;
marginAvailable: boolean;
}
interface BinanceRawAccountStatus {
totalWalletBalance: string;
totalMarginBalance: string;
availableBalance: string;
totalUnrealizedProfit: string;
totalInitialMargin: string;
totalMaintMargin: string;
assets?: BinanceRawAsset[];
}
interface BinanceMultiAssetsMarginResponse {
multiAssetsMargin: boolean;
}
interface BinanceAssetIndex {
symbol: string;
time: number;
index: string;
bidBuffer: string;
askBuffer: string;
bidRate: string;
askRate: string;
autoExchangeBidBuffer: string;
autoExchangeAskBuffer: string;
autoExchangeBidRate: string;
autoExchangeAskRate: string;
}
interface BinanceRawUserDataEvent {
e?: string;
ac?: {
s: string;
l: string;
};
a?: {
B?: unknown[];
P?: unknown[];
};
}
interface BinanceWsHandlers {
onUserDataEvent: (event: unknown) => void;
onWsApiResponse: (id: number, result: unknown) => void;
}
type MarginMode = 'cross' | 'isolated';
type AccountType = BinanceAccountType | BybitAccountType | HyperliquidAccountType;
declare const ACCOUNT_TYPE_LABELS: Record<AccountType, string>;
interface AssetBalance {
asset: string;
free: string;
used: string;
total: string;
walletBalance: string;
usdValue: string;
}
interface AccountBalance {
accountType: AccountType;
free: Record<string, string>;
used: Record<string, string>;
total: Record<string, string>;
availableToTrade: string;
totalEquity: string;
walletBalance: string;
unrealizedPnl: string;
initialMarginUsed: string;
maintenanceMargin: string;
marginRatio: string;
assets: AssetBalance[];
timestamp: number;
}
interface AccountPosition {
symbol: string;
side: 'long' | 'short' | 'both';
size: string;
entryPrice: string;
unrealizedPnl: string;
leverage: string;
marginType: MarginMode;
liquidationPrice: string | null;
}
interface TrackedAssetInfo {
coin: string;
leverage: string;
marginType: MarginMode;
}
interface ExchangeState {
balance: AccountBalance | null;
positions: Map<string, AccountPosition>;
leverageSettings: Map<string, string>;
trackedAssets: Map<string, TrackedAssetInfo>;
lastUpdated: number;
initialized: boolean;
}
type BalanceCallback = (balance: AccountBalance) => void;
type PositionsCallback = (positions: AccountPosition[]) => void;
type TrackedAssetCallback = (info: TrackedAssetInfo) => void;
interface Tracker<T> {
get(): T;
untrack(): void;
}
interface AccountConfig {
exchange: Connector;
demo?: boolean;
onAuthError?: () => void;
}
type HyperliquidAccountCredentials = HyperliquidCredentialsDTO & {
address: string;
};
type SupportedCredentials = BinanceCredentialsDTO | BybitCredentialsDTO | HyperliquidAccountCredentials;
interface StateUpdate {
balance?: AccountBalance;
positions?: Map<string, AccountPosition>;
leverageSettings?: Map<string, string>;
trackedAssets?: Map<string, TrackedAssetInfo>;
}
export { ACCOUNT_TYPE_LABELS as A, type BalanceCallback as B, type ExchangeState as E, type HyperliquidAccountCredentials as H, type MarginMode as M, type PositionsCallback as P, type StateUpdate as S, type TrackedAssetCallback as T, type AccountBalance as a, type AccountConfig as b, type AccountPosition as c, type AccountType as d, type AssetBalance as e, BinanceAccountType as f, type SupportedCredentials as g, type TrackedAssetInfo as h, type Tracker as i, type BinanceRawAccountStatus as j, type BinanceRawPositionRisk as k, type BinanceAssetIndex as l, type BinanceRawUserDataEvent as m, type BinanceWsHandlers as n, type BinanceMultiAssetsMarginResponse as o, type BinanceRawAsset as p };